Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Jul 28, 2025

Summary by CodeRabbit

  • New Features

    • Added robust support for polymorphic (delegate) models, including creation, querying, updating, and deletion of base and derived models with correct discriminator handling.
    • Introduced support for mixins and type inheritance in schemas, allowing models and types to inherit fields and attributes from multiple sources.
    • Enabled custom type definitions and typed JSON fields, with corresponding validation and runtime support.
    • Added a CLI command to validate ZModel schemas.
    • Added AI-powered GitHub workflows for automated code review and interaction.
  • Bug Fixes

    • Improved attribute validation to detect duplication and deprecation.
    • Enhanced relation validation logic, including self-relations, many-to-many, and inheritance cycles.
    • Fixed unique constraint naming to ensure uniqueness across models.
  • Documentation

    • Added comprehensive documentation for working with Claude Code and development workflows.
  • Tests

    • Introduced extensive test suites for delegate models, mixins, inheritance, typed JSON fields, and CLI validation.
    • Updated and expanded test schemas and type-checking utilities.
  • Chores

    • Updated package versions and refined ignore/configuration files.
    • Automated schema and type generation for test suites.
    • Improved VSCode tasks for build and PR submission.
  • Refactor

    • Unified field and attribute handling across models and types.
    • Streamlined and generalized validation, linking, and scope logic in schema processing.
    • Improved runtime query, CRUD, and aggregation logic to support advanced schema features.
    • Reorganized and enhanced dialect and query builder implementations for delegate models.
    • Enhanced workspace manager to dynamically load plugin models.

ymc9 and others added 18 commits July 17, 2025 22:02
* Claude PR Assistant workflow

* Claude Code Review workflow
* chore: add CLAUDE.md

* fix: add a few missing zmodel validation checks

* update

* update

* update
* chore: update test schema generation

* break down large test suite into smaller ones
* feat: implementing mixin

* format

* update
* feat: implement delegate models (create + read)

* update

* update

* update
* feat: count and aggregate for delegate models

* fixes
* feat: delegate client typing

* update
Co-authored-by: ymc9 <104139426+ymc9@users.noreply.github.com>
Copilot AI review requested due to automatic review settings July 28, 2025 15:21
@coderabbitai
Copy link

coderabbitai bot commented Jul 28, 2025

Walkthrough

This update introduces comprehensive enhancements to the ZenStack codebase, focusing on polymorphic (delegate) model support, mixins, and type definitions. The language grammar and AST are unified to generalize field and attribute handling, enabling mixins, inheritance, and delegate models with discriminators. The runtime client, CRUD operations, and type system are refactored to support polymorphic models, custom type definitions, and improved validation. Extensive new tests, documentation, and generated schema/type files are added. Numerous internal utilities, validators, and dialects are updated to align with the new abstractions and features.

Changes

Cohort / File(s) Change Summary
CI & Docs
.github/workflows/claude-code-review.yml, .github/workflows/claude.yml, CLAUDE.md, .prettierignore, TODO.md, .vscode/tasks.json
Added new GitHub workflows for Claude AI code review and interaction, enhanced documentation for Claude usage, refined Prettier ignore patterns, updated TODO list, and added/modified VSCode tasks.
Version Bumps & Package Metadata
package.json, packages/*/package.json
Updated package versions to 3.0.0-alpha.13, added new exports and dev dependencies, and updated build/test scripts where applicable.
CLI: Validate Command & Tests
packages/cli/src/actions/validate.ts, packages/cli/src/actions/index.ts, packages/cli/src/index.ts, packages/cli/test/validate.test.ts
Introduced a new CLI validate command for schema validation, exported the validate action, registered the command in CLI, and added comprehensive tests for validation scenarios.
CLI: Mixins & Inheritance Tests
packages/cli/test/ts-schema-gen.test.ts
Added tests verifying correct merging of fields and attributes from mixins and inheritance in schema generation.
Language: Grammar & AST Unification
packages/language/src/ast.ts, packages/language/src/utils.ts, packages/language/src/zmodel-linker.ts, packages/language/src/zmodel-scope.ts, packages/language/src/zmodel.langium, packages/language/src/validators/*, packages/language/tsup.config.ts, packages/language/vitest.config.ts, packages/language/package.json, packages/language/res/stdlib.zmodel
Unified DataModelField and TypeDefField into a single DataField abstraction; refactored grammar rules, AST interfaces, validators, scope and linking logic accordingly; added new utility exports and dev dependencies; enhanced standard library attribute declarations with metadata and deprecation support.
Language: Workspace & Plugin Models
packages/language/src/zmodel-workspace-manager.ts
Extended workspace manager to dynamically discover and load plugin model documents based on plugin declarations found in loaded documents, scanning workspace folders recursively.
Language: Tests & Utilities
packages/language/test/delegate.test.ts, packages/language/test/mixin.test.ts, packages/language/test/utils.ts
Added new test suites for delegate model inheritance validation, mixin functionality and error detection, and utility functions to load schemas and assert errors in tests.
Runtime: Core Polymorphic/Delegate Model Support
packages/runtime/src/client/crud-types.ts, packages/runtime/src/client/contract.ts, packages/runtime/src/client/query-builder.ts, packages/runtime/src/client/crud/operations/base.ts, packages/runtime/src/client/crud/dialects/base.ts, packages/runtime/src/client/crud/dialects/sqlite.ts, packages/runtime/src/client/crud/dialects/postgresql.ts, packages/runtime/src/client/crud/operations/aggregate.ts, packages/runtime/src/client/crud/operations/count.ts, packages/runtime/src/client/crud/operations/delete.ts, packages/runtime/src/client/crud/operations/update.ts, packages/runtime/src/client/crud/validator.ts, packages/runtime/src/client/executor/name-mapper.ts, packages/runtime/src/client/query-utils.ts, packages/runtime/src/client/result-processor.ts, packages/runtime/src/client/helpers/schema-db-pusher.ts, packages/runtime/src/client/constants.ts, packages/runtime/src/client/plugin.ts, packages/runtime/src/client/client-impl.ts
Refactored type utilities and CRUD operation handlers to fully support polymorphic delegate models with discriminators; enhanced query building to include delegate joins; improved result processing for delegate fields; extended validation to support custom type definitions and discriminator fields; added constants and plugin context enhancements; updated dialects to handle delegate model selections and filters.
Runtime: Test Infrastructure & Schema Generation
packages/runtime/test/scripts/generate.ts, packages/runtime/test/schemas/basic/*, packages/runtime/test/schemas/delegate/*, packages/runtime/test/schemas/todo/*, packages/runtime/test/schemas/typing/*
Added schema generation scripts and new schema, model, and input type files for basic, delegate, todo, and typing test suites; introduced type-level tests for polymorphic models and typed JSON fields.
Runtime: Test Suites (Delegate, Mixins, Typed JSON, etc.)
packages/runtime/test/client-api/delegate.test.ts, packages/runtime/test/client-api/mixin.test.ts, packages/runtime/test/client-api/typed-json-fields.test.ts
Added extensive end-to-end test suites for delegate model behaviors, mixin support, and typed JSON field handling across supported database providers.
Runtime: Test Suites (Refactored Imports/Minor Updates)
packages/runtime/test/client-api/*, packages/runtime/test/plugin/*, packages/runtime/test/policy/*, packages/runtime/test/query-builder/*
Updated schema imports for consistency across tests, added explicit naming metadata to schemas and models, improved test client typings, and applied minor assertion and test fixes.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120+ minutes

  • Complexity: This is a critical, high-complexity, and high-volume change affecting core abstractions (field/type unification, delegate models, mixins), runtime CRUD logic, type system, validators, and extensive test/data generation.
  • Scope: Hundreds of files, fundamental architectural changes, and deep cross-cutting refactors.
  • Review Time: Requires careful review of language grammar, AST, runtime CRUD, type utilities, validator logic, and new/updated tests and schema files.

Possibly related PRs

  • fix(delegate): filter fixes #112: Refactors and fixes filter-related methods in the BaseCrudDialect class, including buildSelectModel and filter method signatures, which the current PR builds upon for delegate model support and query building enhancements.

Poem

🐇✨

In fields of code where models mix and blend,
Polymorphic bunnies hop—inheritance has no end!
Mixins bring their magic, types unite as one,
Delegates and discriminators—oh, what fun!
With tests that leap through every case,
This rabbit cheers your code’s embrace—
For ZenStack’s garden just grew a wondrous, hybrid place!

((\
( -.-)
o_(")(")

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

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 generate unit tests to generate unit tests for 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.

@claude
Copy link

claude bot commented Jul 28, 2025

Claude finished @ymc9's task —— View job


PR Review Complete

This is a substantial dev->main merge containing major new features and improvements for ZenStack v3.0.0-alpha.13. Here's my comprehensive review:

🎯 Overall Assessment

This PR represents a well-structured release with significant new features. The code quality is generally high with comprehensive test coverage and proper error handling.

Strengths

Security & GitHub Actions

  • GitHub Actions workflows (.github/workflows/) follow security best practices
  • Proper permissions scoping (contents: read, pull-requests: read, etc.)
  • Secure token handling with ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
  • No hardcoded secrets or security vulnerabilities detected

Code Quality & Architecture

  • Delegate Models: Well-implemented polymorphic inheritance system

    • Proper validation prevents direct creation of delegate models (packages/runtime/src/client/crud/operations/base.ts:400-402)
    • Clean separation of concerns with base model handling
    • Comprehensive test coverage in packages/runtime/test/client-api/delegate.test.ts
  • Type Safety: Excellent TypeScript implementation

    • Strong typing throughout with proper generic constraints
    • Typed JSON fields with validation support
    • Runtime type checking with Zod integration

Test Coverage

  • Extensive test suite additions (1000+ new test lines)
  • Cross-database testing (SQLite + PostgreSQL)
  • Edge case coverage for new features
  • Proper test isolation and cleanup

⚠️ Areas for Improvement

Performance Considerations

  1. packages/runtime/src/client/crud/operations/base.ts:494-498

    if (modelDef.baseModel) {
        const baseCreateResult = await this.processBaseModelCreate(kysely, modelDef.baseModel, createFields, model);
        createFields = baseCreateResult.remainingFields;
    }
    • Consider optimizing base model creation to reduce database round trips
    • Could benefit from transaction batching for complex delegate hierarchies
  2. Query Performance: Multi-level delegation might generate complex queries

    • Monitor query plans for deeply nested delegate structures
    • Consider adding query hints or optimizations

Error Handling

  1. packages/cli/src/actions/validate.ts:14-21
    try {
        await loadSchemaDocument(schemaFile);
        console.log(colors.green('✓ Schema validation completed successfully.'));
    } catch (error) {
        console.error(colors.red('✗ Schema validation failed.'));
        throw error; // Could provide more context
    }
    • Error messages could be more descriptive for end users
    • Consider adding structured error reporting

Minor Code Quality Issues

  1. packages/language/src/validators/datamodel-validator.ts:58-64

    • Long error message could be split for better readability
    • Consider extracting validation messages to constants
  2. Memory Management: Large file operations could benefit from streaming

    • Consider memory usage for very large schema files

🔍 Specific Feature Reviews

Delegate Models

  • Implementation: Excellent polymorphic inheritance system
  • Validation: Proper constraints prevent misuse
  • Testing: Comprehensive coverage including edge cases
  • Documentation: Well-documented in schema examples

Typed JSON Fields

  • Type Safety: Strong compile-time and runtime validation
  • Database Support: Works across SQLite and PostgreSQL
  • Error Handling: Proper validation with meaningful messages

CLI Validation

  • Simple and Effective: Clean implementation
  • Error Reporting: Basic but functional
  • Integration: Follows existing CLI patterns

Mixin Support

  • Language Integration: Well-integrated into ZModel grammar
  • Validation: Proper inheritance checks
  • Testing: Good coverage of mixin scenarios

🚀 Recommendations

  1. Performance Monitoring: Add telemetry for delegate model operations to monitor real-world performance
  2. Documentation: Consider adding migration guide for the new delegate/mixin features
  3. Error Messages: Enhance CLI error reporting with actionable suggestions
  4. Query Optimization: Monitor and optimize complex delegate queries in production

📊 Test Coverage Assessment

  • Excellent coverage for new features (delegate, mixin, typed JSON)
  • Cross-database testing ensures compatibility
  • Edge case handling is comprehensive
  • Integration tests validate real-world scenarios

🔒 Security Review

  • No security vulnerabilities detected
  • Proper input validation throughout
  • Safe database operations with parameterized queries
  • GitHub Actions security follows best practices

Final Verdict

This is a high-quality release ready for merge. The new features are well-implemented with excellent test coverage and proper error handling. The architectural decisions are sound and the code follows established patterns.

Recommendation: APPROVE

The minor performance and error handling suggestions can be addressed in future iterations without blocking this release.


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 development branch to main, containing significant enhancements to the ZenStack framework including version bump from 3.0.0-alpha.12 to 3.0.0-alpha.13, new Prisma consistency validation tests, support for type definitions in schemas, improved turbo build configuration, and delegate model improvements.

  • Version bump across all packages to 3.0.0-alpha.13
  • Addition of comprehensive Prisma consistency validation tests for various schema constructs
  • Introduction of type definitions support in the schema system with TypeDefResult type
  • Enhanced TypeScript schema generation with field name properties and delegate model handling

Reviewed Changes

Copilot reviewed 142 out of 145 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
turbo.json Updates build inputs to include zenstack/*.zmodel files and adds watch task
tests/e2e/prisma-consistency/*.test.ts New comprehensive validation tests for Prisma schema consistency
packages/sdk/src/*.ts Enhanced TypeScript schema generation with type definitions and delegate model support
packages/runtime/src/schema/schema.ts Extended schema types with TypeDefResult and delegate model support
samples/blog/zenstack/schema.zmodel Demonstrates type definition usage with CommonFields mixin
Multiple package.json files Version bump to 3.0.0-alpha.13 across all packages
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported
Comments suppressed due to low confidence (1)

packages/sdk/src/prisma/prisma-schema-generator.ts:391

  • The variable name 'auxName' is not descriptive. Consider renaming to something more specific like 'delegateRelationFieldName' or 'concreteModelRelationName'.
            const auxName = this.truncate(`${DELEGATE_AUX_RELATION_PREFIX}_${lowerCaseFirst(concrete.name)}`);

@ymc9 ymc9 changed the title merge dev to main merge dev to main (v3.0.0-alpha.13) Jul 28, 2025
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: 8

🧹 Nitpick comments (33)
package.json (1)

1-41: Optional: add an automated consistency check for workspace versions
Since this repo manually bumps dozens of packages in lock-step, consider adding a small PNPM/Turbo task that fails CI when any workspace package’s version disagrees with the root version. This prevents silent mismatches on future bumps.

.vscode/tasks.json (1)

54-62: Add a task group for “Submit PR” and consider a problem matcher.

The other tasks are grouped ("build", "test", etc.); the new “Submit PR” task is not.
Grouping lets it appear under VS Code’s ⌘⇧B picker and prevents category clutter.

Minimal tweak:

         {
             "label": "Submit PR",
             "command": "pnpm pr",
             "type": "shell",
+            "group": { "kind": "build" },
             "icon": {
                 "color": "terminal.ansiWhite",
                 "id": "server-process"
             },
             "problemMatcher": []
         }
TODO.md (2)

10-15: Fix Markdown indentation (MD007).

Sub-items under “CLI” are indented four spaces; the repo-wide markdown-lint rule expects two. Prevent noisy CI failures by normalising:

-    - [x] validate
-    - [ ] format
-    - [ ] db seed
+  - [x] validate
+  - [ ] format
+  - [ ] db seed

61-68: Indentation drift under “Extensions”.

Same MD007 warnings appear here. Quick fix:

-        - [ ] Custom procedures
+      - [ ] Custom procedures

Continue the two-space rule for deeper levels.

.github/workflows/claude.yml (2)

40-64: Trailing spaces and blank-line lint errors.

yamllint flags six lines with trailing spaces and an extra blank line at 64. They don’t break YAML parsing but will keep failing lint jobs.

Quick removal:

-          actions: read # Required for Claude to read CI results on PRs␠
+          actions: read # Required for Claude to read CI results on PRs
...
-          # model: "claude-opus-4-20250514"␠
+          # model: "claude-opus-4-20250514"
...
-          # claude_env: |␠
+          # claude_env: |

13-20: Add a concurrency group to avoid duplicate runs.

Multiple comments containing “@claude” on the same PR will queue separate jobs, wasting CI minutes. Consider:

   jobs:
     claude:
+      concurrency:
+        group: claude-${{ github.event.pull_request.number || github.run_id }}
+        cancel-in-progress: true
.github/workflows/claude-code-review.yml (2)

20-78: Clean up trailing spaces and extra blank line (yamllint).

Several lines (20, 27, 42, 51, 56, 64, 67, 70, 73) contain trailing spaces; line 78 is an extra blank line. Remove to keep CI green.


13-34: Consider cancelling outdated review jobs.

Pushing commits quickly can spawn parallel “Claude Code Review” runs. A concurrency block prevents noisy duplicate reviews:

   jobs:
     claude-review:
+      concurrency:
+        group: claude-review-${{ github.event.pull_request.number }}
+        cancel-in-progress: true
CLAUDE.md (3)

17-18: Pinning pnpm version may create unnecessary churn
Hard-pinning to pnpm@10.12.1 forces every contributor/CI runner to stay on that specific release. Minor/patch versions frequently deliver bug-fixes and security updates, so consider:

- - Package manager is pinned to `pnpm@10.12.1`
+ - Works with `pnpm >=10.12.1` (tested); pin via `.npmrc` only in CI if reproducibility is critical

This keeps local developer experience flexible while CI still guarantees deterministic builds.


30-33: Clarify Prisma dependency scope
The doc states npx zenstack db push and migration commands “use Prisma”. Readers might assume Prisma is required at runtime, which contradicts the later “No runtime dependency on @prisma/client”. Add an explicit note:

“Prisma is used only for schema comparison/migration generation; generated applications do not carry a Prisma runtime dependency.”

Helps avoid confusion for new adopters.


81-84: Suggest adding watch-time codegen hint
Because zenstack generate must be rerun after every schema edit, add a tip to hook it into Turbo’s watch pipeline or pnpm dev so contributors don’t forget. Small DX win.

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

3-3: Type-only import – can be import type
schema is used only for generic parameterisation; mark as type-only to avoid emitting runtime import in compiled JS and keep bundle clean:

-import { schema } from '../schemas/basic';
+import type { schema } from '../schemas/basic';
packages/runtime/test/client-api/upsert.test.ts (1)

3-3: Duplicate runtime import
Same as previous file – convert to import type to drop unused runtime code when transpiled.

packages/language/tsup.config.ts (1)

7-7: Consider enabling code-splitting to avoid duplicate bundles

With a third entry point (utils) added and splitting: false, common code will be duplicated across index.js, ast.js, and utils.js, slightly bloating the package size. If consumers don’t rely on the current single-file bundles, you could switch on splitting so shared chunks are emitted once:

-    splitting: false,
+    splitting: true,

This is optional and may be deferred if bundle size isn’t a concern or if preserving standalone files is intentional.

packages/cli/package.json (1)

6-6: Version bump acknowledged

@zenstackhq/cli moves to 3.0.0-alpha.13. Ensure release notes/changelog reflect this increment, but the change itself is fine.

If not already done, remember to tag the corresponding release and update CHANGELOG.md.

packages/language/test/utils.ts (2)

8-16: Consider cleanup of temporary files.

The function correctly creates temporary files and loads schemas, but temporary files are not cleaned up after use. This could lead to accumulation of temp files during test runs.

Consider adding cleanup of temporary files:

 export async function loadSchema(schema: string) {
     // create a temp file
     const tempFile = path.join(os.tmpdir(), `zenstack-schema-${crypto.randomUUID()}.zmodel`);
-    fs.writeFileSync(tempFile, schema);
-    const r = await loadDocument(tempFile);
-    expect(r.success).toBe(true);
-    invariant(r.success);
-    return r.model;
+    try {
+        fs.writeFileSync(tempFile, schema);
+        const r = await loadDocument(tempFile);
+        expect(r.success).toBe(true);
+        invariant(r.success);
+        return r.model;
+    } finally {
+        if (fs.existsSync(tempFile)) {
+            fs.unlinkSync(tempFile);
+        }
+    }
 }

18-30: Same cleanup issue as loadSchema function.

The error handling logic is well-implemented with support for both string and RegExp error matching. However, the same temporary file cleanup issue applies here.

Apply the same cleanup pattern as suggested for loadSchema:

 export async function loadSchemaWithError(schema: string, error: string | RegExp) {
     // create a temp file
     const tempFile = path.join(os.tmpdir(), `zenstack-schema-${crypto.randomUUID()}.zmodel`);
-    fs.writeFileSync(tempFile, schema);
-    const r = await loadDocument(tempFile);
-    expect(r.success).toBe(false);
-    invariant(!r.success);
-    if (typeof error === 'string') {
-        expect(r.errors.some((e) => e.toString().toLowerCase().includes(error.toLowerCase()))).toBe(true);
-    } else {
-        expect(r.errors.some((e) => error.test(e))).toBe(true);
-    }
+    try {
+        fs.writeFileSync(tempFile, schema);
+        const r = await loadDocument(tempFile);
+        expect(r.success).toBe(false);
+        invariant(!r.success);
+        if (typeof error === 'string') {
+            expect(r.errors.some((e) => e.toString().toLowerCase().includes(error.toLowerCase()))).toBe(true);
+        } else {
+            expect(r.errors.some((e) => error.test(e))).toBe(true);
+        }
+    } finally {
+        if (fs.existsSync(tempFile)) {
+            fs.unlinkSync(tempFile);
+        }
+    }
 }
packages/runtime/src/client/crud/operations/delete.ts (1)

31-37: Consider the performance impact of transactional deletes

While transactional safety is important for polymorphic models, wrapping simple delete operations in transactions may impact performance. The TODO comment correctly identifies this concern.

Consider implementing a check to determine if the transaction is necessary based on whether the model has delegate relationships or complex constraints. Would you like me to help implement this optimization?

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

52-56: Document the null return behavior

Returning null for cascade deletes may violate TypeScript's type expectations. Consider documenting this behavior clearly in the method's JSDoc.

packages/runtime/test/scripts/generate.ts (1)

10-11: Update comment to match actual directory being searched.

The comment mentions "e2e" directory but the code actually searches "../schemas/**/" directory.

-    // glob all zmodel files in "e2e" directory
+    // glob all zmodel files in "schemas" directory
packages/runtime/src/client/query-utils.ts (1)

285-292: Consider using Object.fromEntries for cleaner implementation.

The function works correctly, but could be more concise.

 export function extractFields(object: any, fields: string[]) {
-    return fields.reduce((acc: any, field) => {
-        if (field in object) {
-            acc[field] = object[field];
-        }
-        return acc;
-    }, {});
+    return Object.fromEntries(
+        fields.filter(field => field in object).map(field => [field, object[field]])
+    );
 }
packages/runtime/src/client/crud/dialects/postgresql.ts (1)

210-223: Delegate descendant JSON selection implemented correctly.

The implementation properly handles delegate descendant models by selecting their JSON representations with the appropriate prefix. The TODO comment correctly identifies a potential optimization opportunity.

Would you like me to create an implementation that conditionally selects descendant JSON fields based on the actual fields being queried?

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

80-86: Consistent implementation with PostgreSQL dialect.

The changes for field selection and delegate descendant handling mirror the PostgreSQL dialect implementation, ensuring consistency across database providers.

Consider extracting the delegate descendant JSON selection logic into a shared method in the base dialect class to reduce code duplication between SQLite and PostgreSQL dialects.

Also applies to: 154-166

packages/runtime/test/schemas/basic/schema.ts (1)

246-269: Consider applying CommonFields as a mixin to reduce duplication.

The CommonFields type definition contains id, createdAt, and updatedAt fields that are duplicated across all models. Based on the PR's focus on mixin support, these common fields should be applied as a mixin to the models to eliminate redundancy.

packages/language/src/zmodel-workspace-manager.ts (1)

114-127: Optimize directory sorting logic.

The current sorting logic only prioritizes node_modules but returns 1 for all other directories, which doesn't maintain their original order.

Consider improving the sorting to maintain relative order:

 const content = (await this.fileSystemProvider.readDirectory(folderPath)).sort((a, b) => {
     // make sure the node_modules folder is always the first one to be checked
     // so we can exit early if the plugin is found
     if (a.isDirectory && b.isDirectory) {
         const aName = UriUtils.basename(a.uri);
+        const bName = UriUtils.basename(b.uri);
         if (aName === 'node_modules') {
             return -1;
-        } else {
+        } else if (bName === 'node_modules') {
             return 1;
+        } else {
+            return 0;
         }
     } else {
         return 0;
     }
 });
packages/runtime/test/client-api/delegate.test.ts (2)

355-597: Comprehensive filter test coverage across inheritance hierarchy.

The tests thoroughly validate filtering behavior at different levels of the polymorphic hierarchy and through relations.

Consider extracting the repeated test data setup into a helper function to reduce duplication between test cases.


1-1215: Consider enhancing test isolation and assertions.

While the test coverage is excellent, consider these improvements:

  1. Add unique identifiers to test data to prevent conflicts if tests run in parallel
  2. Use more specific assertions where possible

For example, instead of:

await expect(client.ratedVideo.findMany()).toResolveWithLength(1);

Consider:

const videos = await client.ratedVideo.findMany();
expect(videos).toHaveLength(1);
expect(videos[0]).toMatchObject({ url: 'abc', rating: 5 });
packages/runtime/test/schemas/delegate/typecheck.ts (1)

1-183: Consider adding file documentation.

This file serves as a compile-time type validation test. Consider adding a header comment to clarify its purpose.

Add a file header:

+/**
+ * TypeScript compile-time type checking tests for delegate models.
+ * This file validates that the TypeScript types are correctly generated and enforced.
+ * It uses @ts-expect-error comments to ensure invalid operations are caught at compile time.
+ * This file is not meant to be executed but rather to be type-checked by TypeScript.
+ */
 import SQLite from 'better-sqlite3';
packages/language/src/zmodel.langium (2)

168-182: Consider enforcing a consistent clause ordering.

While the flexibility to specify WithClause and ExtendsClause in any order is convenient, it might lead to inconsistent code styles across the codebase. Consider enforcing a single canonical order (e.g., always extends before with) to improve consistency.

-        ('model' name=RegularID (WithClause | ExtendsClause | (ExtendsClause WithClause) | (WithClause ExtendsClause))?) |
+        ('model' name=RegularID ((ExtendsClause WithClause?) | WithClause)?) |

252-257: LGTM! Consider addressing the TODO comment.

The DataFieldAttribute correctly replaces the previous field-specific attribute types. However, there's a TODO comment at line 255 about renaming DataModelAttribute since it's now used for both DataModel and TypeDef. This should be addressed for consistency.

Would you like me to suggest a better name for DataModelAttribute that reflects its dual usage?

packages/language/src/validators/datamodel-validator.ts (2)

438-475: Good inheritance validation with room for improvement.

The validation correctly:

  • Ensures only delegate models can be extended
  • Detects inheritance cycles with clear error messages

Consider extracting the cycle detection logic into a reusable utility function since similar logic exists in validateMixins.


477-492: Consider extracting common cycle detection logic.

The mixin validation correctly detects cycles, but the pattern is nearly identical to validateInherits. Consider extracting a generic cycle detection utility.

private detectCycle<T extends { name: string }>(
    start: T,
    getNext: (item: T) => T[],
    errorMessage: (path: string[]) => string,
    accept: ValidationAcceptor,
): boolean {
    const seen: T[] = [];
    const todo = [start];
    // ... common cycle detection logic
}
packages/runtime/src/client/crud/dialects/base.ts (1)

781-819: Good polymorphic field selection with performance consideration.

The buildSelectAllFields method cleverly packs delegate descendant fields into JSON objects. However, for models with many descendants, this could impact query performance.

Consider adding a comment explaining the performance implications and potentially implementing lazy loading for delegate fields in the future.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ed6cfe6 and 33ac58e.

⛔ Files ignored due to path filters (3)
  • packages/language/src/generated/ast.ts is excluded by !**/generated/**
  • packages/language/src/generated/grammar.ts is excluded by !**/generated/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (107)
  • .github/workflows/claude-code-review.yml (1 hunks)
  • .github/workflows/claude.yml (1 hunks)
  • .prettierignore (1 hunks)
  • .vscode/tasks.json (2 hunks)
  • CLAUDE.md (1 hunks)
  • TODO.md (3 hunks)
  • package.json (1 hunks)
  • packages/cli/package.json (1 hunks)
  • packages/cli/src/actions/generate.ts (2 hunks)
  • packages/cli/src/actions/index.ts (1 hunks)
  • packages/cli/src/actions/validate.ts (1 hunks)
  • packages/cli/src/index.ts (3 hunks)
  • packages/cli/test/ts-schema-gen.test.ts (1 hunks)
  • packages/cli/test/validate.test.ts (1 hunks)
  • packages/common-helpers/package.json (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 (3 hunks)
  • packages/language/res/stdlib.zmodel (6 hunks)
  • packages/language/src/ast.ts (2 hunks)
  • packages/language/src/utils.ts (14 hunks)
  • packages/language/src/validators/attribute-application-validator.ts (13 hunks)
  • packages/language/src/validators/common.ts (2 hunks)
  • packages/language/src/validators/datamodel-validator.ts (8 hunks)
  • packages/language/src/validators/expression-validator.ts (3 hunks)
  • packages/language/src/validators/function-invocation-validator.ts (3 hunks)
  • packages/language/src/zmodel-linker.ts (9 hunks)
  • packages/language/src/zmodel-scope.ts (5 hunks)
  • packages/language/src/zmodel-workspace-manager.ts (3 hunks)
  • packages/language/src/zmodel.langium (5 hunks)
  • packages/language/test/delegate.test.ts (1 hunks)
  • packages/language/test/mixin.test.ts (1 hunks)
  • packages/language/test/utils.ts (1 hunks)
  • packages/language/tsup.config.ts (1 hunks)
  • packages/language/vitest.config.ts (1 hunks)
  • packages/runtime/package.json (2 hunks)
  • packages/runtime/src/client/client-impl.ts (1 hunks)
  • packages/runtime/src/client/constants.ts (1 hunks)
  • packages/runtime/src/client/contract.ts (2 hunks)
  • packages/runtime/src/client/crud-types.ts (22 hunks)
  • packages/runtime/src/client/crud/dialects/base.ts (19 hunks)
  • packages/runtime/src/client/crud/dialects/postgresql.ts (3 hunks)
  • packages/runtime/src/client/crud/dialects/sqlite.ts (4 hunks)
  • packages/runtime/src/client/crud/operations/aggregate.ts (2 hunks)
  • packages/runtime/src/client/crud/operations/base.ts (23 hunks)
  • packages/runtime/src/client/crud/operations/count.ts (3 hunks)
  • packages/runtime/src/client/crud/operations/delete.ts (1 hunks)
  • packages/runtime/src/client/crud/operations/update.ts (2 hunks)
  • packages/runtime/src/client/crud/validator.ts (7 hunks)
  • packages/runtime/src/client/executor/name-mapper.ts (1 hunks)
  • packages/runtime/src/client/helpers/schema-db-pusher.ts (3 hunks)
  • packages/runtime/src/client/plugin.ts (1 hunks)
  • packages/runtime/src/client/query-builder.ts (3 hunks)
  • packages/runtime/src/client/query-utils.ts (3 hunks)
  • packages/runtime/src/client/result-processor.ts (3 hunks)
  • packages/runtime/test/client-api/aggregate.test.ts (1 hunks)
  • packages/runtime/test/client-api/client-specs.ts (1 hunks)
  • packages/runtime/test/client-api/count.test.ts (1 hunks)
  • packages/runtime/test/client-api/create-many-and-return.test.ts (1 hunks)
  • packages/runtime/test/client-api/create-many.test.ts (1 hunks)
  • packages/runtime/test/client-api/create.test.ts (1 hunks)
  • packages/runtime/test/client-api/default-values.test.ts (1 hunks)
  • packages/runtime/test/client-api/delegate.test.ts (1 hunks)
  • packages/runtime/test/client-api/delete-many.test.ts (1 hunks)
  • packages/runtime/test/client-api/delete.test.ts (1 hunks)
  • packages/runtime/test/client-api/filter.test.ts (1 hunks)
  • packages/runtime/test/client-api/find.test.ts (2 hunks)
  • packages/runtime/test/client-api/group-by.test.ts (1 hunks)
  • packages/runtime/test/client-api/mixin.test.ts (1 hunks)
  • packages/runtime/test/client-api/name-mapping.test.ts (1 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/typed-json-fields.test.ts (1 hunks)
  • packages/runtime/test/client-api/undefined-values.test.ts (1 hunks)
  • packages/runtime/test/client-api/update-many.test.ts (1 hunks)
  • packages/runtime/test/client-api/update.test.ts (1 hunks)
  • packages/runtime/test/client-api/upsert.test.ts (1 hunks)
  • packages/runtime/test/client-api/utils.ts (1 hunks)
  • packages/runtime/test/plugin/kysely-on-query.test.ts (1 hunks)
  • packages/runtime/test/plugin/mutation-hooks.test.ts (1 hunks)
  • packages/runtime/test/plugin/query-lifecycle.test.ts (1 hunks)
  • packages/runtime/test/policy/read.test.ts (1 hunks)
  • packages/runtime/test/policy/todo-sample.test.ts (2 hunks)
  • packages/runtime/test/policy/utils.ts (1 hunks)
  • packages/runtime/test/query-builder/query-builder.test.ts (1 hunks)
  • packages/runtime/test/schemas/basic/helper.ts (1 hunks)
  • packages/runtime/test/schemas/basic/index.ts (1 hunks)
  • packages/runtime/test/schemas/basic/input.ts (1 hunks)
  • packages/runtime/test/schemas/basic/models.ts (1 hunks)
  • packages/runtime/test/schemas/basic/schema.ts (1 hunks)
  • packages/runtime/test/schemas/basic/schema.zmodel (1 hunks)
  • packages/runtime/test/schemas/delegate/input.ts (1 hunks)
  • packages/runtime/test/schemas/delegate/models.ts (1 hunks)
  • packages/runtime/test/schemas/delegate/schema.ts (1 hunks)
  • packages/runtime/test/schemas/delegate/schema.zmodel (1 hunks)
  • packages/runtime/test/schemas/delegate/typecheck.ts (1 hunks)
  • packages/runtime/test/schemas/todo/input.ts (1 hunks)
  • packages/runtime/test/schemas/todo/models.ts (1 hunks)
  • packages/runtime/test/schemas/todo/schema.ts (1 hunks)
  • packages/runtime/test/schemas/todo/todo.zmodel (1 hunks)
  • packages/runtime/test/schemas/typing/input.ts (1 hunks)
  • packages/runtime/test/schemas/typing/models.ts (1 hunks)
  • packages/runtime/test/schemas/typing/schema.ts (7 hunks)
  • packages/runtime/test/schemas/typing/schema.zmodel (1 hunks)
  • packages/runtime/test/schemas/typing/typecheck.ts (5 hunks)
  • packages/runtime/test/scripts/generate.ts (1 hunks)
⛔ Files not processed due to max files limit (35)
  • packages/runtime/test/test-schema.ts
  • packages/runtime/test/typing/generate.ts
  • packages/runtime/test/typing/models.ts
  • packages/runtime/test/utils.ts
  • packages/runtime/tsup.config.ts
  • packages/sdk/package.json
  • packages/sdk/src/model-utils.ts
  • packages/sdk/src/prisma/prisma-schema-generator.ts
  • packages/sdk/src/schema/schema.ts
  • packages/sdk/src/ts-schema-generator.ts
  • packages/sdk/src/zmodel-code-generator.ts
  • packages/tanstack-query/package.json
  • packages/testtools/package.json
  • packages/typescript-config/package.json
  • packages/zod/package.json
  • samples/blog/package.json
  • samples/blog/zenstack/models.ts
  • samples/blog/zenstack/schema.prisma
  • samples/blog/zenstack/schema.ts
  • samples/blog/zenstack/schema.zmodel
  • tests/e2e/package.json
  • tests/e2e/prisma-consistency/attributes.test.ts
  • tests/e2e/prisma-consistency/basic-models.test.ts
  • tests/e2e/prisma-consistency/compound-ids.test.ts
  • tests/e2e/prisma-consistency/datasource.test.ts
  • tests/e2e/prisma-consistency/enums.test.ts
  • tests/e2e/prisma-consistency/field-types.test.ts
  • tests/e2e/prisma-consistency/relation-validation.test.ts
  • tests/e2e/prisma-consistency/relations-many-to-many.test.ts
  • tests/e2e/prisma-consistency/relations-one-to-many.test.ts
  • tests/e2e/prisma-consistency/relations-one-to-one.test.ts
  • tests/e2e/prisma-consistency/relations-self.test.ts
  • tests/e2e/prisma-consistency/test-utils.ts
  • tests/e2e/prisma-consistency/unique-constraints.test.ts
  • turbo.json
🧰 Additional context used
🧬 Code Graph Analysis (31)
packages/runtime/test/client-api/name-mapping.test.ts (1)
packages/runtime/src/schema/expression.ts (1)
  • ExpressionUtils (16-112)
packages/language/src/validators/expression-validator.ts (2)
packages/language/src/utils.ts (1)
  • isDataFieldReference (138-140)
packages/language/src/generated/ast.ts (2)
  • isNullExpr (591-593)
  • isThisExpr (721-723)
packages/language/src/validators/common.ts (1)
packages/language/src/generated/ast.ts (1)
  • isDataField (344-346)
packages/cli/src/actions/validate.ts (1)
packages/cli/src/actions/action-utils.ts (2)
  • getSchemaFile (8-33)
  • loadSchemaDocument (35-45)
packages/runtime/test/schemas/delegate/schema.ts (2)
packages/runtime/src/schema/expression.ts (1)
  • ExpressionUtils (16-112)
packages/sdk/src/schema/schema.ts (1)
  • SchemaDef (10-18)
packages/runtime/test/client-api/default-values.test.ts (1)
packages/runtime/src/schema/expression.ts (1)
  • ExpressionUtils (16-112)
packages/runtime/test/schemas/basic/helper.ts (2)
packages/sdk/src/schema/schema.ts (1)
  • DataSourceProviderType (4-4)
packages/runtime/test/schemas/basic/schema.ts (1)
  • schema (9-279)
packages/language/test/mixin.test.ts (2)
packages/language/test/utils.ts (2)
  • loadSchema (8-16)
  • loadSchemaWithError (18-30)
packages/language/src/generated/ast.ts (4)
  • DataModel (377-387)
  • DataModel (389-389)
  • TypeDef (725-733)
  • TypeDef (735-735)
packages/runtime/src/client/crud/operations/update.ts (3)
packages/runtime/src/client/crud-types.ts (1)
  • WhereInput (208-233)
packages/sdk/src/schema/schema.ts (1)
  • GetModels (108-108)
packages/runtime/src/plugins/policy/errors.ts (1)
  • RejectedByPolicyError (4-11)
packages/language/src/ast.ts (1)
packages/language/src/generated/ast.ts (2)
  • DataField (333-340)
  • DataField (342-342)
packages/runtime/test/schemas/basic/models.ts (2)
packages/runtime/test/schemas/todo/models.ts (1)
  • User (12-12)
packages/runtime/test/schemas/typing/models.ts (5)
  • User (10-10)
  • Post (11-11)
  • Profile (12-12)
  • Role (18-18)
  • Role (19-19)
packages/runtime/src/client/crud/operations/delete.ts (2)
packages/runtime/src/client/errors.ts (1)
  • NotFoundError (27-31)
packages/runtime/src/client/crud-types.ts (1)
  • DeleteManyArgs (881-884)
packages/language/test/utils.ts (2)
packages/language/src/index.ts (1)
  • loadDocument (20-103)
packages/common-helpers/src/tiny-invariant.ts (1)
  • invariant (4-14)
packages/language/test/delegate.test.ts (2)
packages/language/test/utils.ts (2)
  • loadSchema (8-16)
  • loadSchemaWithError (18-30)
packages/language/src/ast.ts (1)
  • DataModel (49-54)
packages/language/src/validators/function-invocation-validator.ts (2)
packages/language/src/generated/ast.ts (7)
  • DataModelAttribute (395-400)
  • DataModelAttribute (402-402)
  • DataFieldAttribute (348-353)
  • DataFieldAttribute (355-355)
  • isDataModelAttribute (404-406)
  • isDataFieldAttribute (357-359)
  • isDataModel (391-393)
packages/language/src/utils.ts (1)
  • isDataFieldReference (138-140)
packages/cli/test/validate.test.ts (1)
packages/cli/test/utils.ts (2)
  • createProject (12-18)
  • runCli (20-23)
packages/runtime/src/client/result-processor.ts (3)
packages/runtime/src/client/constants.ts (1)
  • DELEGATE_JOINED_FIELD_PREFIX (19-19)
packages/sdk/src/schema/schema.ts (1)
  • GetModels (108-108)
packages/runtime/src/client/query-utils.ts (1)
  • getIdValues (146-152)
packages/runtime/src/client/crud/dialects/sqlite.ts (2)
packages/runtime/src/client/query-utils.ts (1)
  • getDelegateDescendantModels (317-330)
packages/runtime/src/client/constants.ts (1)
  • DELEGATE_JOINED_FIELD_PREFIX (19-19)
packages/language/src/zmodel-scope.ts (2)
packages/language/src/generated/ast.ts (3)
  • isDataModel (391-393)
  • isDataField (344-346)
  • isMemberAccessExpr (555-557)
packages/language/src/utils.ts (2)
  • getRecursiveBases (164-185)
  • getAllFields (532-555)
packages/runtime/test/schemas/typing/typecheck.ts (1)
packages/runtime/test/schemas/typing/models.ts (2)
  • IdentityProvider (17-17)
  • Identity (16-16)
packages/runtime/test/client-api/delegate.test.ts (3)
packages/runtime/test/utils.ts (1)
  • createTestClient (75-155)
packages/runtime/src/client/crud/dialects/postgresql.ts (1)
  • provider (27-29)
packages/runtime/src/client/crud/dialects/sqlite.ts (1)
  • provider (27-29)
packages/runtime/src/client/crud/validator.ts (5)
packages/runtime/src/client/crud/operations/base.ts (1)
  • schema (89-91)
samples/blog/zenstack/schema.ts (1)
  • schema (9-228)
packages/common-helpers/src/tiny-invariant.ts (1)
  • invariant (4-14)
packages/sdk/src/schema/schema.ts (1)
  • FieldDef (59-74)
packages/runtime/src/client/query-utils.ts (1)
  • getDiscriminatorField (304-315)
packages/runtime/src/client/contract.ts (4)
packages/sdk/src/schema/schema.ts (3)
  • SchemaDef (10-18)
  • GetModels (108-108)
  • IsDelegateModel (263-266)
packages/runtime/src/client/crud-types.ts (21)
  • FindArgs (558-577)
  • SelectSubset (430-436)
  • ModelResult (136-180)
  • FindUniqueArgs (582-584)
  • CreateArgs (590-595)
  • CreateManyArgs (597-597)
  • BatchResult (202-202)
  • CreateManyAndReturnArgs (599-605)
  • UpdateArgs (728-734)
  • UpdateManyArgs (736-739)
  • Subset (426-428)
  • UpdateManyAndReturnArgs (741-747)
  • UpsertArgs (755-762)
  • DeleteArgs (874-879)
  • DeleteManyArgs (881-884)
  • CountArgs (890-895)
  • CountResult (901-911)
  • AggregateArgs (917-931)
  • AggregateResult (957-985)
  • GroupByArgs (999-1014)
  • GroupByResult (1016-1050)
packages/runtime/src/client/promise.ts (1)
  • ZenStackPromise (7-13)
packages/runtime/src/utils/type-utils.ts (1)
  • Simplify (11-17)
packages/language/src/zmodel-workspace-manager.ts (3)
packages/language/src/generated/ast.ts (3)
  • Model (559-563)
  • Model (565-565)
  • isPlugin (628-630)
packages/language/src/utils.ts (1)
  • getLiteral (269-283)
packages/language/src/constants.ts (1)
  • PLUGIN_MODULE_NAME (26-26)
packages/runtime/src/client/query-builder.ts (2)
packages/sdk/src/schema/schema.ts (8)
  • ScalarFields (168-182)
  • ForeignKeyFields (184-188)
  • GetModelField (137-141)
  • GetModelFields (132-135)
  • GetModelFieldType (151-155)
  • ModelFieldIsOptional (217-221)
  • SchemaDef (10-18)
  • GetModels (108-108)
packages/runtime/src/utils/type-utils.ts (1)
  • MapBaseType (37-37)
packages/language/src/validators/attribute-application-validator.ts (5)
packages/language/src/generated/ast.ts (16)
  • DataModelAttribute (395-400)
  • DataModelAttribute (402-402)
  • DataFieldAttribute (348-353)
  • DataFieldAttribute (355-355)
  • InternalAttribute (520-525)
  • InternalAttribute (527-527)
  • DataModel (377-387)
  • DataModel (389-389)
  • isDataField (344-346)
  • DataField (333-340)
  • DataField (342-342)
  • isDataModel (391-393)
  • isArrayExpr (193-195)
  • isReferenceExpr (697-699)
  • Attribute (197-204)
  • Attribute (206-206)
packages/language/src/validators/common.ts (1)
  • AstValidator (7-12)
packages/language/src/ast.ts (1)
  • DataModel (49-54)
packages/language/src/utils.ts (4)
  • getStringLiteral (72-74)
  • getAllAttributes (557-579)
  • isDataFieldReference (138-140)
  • hasAttribute (52-54)
packages/sdk/src/model-utils.ts (1)
  • hasAttribute (58-63)
packages/runtime/src/client/crud/dialects/postgresql.ts (2)
packages/runtime/src/client/query-utils.ts (1)
  • getDelegateDescendantModels (317-330)
packages/runtime/src/client/constants.ts (1)
  • DELEGATE_JOINED_FIELD_PREFIX (19-19)
packages/runtime/src/client/plugin.ts (1)
packages/runtime/src/client/contract.ts (1)
  • ClientContract (50-159)
packages/runtime/src/client/helpers/schema-db-pusher.ts (1)
packages/sdk/src/schema/schema.ts (1)
  • ModelDef (20-36)
packages/language/src/validators/datamodel-validator.ts (6)
packages/language/src/validators/common.ts (1)
  • validateDuplicatedDeclarations (17-43)
packages/language/src/utils.ts (4)
  • getAllFields (532-555)
  • getAllAttributes (557-579)
  • getUniqueFields (242-256)
  • isDelegateModel (153-155)
packages/language/src/generated/ast.ts (7)
  • DataModel (377-387)
  • DataModel (389-389)
  • isDataModel (391-393)
  • DataField (333-340)
  • DataField (342-342)
  • TypeDef (725-733)
  • TypeDef (735-735)
packages/language/src/validators/attribute-application-validator.ts (1)
  • validateAttributeApplication (436-442)
packages/sdk/src/model-utils.ts (1)
  • isDelegateModel (69-71)
packages/common-helpers/src/tiny-invariant.ts (1)
  • invariant (4-14)
packages/runtime/src/client/crud-types.ts (3)
packages/sdk/src/schema/schema.ts (23)
  • IsDelegateModel (263-266)
  • GetSubModels (114-119)
  • NonRelationFields (190-194)
  • SchemaDef (10-18)
  • GetModels (108-108)
  • ModelFieldIsOptional (217-221)
  • FieldIsArray (235-239)
  • RelationFieldType (208-215)
  • GetTypeDefs (127-127)
  • GetTypeDefFields (157-160)
  • TypeDefFieldIsOptional (223-227)
  • GetModelFields (132-135)
  • RelationFields (196-200)
  • GetModelFieldType (151-155)
  • GetModelField (137-141)
  • GetTypeDefField (162-166)
  • FieldHasDefault (247-255)
  • FieldIsRelationArray (257-261)
  • FieldType (202-206)
  • RelationInfo (50-57)
  • FieldIsDelegateDiscriminator (277-281)
  • ForeignKeyFields (184-188)
  • FieldIsDelegateRelation (268-275)
packages/runtime/src/utils/type-utils.ts (6)
  • Optional (3-3)
  • Simplify (11-17)
  • NullableIf (5-5)
  • WrapType (19-23)
  • MapBaseType (37-37)
  • OrArray (48-48)
packages/runtime/src/client/query-builder.ts (1)
  • MapBaseType (32-44)
🪛 markdownlint-cli2 (0.17.2)
TODO.md

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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)

🪛 YAMLlint (1.37.1)
.github/workflows/claude-code-review.yml

[error] 20-20: trailing spaces

(trailing-spaces)


[error] 27-27: trailing spaces

(trailing-spaces)


[error] 42-42: trailing spaces

(trailing-spaces)


[error] 51-51: trailing spaces

(trailing-spaces)


[error] 56-56: trailing spaces

(trailing-spaces)


[error] 64-64: trailing spaces

(trailing-spaces)


[error] 67-67: trailing spaces

(trailing-spaces)


[error] 70-70: trailing spaces

(trailing-spaces)


[error] 73-73: trailing spaces

(trailing-spaces)


[warning] 78-78: too many blank lines (1 > 0)

(empty-lines)

.github/workflows/claude.yml

[error] 42-42: trailing spaces

(trailing-spaces)


[error] 45-45: trailing spaces

(trailing-spaces)


[error] 48-48: trailing spaces

(trailing-spaces)


[error] 51-51: trailing spaces

(trailing-spaces)


[error] 54-54: trailing spaces

(trailing-spaces)


[error] 60-60: trailing spaces

(trailing-spaces)


[warning] 64-64: too many blank lines (1 > 0)

(empty-lines)

⏰ 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). (3)
  • GitHub Check: claude-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (207)
package.json (2)

3-3: Version bump looks good
Nothing else changed in this manifest, and the new alpha tag is consistent with the rest of the PR.


29-33: Verify intentional use of catalog: placeholder for TypeScript
Using the pseudo-specifier catalog: instead of a real semver range can break downstream consumers outside your internal registry and cause CI failures if the catalog entry is missing or unpublished.

Please manually confirm the following:

  • No other workspace declares a concrete TypeScript version:
    rg -H '"typescript":' --glob '**/package.json' | grep -v 'catalog:'
  • Your registry’s catalog actually contains and publishes an entry named typescript (otherwise clients will not resolve a version):
    # Example—adjust to your registry/CLI
    pnpm catalog get typescript
packages/eslint-config/package.json (1)

3-3: LGTM – version bump only
No further issues in this scoped, private package.

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

3-3: LGTM – package metadata updated correctly
Everything else (exports map, files list, scripts) remains untouched and valid.

packages/ide/vscode/package.json (1)

4-4: LGTM – extension version synchronised
The VS Code marketplace expects monotonically increasing versions; alpha.13 maintains that.

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

3-3: LGTM – generator version updated
No other manifest changes; publish workflow should proceed as before.

.vscode/tasks.json (1)

21-22: Confirm pnpm watch script exists.

tasks.json now invokes pnpm watch, but the workspace root must expose a matching script (e.g., via "watch": "turbo run build --watch" or similar). If the script is missing, Dev Container users will hit an immediate failure.

Run in repo root: pnpm run --silent watch --if-present || echo "❌ no watch script" to verify.

.prettierignore (1)

2-7: Pattern refinements look good.

Limiting ignores to test/** and samples/** keeps generated artefacts out of commit diffs while still formatting first-class source. No issues spotted.

CLAUDE.md (1)

59-63: SQLite driver mismatch
The bullet lists better-sqlite3 as the SQLite driver, yet Kysely’s official adapter for better-sqlite3 is still community status and kysely 0.25+ defaults to @sqlite.org/sqlite. Ensure the driver mentioned matches what @zenstackhq/runtime actually imports; otherwise update here to prevent setup errors.

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

2-2: Import path updated – ensure old helper removed
../schemas/basic replaces ../test-schema. Verify that packages/runtime/test/test-schema.* (and any ts-generated artefacts) are deleted; lingering files may shadow the new schema in path resolution and cause silent test contamination.

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

2-2: Side-effect of schema switch on snapshot tests
Moving to basic schema changes default model policy/settings. Any snapshot-based assertions (e.g., SQL text, JSON outputs) in downstream tests may now differ. Re-run the full suite and update snapshots to avoid flaky CI.

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

3-3: Consistent use of shared basic schema – looks good

Importing from ../schemas/basic aligns this test with the new centralized schema package and the relative path resolves correctly from client-api/. No further changes needed.

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

5-5: Schema path updated to shared module – no issues found

The switch to ../schemas/basic keeps the plugin tests in sync with the new unified schema while preserving the exported schema identifier. Looks correct.

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

3-3: Unified schema import enhances consistency

Path change to ../schemas/basic is accurate for the client-api/group-by directory and matches other tests. Good cleanup.

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

3-3: Import path refactor verified

The new relative import resolves to packages/runtime/test/schemas/basic, ensuring all aggregate tests run against the consolidated schema. Approved.

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

3-3: Centralized schema reference confirmed

../schemas/basic is the correct relative path from client-api/transaction and keeps transaction tests aligned with the shared schema definitions.

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

3-3: Import path update looks correct.

Switching to the centralized ../schemas/basic keeps the suite consistent with other tests.

packages/runtime/test/policy/read.test.ts (1)

5-5: Consistent schema source.

Good move to the shared basic schema – avoids drift across policy and client-API tests.

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

3-3: Aligned with new schema hierarchy.

Import now matches other test files; no further action required.

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

3-3: Uniform schema import.

Change is straightforward and correct.

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

3-3: Path update acknowledged.

Importing from the shared basic schema keeps the count tests aligned with the rest of the suite.

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

3-3: Centralized schema import looks correct

The switch to ../schemas/basic keeps this test consistent with the new shared schema module. No further action needed.

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

3-3: Consistent schema path – good move

Importing schema from the unified ../schemas/basic module aligns this file with the rest of the test suite. Looks fine.

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

5-5: Schema path updated correctly

This change mirrors the rest of the test updates; nothing else to flag.

packages/runtime/test/query-builder/query-builder.test.ts (1)

5-5: getSchema import updated — looks good

Using the shared basic schema helper keeps the query-builder tests in sync with other suites. No issues spotted.

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

3-3: Aligned schema import path – looks good

The switch to ../schemas/basic keeps the tests consistent with the new centralized schema module. No other changes needed.

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

3-3: Import path update verified

Importing schema from the consolidated ../schemas/basic module is correct and compiles cleanly.

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

4-4: Schema source updated successfully

The new import path matches the rest of the suite; no issues detected.

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

3-3: Consistent schema import confirmed

The test now relies on the shared basic schema; this aligns with other updated tests.

packages/runtime/test/schemas/todo/todo.zmodel (1)

76-76: LGTM: Nullable bio field adjustment

Making the bio field nullable is appropriate since it's marked with @ignore and won't be persisted to the database. This change improves the schema definition consistency for test purposes.

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

16-19: LGTM: Well-designed constant for delegate model support

The new DELEGATE_JOINED_FIELD_PREFIX constant is well-named and documented. The '$delegate$' prefix uses special characters that won't conflict with regular field names, making it safe for identifying joined delegate rows in query results.

packages/runtime/test/schemas/basic/index.ts (1)

1-2: LGTM: Clean barrel export pattern

This index file follows standard practices for centralizing module exports, making it easier to import schema components from a single location.

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

13-13: LGTM: Explicit model naming improves clarity

Adding the explicit name: 'Foo' property to the model definition makes the schema more self-documenting and consistent with other schema definitions in the codebase.


16-16: LGTM: Explicit field naming enhances consistency

Adding explicit name properties to the id and x fields improves schema clarity and aligns with naming conventions used elsewhere in the codebase. This makes the schema definition more explicit and maintainable.

Also applies to: 22-22

packages/cli/src/actions/generate.ts (2)

20-21: LGTM: Good timing measurement setup

Recording the start timestamp is a clean way to measure the generation process duration for user feedback.


45-45: LGTM: Helpful performance feedback for users

Adding the elapsed time to the success message provides valuable feedback to users about the generation performance. This is a nice UX improvement that helps with debugging and monitoring.

packages/language/vitest.config.ts (1)

1-4: LGTM! Standard Vitest configuration setup.

The configuration correctly merges the base config with package-specific overrides. The empty defineConfig({}) is appropriate when no package-specific configuration is needed.

packages/language/src/validators/common.ts (2)

2-2: LGTM! Import updated to align with AST refactoring.

The change from isDataModelField to isDataField is consistent with the broader refactoring to unify field handling under the DataField abstraction.


31-32: LGTM! Type guard usage updated correctly.

The function logic remains intact while using the new isDataField type guard. The filtering logic for inherited fields (checking x.$container !== container) is preserved correctly.

packages/runtime/test/policy/todo-sample.test.ts (3)

1-2: LGTM! Schema import updated to new organization.

The import change from dynamic schema generation to static schema import aligns with the new schema organization and simplifies test setup.


377-377: Good defensive programming with optional chaining.

Using r?.lists instead of r.lists prevents potential runtime errors if the query result is undefined, making the test more robust.


383-383: Consistent use of optional chaining.

Similar to the previous assertion, using r1?.lists maintains consistency and improves test safety.

packages/cli/src/actions/index.ts (2)

6-6: LGTM! Import added for new validate action.

The import follows the same pattern as other CLI actions and correctly imports the validate functionality.


8-8: LGTM! Export correctly exposes validate action.

The validate action is properly added to the exports, making it available as part of the CLI's public API alongside other actions.

packages/runtime/test/schemas/basic/helper.ts (1)

1-11: LGTM! Clean utility function for provider-specific schemas.

The getSchema function provides a clean way to create schema variants with different provider types. The generic type constraint ensures type safety, and the spread operator correctly preserves the original schema while overriding the provider.

packages/runtime/package.json (4)

3-3: LGTM: Version bump follows semantic versioning.

The alpha version increment from 3.0.0-alpha.12 to 3.0.0-alpha.13 is appropriate for continued alpha releases.


7-7: LGTM: Build script enhancement ensures generated files are current.

Adding pnpm test:generate after tsup-node ensures that generated test files are updated after the build process, which is good practice for maintaining consistency.


10-11: LGTM: Test script simplification and path update.

The test script simplification and the path update from test/typing/generate.ts to test/scripts/generate.ts suggests better organization of test utilities.


76-81: LGTM: Dependency restructuring aligns with peer dependency pattern.

Moving zod from direct dependencies to peer dependencies is appropriate since it's used internally but allows consumers to control the version. Adding pg as a peer dependency follows the same pattern as better-sqlite3.

packages/runtime/test/schemas/todo/models.ts (1)

1-15: LGTM: Well-structured auto-generated model types.

This auto-generated file follows the correct pattern with:

  • Appropriate warning header to prevent manual modifications
  • Consistent type alias exports using the generic $ModelResult type
  • Clean imports and exports structure

The file serves its purpose of providing strongly typed model result types for the todo schema.

packages/runtime/src/client/executor/name-mapper.ts (1)

266-266: LGTM: Correct filtering for delegate model inheritance.

The additional filter !fieldDef.originModel appropriately excludes inherited fields from delegate base models. This prevents inherited delegate fields from being treated as direct scalar fields of the current model, which is essential for proper polymorphic model handling.

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

400-406: LGTM: Improved type safety with explicit casting.

The explicit cast to Promise<unknown> improves TypeScript type inference and ensures consistent typing in the plugin hook system. This defensive typing practice enhances code maintainability and clarity.

packages/runtime/test/schemas/typing/schema.zmodel (3)

11-18: LGTM: Well-defined custom types for identity management.

The new Identity and IdentityProvider type definitions are well-structured:

  • Identity appropriately contains an array of identity providers
  • IdentityProvider has a required id and optional name field
  • The syntax follows ZenStack schema conventions correctly

These types provide a clean abstraction for managing user identity providers.


30-30: LGTM: Appropriate JSON field integration.

The new identity field on the User model correctly uses the @json annotation to store the custom Identity type as JSON. This allows for flexible storage of structured identity provider data while maintaining type safety.


21-29: LGTM: Formatting improvements enhance readability.

The spacing and alignment adjustments in the User model fields improve code readability without affecting functionality. The consistent formatting makes the schema easier to read and maintain.

packages/language/src/validators/function-invocation-validator.ts (3)

6-6: LGTM! Import updates align with unified field abstraction.

The changes from DataModelFieldAttribute to DataFieldAttribute and related type guards are consistent with the broader refactoring to unify field handling across data models and type definitions.

Also applies to: 13-13, 21-21


59-61: LGTM! Type handling correctly extended for unified field abstraction.

The validation logic properly supports both DataModelAttribute and DataFieldAttribute types, maintaining backward compatibility while enabling the new unified field handling.


179-179: LGTM! Function reference updated consistently with unified field abstraction.

The change from isDataModelFieldReference to isDataFieldReference maintains the same validation logic while using the updated utility function from the unified field handling refactor.

packages/cli/src/actions/validate.ts (1)

1-23: LGTM! Clean and well-structured CLI action implementation.

The validate action follows excellent patterns:

  • Proper separation of concerns using utility functions from action-utils
  • User-friendly success/failure messaging with colors
  • Correct error handling that maintains CLI exit code behavior
  • Simple, focused implementation that does one thing well

The code reuses existing utilities (getSchemaFile, loadSchemaDocument) which promotes consistency across CLI actions.

packages/language/src/validators/expression-validator.ts (2)

21-21: LGTM! Import updated consistently with unified field abstraction.

The change from isDataModelFieldReference to isDataFieldReference aligns with the broader refactoring effort to unify field handling across the language package.


152-153: LGTM! Validation logic updated consistently with unified field abstraction.

The usage of isDataFieldReference instead of isDataModelFieldReference maintains the same validation behavior while using the updated utility function. The validation logic for binary expressions remains correct:

  • Field-to-null comparisons in validation context are properly allowed
  • Unsupported field-to-field and field-to-this comparisons are correctly prevented

Also applies to: 207-208, 212-213

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

4-4: LGTM! Schema import updated for test consolidation.

The change from ../test-schema to ../schemas/basic aligns with the broader effort to standardize test schemas across client API tests, improving consistency and maintainability.


76-76: LGTM! Explicit ordering improves test reliability.

Adding explicit orderBy: { id: 'asc' } clauses to negative take tests makes the expected behavior clear and deterministic, removing dependency on potentially inconsistent default sorting behavior. This is a good practice for reliable test assertions.

Also applies to: 79-79

packages/cli/src/index.ts (3)

27-29: LGTM! Action handler follows established patterns.

The validateAction function correctly follows the same pattern as other CLI action handlers, with proper TypeScript typing and clean separation of concerns.


42-42: LGTM! CLI description updated with clear product tagline.

The updated description "ZenStack is a database access toolkit for TypeScript apps" provides a clear and concise explanation of the product's purpose.


122-122: LGTM! New validate command properly integrated.

The new validate command follows established CLI patterns with proper schema option integration and clear description. It provides a clean interface for schema validation functionality.

packages/language/package.json (3)

4-4: LGTM!

Version bump to 3.0.0-alpha.13 is appropriate and aligns with coordinated versioning across the monorepo packages.


40-49: LGTM!

The new "./utils" export follows the established pattern with proper dual package support (import/require) and aligns with the addition of src/utils.ts as a new entry point in the build configuration.


64-64: LGTM!

Addition of @zenstackhq/common-helpers as a devDependency with workspace reference is appropriate for internal tooling dependencies.

packages/language/test/mixin.test.ts (6)

1-4: LGTM!

Appropriate imports for testing framework, utilities, and AST types needed for mixin functionality testing.


5-24: LGTM!

Well-structured test for basic model mixin functionality. The test correctly verifies that a model can mix multiple types and that the mixin references are properly resolved.


26-50: LGTM!

Comprehensive test for nested mixin inheritance where types can mix other types, and models can then mix those composite types. The test properly validates the mixin chain.


52-69: LGTM!

Essential test for cyclic mixin detection. This validation prevents infinite recursion and ensures schema integrity.


71-88: LGTM!

Important test for detecting field name conflicts when mixing types. This prevents ambiguous field resolution at runtime.


90-109: LGTM!

Critical test for detecting duplicate attributes from mixins. The test correctly validates that unique attributes like @@id cannot be applied multiple times through mixin inheritance.

packages/cli/test/validate.test.ts (8)

1-5: LGTM!

Appropriate imports for file system operations, testing framework, and CLI test utilities.


6-36: LGTM!

Well-defined test fixtures with both valid and invalid schema examples. The invalid schema correctly demonstrates a validation error (missing authorId field for the relation).


38-44: LGTM!

Basic test case for successful validation of a valid schema. Correctly expects no error to be thrown.


46-51: LGTM!

Essential test case for validation failure. Correctly expects an error to be thrown when validating an invalid schema.


53-59: LGTM!

Good test for custom schema location support. The test properly renames the default schema file and validates using the custom path.


61-66: LGTM!

Important test for error handling when schema file doesn't exist. Correctly expects an error to be thrown.


68-82: LGTM!

Comprehensive test for package.json configuration support. The test properly sets up a custom schema location in package.json and validates that the CLI respects this configuration.


84-101: LGTM!

Good test for syntax error detection. The test uses a schema with a missing closing brace to trigger a syntax error and correctly expects validation to fail.

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

15-15: LGTM!

Addition of explicit name: 'Model' to the schema definition aligns with the systematic enhancement of schema metadata across the codebase.


18-57: LGTM!

Addition of explicit name properties to all field definitions follows the established pattern for schema metadata enhancement. The field names correctly match their object keys and don't affect the test functionality.

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

1-1: LGTM!

Addition of ExpressionBuilder import is necessary for the dialect-aware query building enhancements.


19-22: LGTM!

Excellent improvement replacing the generic table selection with dialect-aware buildSelectModel. This ensures proper handling of polymorphic models and delegate joins.


24-44: LGTM!

Well-implemented logic for selective field inclusion in aggregation queries. The code correctly:

  1. Collects fields from aggregation body (keys starting with '_')
  2. Filters out '_all' and only includes explicitly requested fields
  3. Uses buildSelectField for dialect-aware field selection
  4. Falls back to selecting literal 1 as '_all' when no fields are specified

This approach improves query precision and performance by only selecting fields that are actually needed for aggregation.

packages/language/test/delegate.test.ts (5)

6-22: LGTM! Well-structured delegate inheritance test.

The test correctly validates that models can inherit from delegate models and properly checks the AST relationships between base and derived models.


24-38: LGTM! Proper validation of delegate inheritance rules.

The test correctly verifies that inheritance is only allowed from delegate models and expects the appropriate error message.


40-55: LGTM! Essential cyclic inheritance detection test.

The test properly validates the prevention of cyclic inheritance chains, which is crucial for maintaining a valid inheritance hierarchy.


57-72: LGTM! Proper field duplication validation.

The test correctly validates that derived models cannot redefine fields from their base delegate models, maintaining inheritance integrity.


74-91: LGTM! Attribute uniqueness validation in inheritance.

The test correctly validates that certain attributes like @@id can only be applied once in an inheritance hierarchy, preventing conflicting definitions.

packages/cli/test/ts-schema-gen.test.ts (3)

185-221: LGTM! Comprehensive mixin merging test.

The test thoroughly validates that schema generation correctly merges fields and attributes from multiple mixins into the target model, preserving all field properties and constraints.


223-268: LGTM! Type definition inheritance test.

The test correctly validates that type definitions with inheritance are properly generated, including field merging and attribute inheritance from base types.


270-327: LGTM! Delegate model inheritance validation.

The test comprehensively validates schema generation for delegate model inheritance, including proper field merging, metadata preservation, and delegate-specific properties like isDelegate and baseModel.

packages/language/src/ast.ts (2)

2-2: LGTM! Updated imports for unified field types.

The import correctly includes DataField from the generated AST, aligning with the refactoring to consolidate field types under a unified abstraction.


53-53: LGTM! Consistent with field type unification.

The change from DataModelField[] to DataField[] is consistent with the broader refactoring to unify field types under the DataField abstraction.

packages/runtime/test/schemas/typing/typecheck.ts (5)

2-3: LGTM! Updated imports for new schema structure.

The import paths have been correctly updated to reflect the new schema organization, and the new type definitions Identity and IdentityProvider are properly imported.


31-31: LGTM! Added type definitions test to main flow.

The addition of typeDefs() call appropriately includes the new type definition tests in the main execution flow.


43-43: LGTM! Safe property access for new identity field.

The log statement correctly demonstrates usage of the new identity field with proper optional chaining to handle potential null/undefined values.


210-227: LGTM! Comprehensive type safety testing for identity field.

The identity field addition thoroughly tests the new type definitions with proper validation of required fields, optional fields, and TypeScript error expectations for type safety.


635-647: LGTM! Well-structured type definition usage demonstration.

The function effectively demonstrates proper usage of the new Identity and IdentityProvider types, providing both testing coverage and usage examples.

packages/runtime/test/schemas/basic/models.ts (1)

1-16: LGTM! Well-structured auto-generated model types.

The file follows established conventions for auto-generated model files with proper warning headers, consistent type exports using utility types, and appropriate enum handling.

packages/language/src/zmodel-scope.ts (4)

22-22: LGTM - Import changes support unified field handling.

The import of isDataField to replace separate field type predicates, along with getAllFields and getRecursiveBases, correctly supports the unified field handling approach throughout the scope provider.

Also applies to: 34-34, 37-37


148-148: LGTM - Consistent use of unified field predicate.

The replacement of separate field type checks with isDataField is consistent with the unified field handling approach and correctly handles both data model fields and type definition fields.

Also applies to: 156-156


196-196: LGTM - Unified field handling in collection predicate scope.

The use of isDataField for both reference and member access expressions in collection predicate scope resolution maintains consistency with the unified field approach.

Also applies to: 204-204


234-234: LGTM - Switch to unified field retrieval.

The replacement of getModelFieldsWithBases with getAllFields aligns with the unified field handling approach and should provide more comprehensive field resolution including mixins and inheritance.

packages/runtime/test/schemas/delegate/schema.ts (1)

1-466: Well-structured delegate model schema for comprehensive testing.

This auto-generated schema properly demonstrates:

  • Multi-level delegate inheritance (Asset -> Video -> RatedVideo)
  • Proper discriminator field configuration with isDiscriminator: true
  • Correct field inheritance tracking via originModel properties
  • Bidirectional relations with cascade delete behavior
  • Comprehensive field types and constraints

The nested delegate structure provides excellent test coverage for polymorphic model scenarios.

packages/runtime/test/schemas/todo/schema.ts (1)

1-396: Comprehensive todo schema with robust authorization rules.

This auto-generated schema demonstrates:

  • Multi-tenant architecture with Space, SpaceUser relationships
  • Complex authorization rules using @@allow and @@deny
  • Proper role-based access control (ADMIN role in SpaceUser)
  • Privacy controls (private lists)
  • Cascade delete relationships for data integrity
  • Comprehensive field validation and constraints

The authorization expressions correctly implement ownership, membership, and role-based access patterns typical in multi-tenant applications.

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

167-167: LGTM - Enhances plugin capabilities with client access.

Adding the client property to the $allOperations hook context improves consistency with the OnQueryHookContext type and enables plugins to access the full client API for more sophisticated behaviors.

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

111-114: LGTM! Clean implementation of custom type support

The addition of custom type definition handling is well-integrated, checking for type definitions in the schema before falling back to built-in type transformations.

packages/runtime/src/client/helpers/schema-db-pusher.ts (1)

80-96: Good improvement for unique constraint naming

Prefixing unique constraint names with the model name ensures uniqueness across models, which is essential for polymorphic model support.

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

47-59: Well-handled edge cases for update operations

The implementation correctly handles both policy violations and cascade delete scenarios. The distinction between these cases based on hasPolicyEnabled is appropriate.

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

218-774: Excellent type-safe enforcement for delegate models

The conditional type correctly excludes creation operations for delegate models at the type level, preventing compile-time errors when attempting invalid operations. This is a robust approach to enforcing the constraint that delegate models can only be created through their concrete subtypes.

packages/runtime/test/client-api/typed-json-fields.test.ts (5)

9-23: Schema definition looks well-structured for typed JSON field testing.

The custom types Identity and IdentityProvider with proper nesting and the @json attribute on the identity field provide good coverage for testing typed JSON functionality.


25-37: Test setup and teardown are properly configured.

Good use of provider-specific configuration and proper cleanup with client disconnection.


39-131: Comprehensive create operation test coverage.

The tests cover essential scenarios including null values, complete data, optional fields, extra fields preservation, and proper validation error handling for missing required fields. The validation test correctly expects failure when the required id field is omitted.


133-169: Find operation tests provide good coverage.

The tests appropriately verify retrieval of records with both null and populated JSON fields, using explicit IDs for deterministic behavior.


171-219: Update operation tests properly validate both success and error cases.

The tests appropriately verify successful updates with extra fields and correct validation error handling when required fields are missing.

packages/runtime/test/scripts/generate.ts (2)

18-27: Schema generation logic is well-implemented.

The function correctly handles output directory determination, plugin model discovery, and import path replacement for local testing. The synchronous file operations are appropriate for a build script.


1-8: Clean imports and proper ESM setup.

The imports are well-organized and the directory resolution using import.meta.url is the correct approach for ESM modules.

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

13-35: Excellent improvements to subquery construction.

The changes enhance maintainability and functionality by:

  • Centralizing the subquery name to avoid hardcoded strings
  • Using dialect.buildSelectModel for dialect-aware model selection supporting polymorphic models
  • Adding proper conditional field selection logic that handles explicit field selection and defaults appropriately

These changes align well with the broader dialect enhancements for polymorphic model support.


38-54: Consistent use of centralized subquery name in outer query.

The update to use the subQueryName variable instead of hardcoded strings maintains consistency with the subquery construction changes and improves maintainability.

packages/runtime/test/client-api/mixin.test.ts (3)

5-79: Comprehensive basic mixin test coverage.

The test effectively validates:

  • Field inheritance from mixins (timestamps in Foo model)
  • Attribute inheritance (unique constraint enforcement)
  • Required field validation from mixins
  • Constraint enforcement (duplicate name rejection)

The test scenarios provide good coverage of mixin behavior and validation.


81-123: Multi-level mixin inheritance test is well-designed.

The test validates that inheritance works correctly through multiple levels (Base1 -> Base2 -> Model A) and confirms all inherited fields are accessible during nested record creation.


125-148: Composite primary key inheritance test is thorough.

The test properly validates that composite primary keys defined in mixins (@@id([id1, id2])) are correctly inherited and functional in the derived model.

packages/runtime/test/schemas/delegate/models.ts (1)

1-16: Well-structured auto-generated model types file.

The file properly:

  • Includes clear warning against manual modification
  • Disables ESLint as appropriate for generated code
  • Uses consistent type alias pattern with ModelResult generic
  • Covers all delegate models mentioned in the schema

The generated structure follows best practices for auto-generated TypeScript files.

packages/runtime/test/schemas/typing/schema.ts (4)

8-8: LGTM! Import path updated correctly.

The import path has been updated to reflect the new module structure with an additional directory level.


15-69: LGTM! Explicit name properties added consistently.

The addition of explicit name properties to all models and fields improves schema introspection capabilities. The naming is consistent and matches the actual identifiers.


70-75: LGTM! New identity JSON field properly configured.

The new optional identity field is correctly configured with the Identity type and @json attribute for storing JSON data.


296-321: LGTM! Well-structured type definitions for identity management.

The new Identity and IdentityProvider type definitions are well-structured for authentication scenarios. The Identity type with a providers array and IdentityProvider with required id and optional name fields follow good design patterns.

packages/runtime/test/schemas/delegate/input.ts (1)

1-151: LGTM! Comprehensive auto-generated type definitions for delegate models.

This auto-generated file provides complete and consistent TypeScript type aliases for all CRUD operations across delegate models. The type coverage is comprehensive, including all major database operations (find, create, update, delete, aggregate, etc.) and utility types (WhereInput, Select, Include, Omit, GetPayload). The consistent pattern and proper generic parameterization indicate the code generation is working correctly.

packages/runtime/test/schemas/todo/input.ts (1)

1-111: LGTM! Consistent auto-generated type definitions for todo models.

This auto-generated file provides complete TypeScript type aliases for all CRUD operations across todo application models (Space, SpaceUser, User, List, Todo). The type coverage follows the same comprehensive pattern as other generated input files, ensuring consistency across different schema test suites.

packages/runtime/test/policy/utils.ts (2)

1-17: LGTM! Improved type safety with function overloads.

The addition of overloaded signatures provides better type precision - when passing a SchemaDef, you get a properly typed ClientContract<Schema>, while string inputs return Promise<any>. This pattern improves developer experience with better IntelliSense and type checking.


18-25: LGTM! Correct async implementation with proper option handling.

The implementation correctly passes through the schema and options while ensuring the PolicyPlugin is included. The type casting is necessary to handle the overloaded signatures properly.

packages/runtime/test/schemas/basic/input.ts (1)

1-91: LGTM! Consistent auto-generated type definitions for basic schema models.

This auto-generated file maintains the same comprehensive pattern as other input type files, providing complete TypeScript type aliases for all CRUD operations across basic schema models (User, Post, Comment, Profile). The consistency in structure ensures a uniform developer experience across different test schemas.

packages/runtime/test/schemas/typing/models.ts (1)

1-20: LGTM! Well-structured type definitions.

The auto-generated type exports follow a consistent pattern and properly distinguish between models (using $ModelResult) and type definitions (using $TypeDefResult). The dual export of the Role enum as both value and type is the correct approach.

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

114-117: Well-implemented schema introspection utilities.

The new functions isInheritedField, getDiscriminatorField, and getDelegateDescendantModels are correctly implemented with proper error handling and validation. The recursive implementation in getDelegateDescendantModels correctly prevents infinite loops using a Set.

Also applies to: 304-330

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

87-92: Improved field selection control.

The refactoring to use buildSelectModel and buildSelectAllFields provides better control over field selection and properly respects the omit option. This aligns well with the delegate model support requirements.

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

39-51: Excellent handling of user-defined types.

The enhanced transformPrimitive method now correctly identifies and serializes user-defined types as JSON, while maintaining the existing behavior for built-in types. The defensive check for typeDefs existence is a good practice.

packages/runtime/test/schemas/typing/input.ts (1)

1-131: Comprehensive generated type definitions.

The auto-generated input types provide complete coverage of all CRUD operations for each model. The consistent naming convention and comprehensive operation coverage ensure type safety across the client API.

packages/runtime/test/schemas/delegate/schema.zmodel (1)

1-58: Schema structure looks good!

The polymorphic delegate model hierarchy is well-designed:

  • Asset serves as the base delegate with common fields
  • Video extends Asset and also acts as a delegate for further specialization
  • RatedVideo and Image are concrete implementations
  • All relations properly use cascade deletes for referential integrity
packages/runtime/src/client/query-builder.ts (1)

21-30: Type filtering correctly hides inherited delegate fields.

The updated ToKyselyTable type properly excludes fields where originModel is a string, ensuring that inherited fields from delegate base models are not exposed in the query builder interface. This is the correct approach for managing polymorphic model fields.

packages/language/src/zmodel-linker.ts (1)

23-516: Field type unification implemented consistently.

All references to DataModelField and DataModelFieldType have been properly replaced with the unified DataField and DataFieldType types throughout the linker. The changes maintain the same functionality while simplifying the type system.

packages/language/res/stdlib.zmodel (2)

222-226: Good addition of @@@once constraint.

The new @@@once attribute properly enforces single application of critical attributes like @id, @unique, and @@id. This prevents configuration errors where multiple primary keys or unique constraints might be accidentally defined.

Also applies to: 235-235, 250-250, 262-262


723-737: Useful metadata and deprecation attributes added.

The new @@meta/@meta attributes provide flexible metadata attachment capabilities, while @@@deprecated enables proper deprecation warnings. These additions improve extensibility and API evolution support.

packages/runtime/test/schemas/basic/schema.zmodel (4)

1-8: LGTM!

The datasource and plugin configurations are appropriate for a test schema.


10-19: Good use of type composition for shared fields.

The CommonFields type effectively promotes DRY principles by centralizing common field definitions that can be reused across models.


21-31: Well-structured user model with appropriate access controls.

The access policies correctly implement the principle of least privilege - users have full control over their own records while maintaining read visibility for authenticated users.


33-45: Secure access control pattern with proper cascade configuration.

The deny-first approach followed by specific allow rules provides robust security. The cascade delete ensures data consistency when users are removed.

packages/language/src/zmodel-workspace-manager.ts (3)

1-31: LGTM!

The imports are appropriate for the plugin loading functionality being added.


74-106: Well-implemented plugin discovery logic.

The code correctly discovers plugin declarations from loaded documents and efficiently tracks unique providers using a Set. The defensive programming with null checks ensures robustness.


141-145: Excellent optimization with early exit.

The early exit when all plugins are loaded is a smart performance optimization that prevents unnecessary filesystem traversal.

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

1-32: LGTM!

The explicit type imports improve code clarity and the new utility imports support the discriminator field handling.


228-243: Clean extension to support custom type definitions.

The code elegantly checks for custom types before falling back to primitive types, maintaining backward compatibility while adding new functionality.


245-269: Well-implemented type definition schema generation with efficient caching.

The method correctly handles complex type definitions with proper support for arrays and optional fields. The caching strategy with prefixed keys prevents collisions.


716-719: Correct handling of discriminator fields in delegate models.

The code properly excludes discriminator fields from create operations since they are auto-assigned based on the model type. This prevents users from incorrectly setting discriminator values.

Also applies to: 807-814

packages/runtime/test/client-api/delegate.test.ts (6)

1-77: Comprehensive test setup with proper multi-provider support.

The test setup correctly demonstrates polymorphic model hierarchies with multi-level delegation and ensures compatibility across different database providers.


78-243: Thorough coverage of delegate model creation constraints and behaviors.

The tests effectively validate that delegate base models cannot be created directly, while derived models work correctly with proper discriminator auto-assignment. The atomicity test is particularly valuable for ensuring data integrity.


245-353: Excellent validation of polymorphic query behavior.

The tests thoroughly verify that queries through base models correctly return derived model data with all fields accessible, demonstrating proper polymorphic behavior.


599-937: Thorough update operation testing with proper constraint validation.

The tests effectively cover update scenarios across the inheritance hierarchy and correctly validate constraints like the unsupported limit option for polymorphic models.


939-1072: Comprehensive delete operation coverage with cascade behavior validation.

The tests effectively verify that deletions properly cascade through the polymorphic hierarchy and that related records are cleaned up correctly.


1074-1213: Well-structured aggregation tests across polymorphic models.

The tests properly validate that aggregation operations correctly process data across the entire inheritance hierarchy.

packages/runtime/test/schemas/delegate/typecheck.ts (4)

1-70: Excellent TypeScript discriminated union type testing.

The tests effectively validate that TypeScript properly narrows types based on discriminator values and prevents access to fields that don't exist on the base type.


72-111: Comprehensive type-level validation of creation constraints.

The tests effectively ensure TypeScript prevents delegate base model creation and discriminator field assignment at compile time, providing excellent developer experience.


113-163: Proper type-level enforcement of discriminator immutability.

The tests correctly ensure that discriminator fields cannot be modified through any update operation, maintaining data integrity at the type level.


165-174: Correct validation of query builder table schema awareness.

The tests properly verify that the query builder API reflects the actual database table structure rather than the composed model view.

packages/language/src/zmodel.langium (2)

69-70: LGTM! Clean unification of field types.

The consolidation of DataModelField and TypeDefField into DataField for both ReferenceTarget and MemberAccessTarget types simplifies the grammar and aligns with the broader refactoring effort.

Also applies to: 98-98


183-198: LGTM! Well-structured field definitions.

The unified DataField and DataFieldType rules provide a clean abstraction for fields across both data models and type definitions. The addition of mixin support to TypeDef is consistent with the overall design.

packages/language/src/validators/attribute-application-validator.ts (5)

55-73: LGTM! Good addition of validation context.

The optional contextDataModel parameter enables proper validation in inheritance and mixin scenarios while maintaining backward compatibility.


130-138: LGTM! Well-implemented deprecation warnings.

The deprecation check correctly identifies deprecated attributes and provides helpful warning messages with fallback to a default message.


139-155: LGTM! Robust duplicate attribute detection.

The duplication check correctly enforces the @@@once constraint by checking both local and inherited attributes when a context is provided.


221-262: LGTM! Comprehensive unique constraint validation.

The enhanced validation properly handles:

  • Empty field arrays (good catch!)
  • Both @@unique and @@id attributes
  • Prevention of using inherited delegate fields in unique constraints

378-434: LGTM! Thorough field type validation.

The isValidAttributeTarget function provides comprehensive validation for attribute applicability based on field types, with clear type mappings and proper handling of all field types.

packages/language/src/validators/datamodel-validator.ts (3)

35-43: LGTM! Well-structured validation flow.

The updated validation method properly:

  • Uses getAllFields to include inherited fields in duplicate checks
  • Adds explicit mixin and inheritance validation
  • Maintains a logical validation order

258-265: LGTM! Important self-relation constraint.

Requiring a name in @relation for self-referential fields is a good practice that prevents ambiguity and improves schema clarity.


332-345: LGTM! Correct many-to-many relation validation.

The validation properly enforces that implicit many-to-many relations cannot have explicit fields or references, which aligns with standard ORM behavior.

packages/language/src/utils.ts (3)

532-555: LGTM! Robust recursive field collection.

The getAllFields implementation correctly:

  • Prevents infinite recursion with cycle detection
  • Maintains proper field precedence (mixins → base → own)
  • Safely handles unresolved references with invariants
  • Respects the @ignore attribute

557-579: LGTM! Consistent attribute collection.

The getAllAttributes implementation properly mirrors the getAllFields pattern, maintaining consistency in the codebase while correctly handling inheritance and mixins.


3-3: Abstract file system operations for browser compatibility

The import of Node.js fs in packages/language/src/utils.ts (line 3) and its use in resolveImport (lines 401–402) may break if this code is ever run in a browser environment. If browser support is required, consider:

  • Replacing direct fs calls with a pluggable file‐system interface (e.g., Langium’s FS abstraction)
  • Allowing injection or mocking of the file system at runtime

Please verify whether this package must support browser targets and adjust the FS usage accordingly.

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

48-58: LGTM! Clean delegate model join implementation.

The buildSelectModel method correctly constructs the join chain for delegate inheritance, recursively joining all base models.


92-110: LGTM! Improved field reference handling.

The centralized field reference construction using originModel properly handles inherited fields and simplifies the filter building logic.


910-970: LGTM! Excellent code organization.

Moving abstract methods to a dedicated section at the bottom improves code readability and makes the class structure clearer.

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

7-34: LGTM! Well-organized imports for delegate model support.

The new imports properly support the polymorphic delegate model functionality and improve type safety by using model-specific field accessors.


51-80: Excellent implementation of delegate model result types.

The discriminated union approach for delegate models is well-designed, ensuring type safety by fixating the discriminator field for each sub-model in the union.


479-499: Well-structured type mapping with improved specificity.

The refactoring to model-specific type mappers (MapModelFieldType, MapTypeDefFieldType) and the addition of type definition support enhance type safety and align with the schema improvements.


615-620: Correct enforcement of discriminator field immutability.

Preventing manual assignment of discriminator fields in both create and update operations ensures data integrity in polymorphic model hierarchies.

Also applies to: 770-774


656-658: Appropriate restrictions for delegate relation operations.

The exclusion of 'create', 'createMany', 'connectOrCreate', and 'upsert' operations for delegate relations correctly enforces the constraints of polymorphic models.

Also applies to: 845-848, 867-868


190-201: Well-designed TypeDefResult type for custom type definitions.

The implementation correctly handles field optionality in type definitions using TypeScript's mapped types and conditional types.


7-34: LGTM! Import additions support delegate model functionality.

The new imports for delegate model support (FieldIsDelegateDiscriminator, FieldIsDelegateRelation, GetModelDiscriminator, GetSubModels, IsDelegateModel) and type definitions (GetTypeDefField, GetTypeDefFields, GetTypeDefs, TypeDefFieldIsOptional) are well-aligned with the polymorphic model enhancements mentioned in the AI summary.


58-79: Excellent polymorphic delegate model support.

The conditional logic for delegate models is well-designed:

  • IsDelegateModel check routes to appropriate result type
  • DelegateUnionResult creates proper union types for sub-models
  • Discriminator field fixation ensures type safety with GetModelDiscriminator
  • Falls back to standard model result for non-delegate models

This implementation correctly handles the polymorphic nature of delegate models where queries can return any sub-model type.


479-499: Excellent refactoring to model-specific field mapping.

The introduction of MapModelFieldType and MapTypeDefFieldType provides better type specificity compared to generic field accessors. Key improvements:

  • MapFieldDefType now supports enums, type definitions (TypeDefResult), and base types
  • Type definition support via GetTypeDefs<Schema> and TypeDefResult<Schema, T['type']>
  • Maintains proper optional/array wrapping with WrapType

This refactoring significantly improves type safety and enables custom type definition support.


190-200: Well-designed TypeDefResult for custom type definitions.

The TypeDefResult type effectively handles custom type definitions with:

  • Proper field mapping via MapTypeDefFieldType
  • Conditional optionality using TypeDefFieldIsOptional
  • Clean use of Optional utility for optional field handling
  • Support for reusable composite types across the schema

This addition enables flexible custom type definitions as mentioned in the AI summary.


616-620: Correct exclusion of discriminator fields from user input.

Preventing assignment of discriminator fields in create operations is essential for delegate model integrity:

  • FieldIsDelegateDiscriminator check ensures discriminator fields are system-managed
  • Prevents user from assigning incorrect discriminator values
  • Maintains consistency in polymorphic model hierarchies

This safety measure is critical for proper delegate model functionality.


657-657: Appropriate restrictions for delegate model relations.

Excluding create, createMany, and connectOrCreate operations for delegate relations is correct because:

  • Delegate models are abstract base types that shouldn't be directly instantiated
  • Only concrete sub-models should be creatable
  • connect operations remain available for referencing existing concrete instances

This restriction maintains the integrity of the polymorphic model hierarchy.


213-226: Consistent model-specific type usage improves type safety.

The systematic replacement of generic field accessors with model-specific ones (GetModelFields, GetModelFieldType, ModelFieldIsOptional) throughout the codebase:

  • Enhances type specificity and IDE support
  • Enables model-specific behaviors like delegate model handling
  • Maintains consistency across all CRUD operation types
  • Improves error detection at compile time

This refactoring significantly strengthens the type system while maintaining backward compatibility.


934-943: NumericFields type properly updated for consistency.

The update to use GetModelFields and GetModelFieldType maintains the same functional logic while improving type specificity:

  • Correctly identifies numeric field types (Int, Float, BigInt, Decimal)
  • Properly excludes array fields from numeric operations
  • Consistent with the file's systematic refactoring to model-specific types
packages/runtime/src/client/crud/operations/base.ts (9)

146-146: Good integration with dialect layer for polymorphic queries.

The use of buildSelectModel and buildSelectAllFields properly delegates polymorphic model handling to the dialect layer. The addition of query IDs enhances error tracking and debugging capabilities.

Also applies to: 191-191, 207-218


400-402: Correct enforcement of delegate model creation rules.

The validation preventing direct creation of delegate models ensures data integrity in the polymorphic hierarchy.


558-590: Well-implemented base model creation for polymorphic hierarchies.

The method correctly:

  • Separates fields between base and derived models
  • Sets the discriminator field appropriately
  • Propagates ID fields from base to derived models

This ensures proper polymorphic model instantiation.


1077-1094: Smart handling of filters in polymorphic model updates.

The logic to read IDs first when the filter might reference base model fields is a good solution to handle the complexity of polymorphic hierarchies.


1329-1331: Appropriate restrictions for polymorphic model batch updates.

Disabling limit-based updates for polymorphic models is the right choice given the complexity of multi-table operations.


2062-2068: Comprehensive cascade handling for polymorphic deletions.

The implementation correctly handles both downward cascades (through base model deletion) and upward cascades (through processDelegateRelationDelete), ensuring referential integrity.

Also applies to: 2109-2109


2116-2143: Excellent solution for upward cascade deletions in polymorphic models.

This method addresses a critical edge case where automatic database cascades don't propagate upward through delegate hierarchies. The check for onDelete === 'Cascade' ensures it only acts when explicitly configured.


2196-2196: Good choice of default transaction isolation level.

Setting 'repeatable read' as the default isolation level is appropriate for complex CRUD operations, especially with polymorphic models that span multiple tables.


1445-1448: Useful utility methods for enhanced CRUD operations.

The addition of model prefixes in buildIdFieldRefs and helper methods like isNumericIncrementalUpdate and isIdFilter improve code clarity and support the polymorphic model operations.

Also applies to: 1201-1218

@claude
Copy link

claude bot commented Jul 28, 2025

Claude finished @ymc9's task —— View job


I'll analyze this and get back to you.

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: 0

🧹 Nitpick comments (7)
TODO.md (7)

10-12: Fix MD007 list-indent violations under “CLI”

Static analysis flags these three lines for using 4-space indents where 2 are expected. Align them with the markdown-lint rule.

-    - [x] validate
-    - [ ] format
-    - [ ] db seed
+  - [x] validate
+  - [ ] format
+  - [ ] db seed

14-14: Correct sub-task indent for “ZModel”

Indent should be 2 spaces (level-1 list), not 4.

-    - [ ] View support
+  - [ ] View support

52-52: Reduce indent depth in “Update” subsection

This third-level item is indented 8 spaces; 4 suffices per MD007.

-        - [x] Strict typing for checked/unchecked input
+    - [x] Strict typing for checked/unchecked input

61-61: Transactions list item: trim extra indentation

-    - [x] Transactions
+  - [x] Transactions

68-68: Custom procedures task: use 4-space (not 8-space) indent

-        - [ ] Custom procedures
+    - [ ] Custom procedures

76-77: Logging / Error system lines carry unnecessary extra spaces

-        - [x] Logging
-        - [x] Error system
+    - [x] Logging
+    - [x] Error system

88-90: Polymorphism subtasks: match 2-space indent rule

-    - [x] ZModel
-    - [x] Runtime
-    - [x] Typing
+  - [x] ZModel
+  - [x] Runtime
+  - [x] Typing
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 33ac58e and a0c79b0.

📒 Files selected for processing (5)
  • .github/workflows/claude-code-review.yml (1 hunks)
  • .github/workflows/claude.yml (1 hunks)
  • TODO.md (3 hunks)
  • packages/runtime/src/client/query-utils.ts (3 hunks)
  • packages/runtime/src/client/result-processor.ts (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .github/workflows/claude-code-review.yml
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/runtime/src/client/query-utils.ts
  • packages/runtime/src/client/result-processor.ts
  • .github/workflows/claude.yml
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
TODO.md

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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)


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

(MD007, ul-indent)

⏰ 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)

@ymc9 ymc9 added this pull request to the merge queue Jul 28, 2025
Merged via the queue into main with commit 30fc2fa Jul 28, 2025
8 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