You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(orm): respect the log option of clients derived with $setOptions - #2902
A client derived with $setOptions (like every derived client) reuses the base client's ZenStackDriver. That driver adds logging by patching each pooled connection the first time it's acquired, only if the base client's log enables it, and always logs with the base client's Log. So $setOptions({ ...db.$options, log }) could not turn logging on, switch to another logger, or turn it off.
The pool-level state (underlying driver, init/destroy lifecycle, sqlite connection mutex, transaction bookkeeping) is kept in one shared state object. withLog(log) returns a driver over the same state with its own Log, so derived clients keep sharing one connection pool.
When a driver acquires a connection, it records its log for that connection. Kysely drivers hand out a connection to one holder at a time until it's released, so queries on it are logged with the log of the client that acquired it.
A connection is patched once, the first time a driver with logging enabled acquires it (previously a connection first acquired without logging was never patched). The patched methods read the connection's current log on each query and skip timing and logging when nothing is enabled.
client-impl.ts: a derived client whose log option differs from its base (identity check) uses withLog(new Log(options.log ?? [])) for its executor and its $qbRaw Kysely instance. $use, $setAuth, $transaction and similar keep the same log reference, so they keep the base driver as before.
Known limitation: calling $setOptions with a different log on a client inside an interactive transaction still logs that transaction's queries with the logger that started it, because those queries run on the connection the transaction already holds.
Overlap with #2899: both PRs change the connection provider argument in the derived-client branch of client-impl.ts. Whichever lands second can combine them as baseClient.isTransaction ? (baseClient.transactionConnection ?? baseClient.$qb.getExecutor()) : new DefaultConnectionProvider(driver), with the executor taking driver.
Validation
New tests/regression/test/issue-2355.test.ts covers:
enabling, switching and disabling logging with $setOptions
logging on transactions started from the derived client and on $qbRaw
failed queries logged with level error
concurrent queries from a base and a derived client going to their own loggers
clients derived without changing log keeping the base logger
Without the change, 7 of the 8 tests fail in 3 of 3 runs; with it, all 8 pass in 3 of 3 runs.
tests/e2e ORM suites that create derived clients and use the driver (client-api/transaction, raw-query, slicing, omit, error-handling, plugin-infra/*): 183 passed before and after. packages/orm unit tests: 7 passed before and after.
@zenstackhq/orm lint and build (tsc + tsdown), tsc for tests/regression and prettier on the changed files pass.
Ran on SQLite only (Node 24, pnpm 10.33.0, in a container). The PostgreSQL and MySQL legs of the CI matrix were not run locally.
Review notes
Before opening this PR, the diff, the issue and the test results went through an independent review. It found no blockers. Changes made from it:
The error test uses a unique-constraint violation instead of a quoted raw query, so it is portable to MySQL and PostgreSQL.
Setup queries from createTestClient are cleared before assertions.
Tests were added for $qbRaw and for concurrent base and derived queries.
withLog reuses the shared state instead of building a throwaway one.
CodeRabbit pointed out that pg-pool can hand a released connection to a queued acquisition before releaseConnection returns. That acquisition can run queries on it (for example a dialect's onReserveConnection hook) while the previous holder's log is still recorded for the connection. This is fixed in 07264a9: the recorded log is now cleared before the connection is released. After that commit:
the regression tests pass (8 of 8, 3 of 3 runs);
the e2e ORM suites listed above pass (183 of 183) and the packages/orm unit tests pass (7 of 7);
lint and prettier pass.
The workflow runs are waiting for maintainer approval (first-time contributor).
This change was written with help from an AI coding assistant (Claude Code).
Summary by CodeRabbit
Bug Fixes
Query logging now respects logging options configured on derived clients, including when logging is enabled or disabled. Queries, transactions, raw queries, and failed operations are logged by the client that runs them, with concurrent queries kept separate.
Derived clients that retain the base client’s logging options continue to share its logging behavior.
Logged queries and streams include their execution duration.
Derived clients reused the base client's ZenStackDriver, which patches
pooled connections for logging only if the base client's log enables it
and always logs with the base client's Log, so `$setOptions` couldn't
enable, change or disable logging.
ZenStackDriver now keeps its pool-level state (underlying driver,
lifecycle, sqlite mutex, transaction bookkeeping) in a shared object.
`withLog()` creates a driver over the same state with its own Log. The
acquiring driver's log is recorded per connection, and patched
connections look it up on each query. A derived client whose `log`
differs from its base uses `withLog()` for its executor and `$qbRaw`.
Fixeszenstackhq#2355
No actionable comments were generated in the recent review.
Walkthrough
Derived clients now use their own logger when their log option differs from the base client’s. They share driver state and connections. Regression tests cover logging across queries, transactions, errors, and concurrent base and derived client operations.
Changes: Derived-client logging
Layer / File(s)
Summary
Shared driver state packages/orm/src/client/executor/zenstack-driver.ts
ZenStackDriver stores driver, lifecycle, connection, and transaction state in shared state that logger-specific driver instances can reuse.
Connection acquisition associates the current driver’s logger with the connection. Query and stream wrappers use that logger to report errors and successful operations with duration data.
When the log option differs from the base client’s, the derived client uses a logger-specific driver and raw Kysely instance. Otherwise, it reuses the base instances.
zenstackhq/zenstack#2899: Both changes affect derived-client connection routing and use the connection-provider code path.
Suggested reviewers:ymc9
Merge Risk: Minimal · up to 8b2d7
This change makes logging options set through $setOptions take effect on derived clients while they continue to share driver state and connections. No outstanding defects were identified, and regression tests cover the main logging scenarios.
Pre-merge checks: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title names the main change: clients derived with $setOptions now honor a changed log option. The raw summary shows derived ClientImpl instances building their own ZenStackDriver with the new log,…
Linked Issues check
Issue #2355 requires $setOptions to make logging effective when it enables, switches, or disables logging. The previous review found this covered at the reviewed head. The head commit 8b2d7b2 is a m…
Out of Scope Changes check
The previous review found that all changed production code and the regression test serve #2355. The incremental diff since the previous reviewed head does not change zenstack-driver.ts. The head com…
Full details: Title check
Explanation
The title names the main change: clients derived with $setOptions now honor a changed log option. The raw summary shows derived ClientImpl instances building their own ZenStackDriver with the new log, and the regression tests cover logging set through $setOptions. The title is specific and matches the linked issue #2355 and the PR objectives. The title is 68 characters, which fits the concise single-sentence expectation.
Full details: Linked Issues check
Explanation
Issue #2355 requires $setOptions to make logging effective when it enables, switches, or disables logging. The previous review found this covered at the reviewed head. The head commit 8b2d7b2 is a merge of dev into the PR branch. A focused diff of packages/orm/src/client/executor/zenstack-driver.ts from the previous reviewed head to head shows no changes, so the driver mechanism that satisfies the requirement is unchanged since the previous review. The per-connection log recording, one-time patching, and clearing of the recorded log before release remain in place. The client-impl.ts derived-client branch was not re-read in this pass. The new commits came from the dev merge, which brings in base-branch changes that are not PR-specific. The regression tests in tests/regression/test/issue-2355.test.ts were not read directly in either review. The known transaction-client limitation is outside the stated requirement. No non-coding requirement exists in the linked issue.
Full details: Out of Scope Changes check
Explanation
The previous review found that all changed production code and the regression test serve #2355. The incremental diff since the previous reviewed head does not change zenstack-driver.ts. The head commit is a merge of dev, which adds base-branch commits such as #2901, #2909, #2897, #2910, #2890, #2889, #2898, and version bumps. These commits belong to other work and are inherited from the base branch, not introduced by this PR. Their presence in the merge does not make the PR's own changes out of scope. The client-impl.ts diff was not re-read in this pass, so its scope rests on the previous review.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Reviewing files that changed from the base of the PR and between 07264a9 and 8b2d7b2.
Files selected for processing: 1
packages/orm/src/client/client-impl.ts
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
A pool can hand a released connection to a queued acquisition during
release (pg-pool resolves the waiting request right away), and queries
run on it before that acquisition records its own log, such as a
dialect's onReserveConnection hook, were logged with the previous
holder's log. Drop the recorded log before releasing the connection.
Reported by CodeRabbit in review.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #2355.
A client derived with
$setOptions(like every derived client) reuses the base client'sZenStackDriver. That driver adds logging by patching each pooled connection the first time it's acquired, only if the base client'slogenables it, and always logs with the base client'sLog. So$setOptions({ ...db.$options, log })could not turn logging on, switch to another logger, or turn it off.Changes
zenstack-driver.tswithLog(log)returns a driver over the same state with its ownLog, so derived clients keep sharing one connection pool.client-impl.ts: a derived client whoselogoption differs from its base (identity check) useswithLog(new Log(options.log ?? []))for its executor and its$qbRawKysely instance.$use,$setAuth,$transactionand similar keep the samelogreference, so they keep the base driver as before.Known limitation: calling
$setOptionswith a differentlogon a client inside an interactive transaction still logs that transaction's queries with the logger that started it, because those queries run on the connection the transaction already holds.Overlap with #2899: both PRs change the connection provider argument in the derived-client branch of
client-impl.ts. Whichever lands second can combine them asbaseClient.isTransaction ? (baseClient.transactionConnection ?? baseClient.$qb.getExecutor()) : new DefaultConnectionProvider(driver), with the executor takingdriver.Validation
New
tests/regression/test/issue-2355.test.tscovers:$setOptions$qbRawerrorlogkeeping the base loggerWithout the change, 7 of the 8 tests fail in 3 of 3 runs; with it, all 8 pass in 3 of 3 runs.
tests/e2eORM suites that create derived clients and use the driver (client-api/transaction,raw-query,slicing,omit,error-handling,plugin-infra/*): 183 passed before and after.packages/ormunit tests: 7 passed before and after.@zenstackhq/ormlint and build (tsc+ tsdown),tscfortests/regressionand prettier on the changed files pass.Ran on SQLite only (Node 24, pnpm 10.33.0, in a container). The PostgreSQL and MySQL legs of the CI matrix were not run locally.
Review notes
createTestClientare cleared before assertions.$qbRawand for concurrent base and derived queries.withLogreuses the shared state instead of building a throwaway one.releaseConnectionreturns. That acquisition can run queries on it (for example a dialect'sonReserveConnectionhook) while the previous holder's log is still recorded for the connection. This is fixed in 07264a9: the recorded log is now cleared before the connection is released. After that commit:packages/ormunit tests pass (7 of 7);This change was written with help from an AI coding assistant (Claude Code).
Summary by CodeRabbit