Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Jul 9, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced transaction support, including interactive and sequential transaction modes, with improved rollback and commit behavior.
    • Added support for the Json scalar type and array fields in database operations and queries.
    • Introduced a new CLI binary alias for easier access.
  • Improvements

    • Improved error messages and input validation for clearer diagnostics.
    • Normalized input arguments by stripping undefined values for more robust query handling.
    • Refined relation handling and selection, including nested and filtered relation counts.
    • Enhanced plugin and lifecycle hook handling for better extensibility.
    • Expanded test coverage for transactions, scalar types, array fields, and undefined values.
  • Bug Fixes

    • Fixed issues with relation creation and type-checking to align with expected typing behavior.
    • Addressed transformation and processing of JSON and array types for consistent results.
  • Chores

    • Updated package versions to 3.0.0-alpha.9 across all packages.
    • Adjusted build and TypeScript configurations to include tests and streamline entry points.
    • Updated documentation and TODOs to reflect recent changes.
  • Style

    • Minor formatting and stylistic updates for consistency.
  • Tests

    • Added and updated tests for transactions, type coverage, undefined values, and plugin hooks.
    • Skipped or commented out certain transaction-related tests pending further review.

ymc9 and others added 8 commits July 3, 2025 09:06
* fix: issues found testing with formbricks

- Nested count during find
- Result processing
- "undefined" field normalization
- Enum fields used as unique

* fix test

* more tests

* fix test
- Nested transaction handling
- Fixed issue with concurrent transactions
- Temporarily disabled running Kysely query interceptor in a transaction
Co-authored-by: ymc9 <104139426+ymc9@users.noreply.github.com>
* feat: implement sequential transaction

* Update packages/runtime/src/client/client-impl.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* addressing comments

* update tests

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings July 9, 2025 09:20
@coderabbitai
Copy link

coderabbitai bot commented Jul 9, 2025

Walkthrough

This update introduces comprehensive enhancements to transaction handling, type coverage, and JSON support in the runtime client. It refactors promise and transaction APIs, adds normalization for input arguments, supports new scalar types (Json, Unsupported), and improves error handling and test coverage. Numerous package versions are incremented to 3.0.0-alpha.9.

Changes

Files/Paths Change Summary
.coderabbit.yaml Added sequence_diagrams: false to config.
TODO.md Marked "Raw queries" as done, added "Transactions" and "Plugin" sections.
package.json, samples/blog/package.json, tests/e2e/package.json, other package.json files Bumped version to 3.0.0-alpha.9.
packages/cli/bin/cli, packages/create-zenstack/bin/cli Removed --no-warnings from Node.js shebang.
packages/cli/package.json Bumped version, added zen binary alias.
packages/runtime/src/client/client-impl.ts Refactored for enhanced transaction support, new promise type, executor injection, and overloads.
packages/runtime/src/client/contract.ts Switched to ZenStackPromise for async methods, added transaction overloads, and isolation level enum.
packages/runtime/src/client/crud-types.ts Renamed CreateManyPayload to CreateManyInput, added non-owned relation support.
packages/runtime/src/client/crud/dialects/base.ts, .../postgresql.ts, .../sqlite.ts Updated transformPrimitive to accept array context, improved error handling for unsupported types.
packages/runtime/src/client/crud/operations/* Added normalization of input args, improved error handling, refactored relation processing, and enhanced transaction logic.
packages/runtime/src/client/crud/validator.ts Improved error handling, schema validation, and support for new types.
packages/runtime/src/client/errors.ts Added InputValidationError, improved error constructors and documentation.
packages/runtime/src/client/executor/zenstack-query-executor.ts Removed internal transaction management, improved error reporting, and mutation hook logic.
packages/runtime/src/client/helpers/schema-db-pusher.ts Added support for mapping Json fields to PostgreSQL jsonb.
packages/runtime/src/client/options.ts Added optional debug property to ClientOptions.
packages/runtime/src/client/plugin.ts Made plugin hooks async, removed transaction-related properties.
packages/runtime/src/client/promise.ts Introduced ZenStackPromise, refactored deferred promise logic.
packages/runtime/src/client/query-utils.ts Improved error messages with model context.
packages/runtime/src/client/result-processor.ts Added JSON transformation, improved relation result handling.
packages/runtime/src/index.ts Changed to export all from ./client.
packages/runtime/src/plugins/policy/* Updated for new transaction and primitive transformation signatures.
packages/runtime/src/utils/type-utils.ts Added UnwrapTuplePromises type.
packages/runtime/test/client-api/*, test/plugin/* Added/updated tests for transactions, type coverage, JSON, undefined values, and array support. Adjusted or commented out transaction-related plugin tests.
packages/runtime/tsconfig.json Included both src/**/* and test/**/* in compilation.
packages/runtime/tsup.config.ts Removed client entry point from build config.
packages/sdk/src/schema/schema.ts Added 'Json' and 'Unsupported' to BuiltinType.
packages/sdk/src/ts-schema-generator.ts Changed fallback type string to 'Unsupported'.
packages/tanstack-query/src/react.ts Updated import path for types.
packages/runtime/test/typing/schema.ts Stylistic changes only (quotes, formatting).

Possibly related PRs

  • zenstackhq/zenstack-v3#81: Both PRs refactor the ClientImpl class, enhancing sequential transaction support and promise handling, and introduce TRANSACTION_UNSUPPORTED_METHODS.
  • zenstackhq/zenstack-v3#74: Both PRs update the transformPrimitive method signature and usage across dialects, improving primitive value transformation logic.
  • zenstackhq/zenstack-v3#73: Both PRs add support for Json and Unsupported types, updating type definitions, validation, and result processing.

Poem

🐇
In burrows deep, where data flows,
Transactions bloom and promise grows.
JSON fields now join the crew,
Arrays and types get coverage too!
With errors clear and tests anew,
This patch brings features, strong and true—
Hopping forward, code review!

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/runtime/src/client/client-impl.ts

Oops! Something went wrong! :(

ESLint: 9.29.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

packages/runtime/src/client/constants.ts

Oops! Something went wrong! :(

ESLint: 9.29.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

packages/runtime/src/client/contract.ts

Oops! Something went wrong! :(

ESLint: 9.29.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

  • 40 others
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR merges the dev branch into main, bumping all package versions from 3.0.0-alpha.8 to 3.0.0-alpha.9 and introducing first-class JSON support, enhanced transaction APIs, and improved error handling across the runtime.

  • Add Json and Unsupported to BuiltinType and wire JSON serialization/deserialization throughout dialects, result processing, and schema generator
  • Overhaul $transaction to support interactive and sequential modes via ZenStackPromise, plus normalization of undefined args
  • Refactor policy plugin to defer transaction support and update error messages, input validation, and diagnostics

Reviewed Changes

Copilot reviewed 63 out of 65 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
packages/*/package.json Bumped versions to 3.0.0-alpha.9
packages/sdk/src/schema/schema.ts Extended BuiltinType with Json and Unsupported
packages/sdk/src/ts-schema-generator.ts Emit 'Unsupported' literal instead of 'unknown'
packages/runtime/src/client/crud/dialects/*.ts Transform and filter JSON values in SQLite/Postgres
packages/runtime/src/client/result-processor.ts Added .with('Json', ...) to handle JSON in results
packages/runtime/src/utils/type-utils.ts Introduced UnwrapTuplePromises
packages/runtime/src/client/promise.ts Renamed and expanded deferred promise to ZenStackPromise
packages/runtime/src/client/client-impl.ts Overloaded $transaction, added interactive/sequential modes
packages/runtime/src/client/crud/validator.ts Allow JSON in filters but mark unsupported in dialect
packages/runtime/src/plugins/policy/policy-handler.ts Stub out transactional enforcement and leave TODO blocks
packages/runtime/test/* New and updated E2E and unit tests for JSON, undefined args, transactions
Comments suppressed due to low confidence (2)

packages/runtime/test/plugin/query-lifecycle.test.ts:258

  • Key transaction behavior tests are being skipped. Consider re-enabling or replacing these tests to ensure transactional hooks continue to work as expected.
    it.skip('rolls back the effect with transaction', async () => {

packages/runtime/src/client/client-impl.ts:157

  • [nitpick] The $transaction overloads for interactive vs. sequential modes introduce complexity. Adding JSDoc comments explaining each overload and example usage would help API consumers understand when to use each form.
    ): Promise<T>;

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🔭 Outside diff range comments (1)
packages/runtime/src/plugins/policy/policy-handler.ts (1)

57-103: Removal of transaction support raises data consistency concerns.

The removal of transaction wrapping means that policy enforcement and mutations are no longer atomic. This could lead to race conditions where:

  • Pre-create policy checks pass but the insert fails
  • Mutations succeed but read-back fails, leaving orphaned data
  • Concurrent modifications between policy check and execution cause inconsistent results

Consider the implications of removing transactional guarantees. If this is intentional, document the rationale and potential risks. The TODO comment suggests this might be temporary - if so, track this technical debt properly.

♻️ Duplicate comments (4)
packages/ide/vscode/package.json (1)

4-4: Same release-process checklist applies

See the checklist in the SDK package review to keep the extension version, tag, and marketplace publication in sync.

packages/common-helpers/package.json (1)

3-3: Same release-process checklist applies

See the checklist in the SDK package review.

packages/zod/package.json (1)

3-3: Same release-process checklist applies

See the checklist in the SDK package review.

packages/tanstack-query/package.json (1)

3-3: Same release-process checklist applies

See the checklist in the SDK package review.

🧹 Nitpick comments (9)
TODO.md (2)

54-57: Fix markdown list indentation for consistency.

The static analysis tool correctly identifies indentation inconsistencies in the markdown list structure. Please adjust the indentation to maintain consistent formatting.

Apply this diff to fix the indentation:

-    - [x] Raw queries
-    - [ ] Transactions
-        - [x] Interactive transaction
-        - [x] Sequential transaction
+  - [x] Raw queries
+  - [ ] Transactions
+    - [x] Interactive transaction
+    - [x] Sequential transaction

75-76: Fix markdown list indentation for the Plugin section.

The indentation for the Plugin section also needs adjustment to maintain consistency.

Apply this diff to fix the indentation:

-    - [ ] Post-mutation hooks should be called after transaction is committed
+  - [ ] Post-mutation hooks should be called after transaction is committed
packages/runtime/src/client/crud/operations/create.ts (1)

10-11: Rename variable for clarity.

The variable should be named normalizedArgs instead of normalizeArgs since it contains the result of normalization, not the normalization function itself.

-        // normalize args to strip `undefined` fields
-        const normalizeArgs = this.normalizeArgs(args);
+        // normalize args to strip `undefined` fields
+        const normalizedArgs = this.normalizeArgs(args);
packages/runtime/src/client/crud/operations/aggregate.ts (1)

9-10: Rename variable for clarity.

Same naming issue as in create.ts - the variable should be normalizedArgs instead of normalizeArgs.

-        // normalize args to strip `undefined` fields
-        const normalizeArgs = this.normalizeArgs(args);
+        // normalize args to strip `undefined` fields
+        const normalizedArgs = this.normalizeArgs(args);
packages/runtime/src/client/crud/operations/count.ts (1)

7-8: Rename variable for clarity.

Same naming issue as in other files - the variable should be normalizedArgs instead of normalizeArgs.

-        // normalize args to strip `undefined` fields
-        const normalizeArgs = this.normalizeArgs(args);
+        // normalize args to strip `undefined` fields
+        const normalizedArgs = this.normalizeArgs(args);
packages/runtime/src/client/crud/dialects/base.ts (1)

40-42: Consider removing or implementing the unused _forArrayField parameter.

The _forArrayField parameter is prefixed with underscore indicating it's unused. If this is intended for future use, consider adding a TODO comment explaining the planned usage. Otherwise, consider removing it until it's actually needed.

packages/runtime/test/client-api/type-coverage.test.ts (1)

86-89: Consider adding explanatory comments for skipped tests.

The array type tests are correctly skipped for SQLite, but it would be helpful to add a comment explaining why.

 it('supports all types - array', async () => {
     if (provider === 'sqlite') {
+        // SQLite doesn't support array types natively
         return;
     }

Same applies to line 134-136.

Also applies to: 133-136

packages/runtime/src/client/crud/validator.ts (1)

409-410: Appropriate handling of new scalar types.

The implementation correctly handles the newly added Json and Unsupported types. The TODO comment indicates JSON filters are planned for future implementation.

Would you like me to help implement JSON filter support or create an issue to track this enhancement?

packages/runtime/src/client/crud/operations/base.ts (1)

1940-1963: Useful input normalization for consistent handling.

The normalizeArgs method provides valuable input sanitization by recursively removing undefined fields, which can prevent issues with database operations.

Consider memoizing the normalization for frequently used argument patterns to avoid repeated cloning and traversal:

+private argsNormalizationCache = new WeakMap<object, object>();
+
 protected normalizeArgs(args: unknown) {
     if (!args) {
         return;
     }
+    if (typeof args === 'object' && this.argsNormalizationCache.has(args)) {
+        return this.argsNormalizationCache.get(args);
+    }
     const newArgs = clone(args);
     this.doNormalizeArgs(newArgs);
+    if (typeof args === 'object') {
+        this.argsNormalizationCache.set(args, newArgs);
+    }
     return newArgs;
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d3e56be and 5a746d9.

📒 Files selected for processing (65)
  • .coderabbit.yaml (1 hunks)
  • TODO.md (2 hunks)
  • package.json (1 hunks)
  • packages/cli/bin/cli (1 hunks)
  • packages/cli/package.json (2 hunks)
  • packages/common-helpers/package.json (1 hunks)
  • packages/create-zenstack/bin/cli (1 hunks)
  • packages/create-zenstack/package.json (1 hunks)
  • packages/eslint-config/package.json (1 hunks)
  • packages/ide/vscode/package.json (1 hunks)
  • packages/language/package.json (1 hunks)
  • packages/runtime/package.json (1 hunks)
  • packages/runtime/src/client/client-impl.ts (11 hunks)
  • packages/runtime/src/client/constants.ts (1 hunks)
  • packages/runtime/src/client/contract.ts (24 hunks)
  • packages/runtime/src/client/crud-types.ts (5 hunks)
  • packages/runtime/src/client/crud/dialects/base.ts (8 hunks)
  • packages/runtime/src/client/crud/dialects/postgresql.ts (4 hunks)
  • packages/runtime/src/client/crud/dialects/sqlite.ts (1 hunks)
  • packages/runtime/src/client/crud/operations/aggregate.ts (4 hunks)
  • packages/runtime/src/client/crud/operations/base.ts (20 hunks)
  • packages/runtime/src/client/crud/operations/count.ts (1 hunks)
  • packages/runtime/src/client/crud/operations/create.ts (1 hunks)
  • packages/runtime/src/client/crud/operations/delete.ts (1 hunks)
  • packages/runtime/src/client/crud/operations/find.ts (1 hunks)
  • packages/runtime/src/client/crud/operations/group-by.ts (4 hunks)
  • packages/runtime/src/client/crud/operations/update.ts (1 hunks)
  • packages/runtime/src/client/crud/validator.ts (10 hunks)
  • packages/runtime/src/client/errors.ts (1 hunks)
  • packages/runtime/src/client/executor/zenstack-query-executor.ts (14 hunks)
  • packages/runtime/src/client/helpers/schema-db-pusher.ts (1 hunks)
  • packages/runtime/src/client/options.ts (1 hunks)
  • packages/runtime/src/client/plugin.ts (2 hunks)
  • packages/runtime/src/client/promise.ts (2 hunks)
  • packages/runtime/src/client/query-utils.ts (2 hunks)
  • packages/runtime/src/client/result-processor.ts (3 hunks)
  • packages/runtime/src/index.ts (1 hunks)
  • packages/runtime/src/plugins/policy/expression-transformer.ts (1 hunks)
  • packages/runtime/src/plugins/policy/plugin.ts (1 hunks)
  • packages/runtime/src/plugins/policy/policy-handler.ts (4 hunks)
  • packages/runtime/src/plugins/policy/utils.ts (1 hunks)
  • packages/runtime/src/utils/type-utils.ts (1 hunks)
  • packages/runtime/test/client-api/create.test.ts (1 hunks)
  • packages/runtime/test/client-api/find.test.ts (3 hunks)
  • packages/runtime/test/client-api/raw-query.test.ts (1 hunks)
  • packages/runtime/test/client-api/transaction.test.ts (1 hunks)
  • packages/runtime/test/client-api/type-coverage.test.ts (2 hunks)
  • packages/runtime/test/client-api/undefined-values.test.ts (1 hunks)
  • packages/runtime/test/plugin/kysely-on-query.test.ts (3 hunks)
  • packages/runtime/test/plugin/mutation-hooks.test.ts (3 hunks)
  • packages/runtime/test/plugin/query-lifecycle.test.ts (1 hunks)
  • packages/runtime/test/typing/schema.ts (1 hunks)
  • packages/runtime/tsconfig.json (1 hunks)
  • packages/runtime/tsconfig.test.json (0 hunks)
  • packages/runtime/tsup.config.ts (0 hunks)
  • packages/sdk/package.json (1 hunks)
  • packages/sdk/src/schema/schema.ts (1 hunks)
  • packages/sdk/src/ts-schema-generator.ts (1 hunks)
  • packages/tanstack-query/package.json (1 hunks)
  • packages/tanstack-query/src/react.ts (1 hunks)
  • packages/testtools/package.json (1 hunks)
  • packages/typescript-config/package.json (1 hunks)
  • packages/zod/package.json (1 hunks)
  • samples/blog/package.json (1 hunks)
  • tests/e2e/package.json (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/runtime/tsconfig.test.json
  • packages/runtime/tsup.config.ts
🧰 Additional context used
🧬 Code Graph Analysis (18)
packages/runtime/test/client-api/raw-query.test.ts (1)
packages/runtime/test/client-api/client-specs.ts (1)
  • createClientSpecs (6-42)
packages/runtime/src/plugins/policy/utils.ts (1)
packages/sdk/src/schema/schema.ts (1)
  • SchemaDef (10-17)
packages/runtime/src/client/crud/operations/find.ts (1)
packages/runtime/src/client/crud/operations/base.ts (1)
  • normalizeArgs (1943-1950)
packages/runtime/src/client/query-utils.ts (1)
packages/runtime/src/client/errors.ts (1)
  • QueryError (13-17)
packages/runtime/src/client/crud/operations/aggregate.ts (1)
packages/runtime/src/client/crud/operations/base.ts (1)
  • normalizeArgs (1943-1950)
packages/runtime/src/client/crud/operations/group-by.ts (1)
packages/runtime/src/client/crud/operations/base.ts (1)
  • normalizeArgs (1943-1950)
packages/runtime/test/client-api/undefined-values.test.ts (3)
packages/runtime/test/client-api/client-specs.ts (1)
  • createClientSpecs (6-42)
packages/runtime/test/typing/schema.ts (1)
  • schema (9-246)
packages/runtime/test/client-api/utils.ts (1)
  • createUser (6-21)
packages/runtime/src/client/crud/dialects/sqlite.ts (2)
packages/sdk/src/schema/schema.ts (1)
  • BuiltinType (76-86)
packages/language/src/generated/ast.ts (1)
  • BuiltinType (100-100)
packages/runtime/src/client/crud/operations/delete.ts (1)
packages/runtime/src/client/crud/operations/base.ts (1)
  • normalizeArgs (1943-1950)
packages/runtime/src/client/crud/operations/update.ts (1)
packages/runtime/src/client/crud/operations/base.ts (1)
  • normalizeArgs (1943-1950)
packages/runtime/src/client/crud/operations/create.ts (1)
packages/runtime/src/client/crud/operations/base.ts (1)
  • normalizeArgs (1943-1950)
packages/runtime/src/client/crud/operations/count.ts (1)
packages/runtime/src/client/crud/operations/base.ts (1)
  • normalizeArgs (1943-1950)
packages/runtime/src/client/plugin.ts (1)
packages/runtime/src/client/contract.ts (1)
  • ModelOperations (210-762)
packages/runtime/src/client/result-processor.ts (2)
packages/sdk/src/schema/schema.ts (1)
  • GetModels (94-94)
packages/common-helpers/src/tiny-invariant.ts (1)
  • invariant (4-14)
packages/runtime/src/client/crud/validator.ts (5)
packages/runtime/src/client/errors.ts (2)
  • InputValidationError (4-8)
  • QueryError (13-17)
packages/common-helpers/src/tiny-invariant.ts (1)
  • invariant (4-14)
packages/runtime/src/client/query-utils.ts (1)
  • getEnum (181-183)
packages/sdk/src/schema/schema.ts (1)
  • BuiltinType (76-86)
packages/language/src/generated/ast.ts (1)
  • BuiltinType (100-100)
packages/runtime/src/client/crud/dialects/postgresql.ts (5)
packages/sdk/src/schema/schema.ts (2)
  • BuiltinType (76-86)
  • GetModels (94-94)
packages/language/src/generated/ast.ts (1)
  • BuiltinType (100-100)
packages/runtime/src/client/query-utils.ts (3)
  • requireField (30-36)
  • buildFieldRef (149-171)
  • isRelationField (109-112)
packages/runtime/src/client/crud/operations/base.ts (1)
  • requireField (118-120)
packages/runtime/src/client/crud-types.ts (1)
  • FindArgs (495-514)
packages/runtime/src/client/crud-types.ts (1)
packages/sdk/src/schema/schema.ts (5)
  • SchemaDef (10-17)
  • GetModels (94-94)
  • RelationFieldType (155-159)
  • RelationFields (145-147)
  • GetField (107-111)
packages/runtime/src/client/contract.ts (3)
packages/runtime/src/client/constants.ts (1)
  • TRANSACTION_UNSUPPORTED_METHODS (14-14)
packages/runtime/src/client/promise.ts (1)
  • ZenStackPromise (7-13)
packages/runtime/src/utils/type-utils.ts (1)
  • UnwrapTuplePromises (72-74)
🪛 markdownlint-cli2 (0.17.2)
TODO.md

54-54: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


55-55: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)


56-56: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


57-57: Unordered list indentation
Expected: 4; Actual: 8

(MD007, ul-indent)


76-76: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

🪛 Biome (1.9.4)
packages/runtime/src/client/errors.ts

[error] 23-25: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (77)
.coderabbit.yaml (1)

4-8: sequence_diagrams key is correctly added at the reviews level – looks good.
The indentation keeps it sibling to auto_review, matching the schema (reviews → sequence_diagrams). No further changes required.

package.json (1)

3-3: Version bump looks good; don’t forget accompanying release artifacts

3.0.0-alpha.9 keeps the monorepo in sync. Please double-check that:
CHANGELOG.md (or equivalent) is updated
• a matching git tag will be pushed during the release workflow

packages/typescript-config/package.json (1)

3-3: Consistent package version

Nothing else changed—LGTM.

packages/eslint-config/package.json (1)

3-3: LGTM – version bump only.

tests/e2e/package.json (1)

3-3: E2E package version aligned

No issues.

samples/blog/package.json (1)

3-3: Sample project version updated

All good; dependencies still use workspace:*.

packages/sdk/package.json (1)

3-3: Confirm release artifacts & downstream workspace resolution

The version bump to 3.0.0-alpha.9 looks fine, but please double-check that:

  1. A corresponding changelog entry / git tag exists.
  2. All workspace packages that depend on @zenstackhq/sdk resolve the new version without lock-file drift (pnpm -r why @zenstackhq/sdk).
packages/testtools/package.json (1)

3-3: Version bump is consistent – good to merge
The 3.0.0-alpha.9 bump keeps @zenstackhq/testtools in sync with the rest of the workspace. No other changes detected.

packages/language/package.json (1)

4-4: Version alignment acknowledged
@zenstackhq/language now targets 3.0.0-alpha.9, maintaining internal version harmony. Nothing else to flag.

packages/runtime/package.json (1)

3-3: Runtime v3.0.0-alpha.9 bump – no deprecated client sub-path imports found
A search for @zenstackhq/runtime/client (ESM imports and CommonJS requires) across the repo returned no matches. The ./client export removal has no remaining consumers.

• packages/runtime/package.json (line 3): updated version to 3.0.0-alpha.9

packages/create-zenstack/package.json (1)

3-3: Package follows monorepo version bump
create-zenstack correctly moved to 3.0.0-alpha.9. No concerns.

packages/create-zenstack/bin/cli (1)

1-1: Removal of --no-warnings is reasonable
Letting Node display warnings will surface potential issues early. Keep an eye on noisy output in CI logs, but this change is generally positive.

packages/tanstack-query/src/react.ts (1)

8-8: LGTM: Import path updated to reflect runtime package restructuring.

The import path change from @zenstackhq/runtime/client to @zenstackhq/runtime aligns with the broader restructuring where client-related types are now re-exported from the main runtime package entry point.

packages/cli/bin/cli (1)

1-1: Good change: Enabling Node.js warnings for better visibility.

Removing the --no-warnings flag allows developers to see important runtime warnings that could indicate potential issues or deprecated API usage.

packages/runtime/test/client-api/raw-query.test.ts (1)

8-8: LGTM: Simplified test client configuration.

Removing the logQueries parameter (which was set to true) means query logging is now disabled by default, resulting in cleaner test output while maintaining the same test functionality.

packages/cli/package.json (2)

6-6: LGTM: Version bump aligns with coordinated release.

The version update to 3.0.0-alpha.9 is consistent with the broader package updates in this PR.


21-22: Good addition: Shorter CLI alias for improved user experience.

Adding the "zen" alias provides a convenient shorter command name while maintaining backward compatibility with the existing "zenstack" command.

packages/runtime/src/client/options.ts (1)

51-54: Excellent addition: Debug mode flag for enhanced troubleshooting.

The optional debug property provides a clean way to enable verbose error reporting and diagnostics throughout the client implementation. The TypeScript typing and JSDoc documentation are well-structured.

packages/runtime/src/utils/type-utils.ts (1)

71-74: LGTM! Clean utility type implementation.

The UnwrapTuplePromises type correctly uses mapped types to transform a readonly tuple by unwrapping promises from each element. This is a well-designed utility type that enhances type safety for sequential transaction results.

packages/runtime/src/client/constants.ts (1)

10-14: LGTM! Well-defined constant for transaction restrictions.

The TRANSACTION_UNSUPPORTED_METHODS constant correctly defines methods that should not be available within transactions. The use of as const ensures proper type inference and immutability.

packages/runtime/src/plugins/policy/utils.ts (2)

22-22: LGTM! Correct adaptation to updated method signature.

The addition of the third boolean parameter false to dialect.transformPrimitive correctly aligns with the updated method signature for handling array context. For boolean literals, false is the appropriate value indicating non-array context.


29-29: LGTM! Consistent parameter usage.

The consistent addition of the third boolean parameter false maintains uniformity with the trueNode function and correctly indicates non-array context for boolean literal transformation.

packages/runtime/test/plugin/query-lifecycle.test.ts (1)

257-268: LGTM! Appropriate test skip during transaction refactoring.

The test is correctly skipped with a clear TODO comment indicating that transactional hooks need to be revisited. The parameter renaming from tx to _tx follows convention for unused parameters, and the commented-out transaction argument aligns with the ongoing transaction API changes.

packages/runtime/tsconfig.json (1)

6-6: LGTM! Enhanced TypeScript coverage for test files.

Expanding the include pattern to cover all files under both src and test directories will ensure proper TypeScript compilation and type checking for test files, which aligns with the test coverage improvements mentioned in the summary.

packages/runtime/src/plugins/policy/expression-transformer.ts (1)

278-278: LGTM! Consistent with updated transformPrimitive method signature.

The addition of the third boolean parameter (false) aligns with the enhanced transformPrimitive method signature that now includes an array context flag. This ensures consistent primitive value transformation across the codebase.

packages/runtime/src/index.ts (1)

1-1: LGTM! Broadened exports enable access to enhanced client functionality.

The change from explicit exports to wildcard export makes all client module functionality available through the main entry point. This enables access to new types and functionality like ZenStackPromise, TransactionIsolationLevel, and enhanced transaction APIs mentioned in the summary.

packages/sdk/src/ts-schema-generator.ts (1)

698-699: LGTM! Improved type safety with explicit 'Unsupported' type.

Changing the fallback from 'unknown' to 'Unsupported' explicitly marks field types that are neither primitive nor references as unsupported. This improves type safety and clarity, aligning with the broader type system enhancements that include the 'Unsupported' type in the BuiltinType union.

packages/runtime/src/client/query-utils.ts (2)

20-20: Good improvement to error message clarity.

Adding "in schema" provides better context for developers when a model is not found.


167-167: Enhanced error message provides better context.

Including the model name in the computed field error message will help developers quickly identify which model is missing the implementation.

packages/runtime/test/plugin/kysely-on-query.test.ts (1)

115-150: Transaction-related tests have been systematically commented out.

All transaction-related tests are commented out with "TODO: revisit transactions" which aligns with the broader transaction handling refactoring mentioned in the AI summary. While this ensures the test suite passes during the transition, it reduces test coverage for transaction scenarios.

Please confirm this is intentional as part of the transaction refactoring effort and that these tests will be restored or replaced with updated implementations once the transaction changes are complete.

Also applies to: 208-256, 258-307, 358-480

packages/runtime/src/client/crud/operations/find.ts (1)

7-13: Good addition of argument normalization.

Normalizing args to strip undefined fields before validation and query execution ensures consistent input processing and aligns with the pattern used in other operation handlers. This improvement will help with cleaner query generation and validation.

packages/runtime/src/client/crud/dialects/sqlite.ts (1)

29-29: Well-implemented JSON support and array field handling.

The additions are well-structured:

  • The _forArrayField parameter provides proper context for array field transformations
  • Array elements are correctly processed with false for the array field parameter
  • JSON values are properly serialized using JSON.stringify

This aligns with the expanded BuiltinType union that includes Json and Unsupported types.

Also applies to: 35-35, 42-42

packages/runtime/test/plugin/mutation-hooks.test.ts (2)

3-3: Good addition of test cleanup.

Adding the afterEach hook to disconnect the client after each test is a good practice that ensures proper resource cleanup and prevents test interference.

Also applies to: 19-21


303-329: Test commented out as part of transaction refactoring.

The test for mutation continuation despite hook errors has been commented out with a TODO note, consistent with the broader transaction handling refactoring. This temporary removal helps maintain a passing test suite during the transition period.

packages/runtime/src/plugins/policy/plugin.ts (1)

18-21: Transaction parameter consistently commented out.

The change correctly comments out the transaction parameter in both the method signature and the handler call, maintaining consistency. This appears to be part of a broader refactoring effort to remove transaction handling from policy plugins.

packages/sdk/src/schema/schema.ts (1)

76-86: Clean addition of new builtin types.

The addition of 'Json' and 'Unsupported' types to the BuiltinType union is well-implemented and aligns with the broader type system enhancements described in the PR objectives.

packages/runtime/src/client/errors.ts (2)

1-8: Well-implemented error class with proper cause support.

The new InputValidationError class correctly extends Error with optional cause support, providing better error semantics for validation failures. The JSDoc documentation is helpful.


10-17: Good enhancement to QueryError with cause support.

Adding the optional cause parameter to QueryError improves error chaining and debugging capabilities.

packages/runtime/src/client/crud/operations/create.ts (1)

14-21: LGTM! Consistent argument normalization pattern.

The implementation correctly normalizes arguments before validation and uses the normalized values throughout the operation handlers. This ensures undefined fields are properly stripped for consistent input processing.

packages/runtime/test/client-api/undefined-values.test.ts (2)

20-22: LGTM! Comprehensive test for undefined argument handling.

This test validates that passing undefined as a top-level argument to findMany works correctly, which is crucial for the argument normalization changes.


24-41: LGTM! Thorough validation of undefined filter handling.

The test properly verifies that filter conditions with undefined values are ignored, allowing queries to match existing records. This validates the normalization behavior for nested undefined values.

packages/runtime/src/client/crud/operations/aggregate.ts (1)

13-48: LGTM! Consistent use of normalized arguments.

The implementation correctly uses the normalized arguments for validation and throughout the query building process. This ensures consistent handling of undefined values in aggregate operations.

packages/runtime/test/typing/schema.ts (1)

6-246: LGTM! Formatting consistency improvements.

The changes are purely stylistic (quotes, line formatting) with no functional impact on the schema definition. The formatting aligns with consistent code style practices.

packages/runtime/src/client/crud/operations/count.ts (1)

11-39: LGTM! Consistent argument normalization implementation.

The implementation correctly normalizes arguments before validation and uses the normalized values throughout the count operation. This ensures consistent handling of undefined values across all CRUD operations.

packages/runtime/src/client/crud/operations/group-by.ts (1)

9-13: No action needed: validateGroupByArgs already handles undefined input safely

Passing undefined into Zod’s safeParse produces a controlled InputValidationError rather than a runtime exception. Since normalizeArgs only returns undefined for falsy input and groupBy requires its args, this path is covered.

packages/runtime/test/client-api/create.test.ts (1)

292-319: Good test coverage for Prisma type compatibility.

The test properly verifies that:

  1. Foreign key fields and owned relations are mutually exclusive (TypeScript error)
  2. Foreign key fields can coexist with non-owned relations (no error)

This ensures type safety and aligns with Prisma's behavior.

packages/runtime/src/client/plugin.ts (2)

157-161: Consistent async hook pattern.

Making the operation hooks explicitly return promises aligns with the asynchronous nature of database operations and ensures consistency across the plugin system.


196-199: Transaction parameter removal aligns with architectural changes.

Commenting out the transaction parameter is consistent with the broader removal of explicit transaction handling from plugin interfaces, as mentioned in the summary.

packages/runtime/test/client-api/find.test.ts (2)

649-698: Excellent test coverage for nested selection features.

The tests comprehensively verify:

  • Nested selection of related fields (posts with author email)
  • Mixing of select and include at different levels
  • Proper object structure in the results

These tests ensure the nested selection feature works correctly.


843-851: Good addition of filtered count test.

Testing filtered counts (e.g., counting only published posts) is an important feature that wasn't previously covered. This ensures the filtering logic works correctly within count operations.

packages/runtime/src/client/crud/dialects/base.ts (1)

429-436: Appropriate error handling for unsupported field types.

Good addition of explicit error handling for Json and Unsupported types:

  • The TODO comment for JSON filters indicates future work
  • The error message for Unsupported fields is clear and prevents misuse

This ensures the type system is exhaustive and provides clear feedback.

packages/runtime/src/client/promise.ts (1)

1-45: Well-designed transaction-aware promise implementation.

The ZenStackPromise type elegantly extends the standard Promise interface with transaction support while maintaining full compatibility. The caching mechanism in cb ensures promises are only executed once, and the error handling properly catches synchronous exceptions.

packages/runtime/test/client-api/transaction.test.ts (1)

108-157: Comprehensive sequential transaction test coverage.

Excellent test coverage for sequential transactions, including edge cases like empty arrays and verifying that promises aren't executed prematurely. The tests effectively validate both the happy path and error scenarios.

packages/runtime/src/client/result-processor.ts (2)

165-173: Proper provider-specific JSON handling.

The transformJson method correctly handles the different JSON representations across database providers. The invariant check for SQLite ensures type safety before parsing.


137-141: Good defensive programming improvements.

The early return guard for falsy data and the stricter condition checking for array relations improve the robustness of the result processing logic.

Also applies to: 157-157

packages/runtime/src/plugins/policy/policy-handler.ts (1)

208-212: Correct array parameter addition to transformPrimitive calls.

The addition of the array parameter ensures proper handling of array fields during primitive transformation, aligning with the dialect implementation changes.

Also applies to: 217-217

packages/runtime/src/client/crud/dialects/postgresql.ts (2)

29-51: LGTM! Well-implemented JSON array handling for node-postgres compatibility.

The addition of the forArrayField parameter and the special handling for JSON arrays addresses the node-postgres issue effectively. The recursive transformation for array elements ensures consistent handling throughout.


220-230: Excellent improvements to relation field handling.

The changes correctly handle synthesized JSON fields for relations and improve nested relation processing by:

  • Distinguishing between relation and scalar fields in buildRelationObjectArgs
  • Merging include and select payloads in buildRelationJoins to ensure all nested relations are processed
  • Filtering only relation fields for recursive JSON join building

These improvements align well with the enhanced transaction and promise handling throughout the PR.

Also applies to: 257-273

packages/runtime/src/client/crud/validator.ts (3)

1-1: Good error handling improvements.

Using InputValidationError with the original error as cause provides better error context and debugging information.

Also applies to: 23-23, 182-183


302-321: Robust validation for compound unique fields.

The use of invariant correctly enforces that unique fields cannot be relations, and the handling of empty enums with z.never() is appropriate. These validation improvements enhance type safety.


653-751: Well-structured refactoring of create data schema.

The renaming to uncheckedVariantFields and checkedVariantFields improves code clarity, and the proper handling of non-owned relations in the unchecked variant aligns perfectly with the type system enhancements in crud-types.ts.

Also applies to: 821-821

packages/runtime/src/client/crud-types.ts (2)

531-536: Good naming consistency improvement.

Renaming CreateManyPayload to CreateManyInput aligns with the naming convention used for other input types throughout the codebase.

Also applies to: 628-635, 656-656


597-617: Excellent type-level enhancement for relation handling.

The addition of NonOwnedRelationFields utility type and the expansion of CreateWithFKInput to include non-owned relations enables more flexible create operations. This allows creating entities with both foreign keys and non-owned relations, which was previously not possible.

Also applies to: 1094-1098

packages/runtime/src/client/contract.ts (2)

39-45: Comprehensive transaction isolation level support.

The enum includes all standard SQL isolation levels plus snapshot isolation, providing flexibility for different database systems and use cases.


119-130: Well-designed transaction API with flexible modes.

The dual transaction modes (interactive with callback and sequential with promise array) provide excellent flexibility. The type-safe exclusion of unsupported methods within transactions prevents runtime errors.

packages/runtime/src/client/executor/zenstack-query-executor.ts (3)

157-161: Excellent error handling enhancement.

Including SQL in error messages and conditionally adding parameter inspection in debug mode provides valuable debugging information while avoiding sensitive data exposure in production.


213-223: Critical fix for executor-client consistency.

The bidirectional update ensures that when a new connection provider is set, both the executor and its associated client remain synchronized. This prevents potential issues where operations could use mismatched executors.


67-68: Clean separation of concerns with transaction management.

Moving transaction management to the client layer and making mutation hooks async improves the architecture by:

  • Delegating transaction control to the appropriate layer
  • Providing better flexibility for plugin implementations
  • Simplifying the executor's responsibilities

Also applies to: 91-92, 101-102

packages/runtime/src/client/client-impl.ts (4)

60-117: Well-structured constructor with flexible executor initialization.

The optional executor parameter and conditional initialization logic provide good flexibility for testing and custom implementations.


153-223: Excellent transaction API implementation with proper isolation and type safety.

The dual overload approach provides flexibility for both interactive and sequential transaction patterns, with proper transaction reuse and isolation level support.


294-327: Consistent promise abstraction for raw query methods.

All raw query methods now properly return ZenStackPromise instances, enabling unified transaction support across the API.


370-411: Well-implemented transaction-aware promise creation.

The callback pattern with optional transaction client enables seamless transaction support while maintaining plugin compatibility.

packages/runtime/src/client/crud/operations/base.ts (5)

206-213: Helpful debug mode enhancement for error messages.

The conditional parameter inspection in debug mode will aid troubleshooting without exposing sensitive data in production.


297-327: Improved count selection using nested queries.

The refactored implementation using subqueries provides better query isolation and properly handles filtered counts.


632-693: Excellent relation processing improvements with clear naming and extended functionality.

The renamed methods improve code clarity, and the addition of createMany support for relations enhances bulk operation capabilities. The early return optimization for empty data is a good defensive programming practice.

Also applies to: 695-778, 790-794


1904-1919: Transaction helper properly supports isolation levels.

The updated safeTransaction method correctly propagates isolation level settings to match the client-level transaction API.


463-473: TransformPrimitive array parameter fully implemented across dialects

Verified that the base transformPrimitive(value, type, _forArrayField) signature has been updated and both SQLite and PostgreSQL dialects override and correctly handle the array flag. No further changes needed.

@ymc9 ymc9 added this pull request to the merge queue Jul 9, 2025
Merged via the queue into main with commit 04323de Jul 9, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants