-
-
Notifications
You must be signed in to change notification settings - Fork 12
merge dev to main (v3.0.0-alpha.13) #119
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
* 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>
WalkthroughThis 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
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120+ minutes
Possibly related PRs
Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
Documentation and Community
|
|
Claude finished @ymc9's task —— View job PR Review CompleteThis 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 AssessmentThis PR represents a well-structured release with significant new features. The code quality is generally high with comprehensive test coverage and proper error handling. ✅ StrengthsSecurity & GitHub Actions
Code Quality & Architecture
Test Coverage
|
There was a problem hiding this 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
TypeDefResulttype - 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)}`);
There was a problem hiding this 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 proceduresContinue the two-space rule for deeper levels.
.github/workflows/claude.yml (2)
40-64: Trailing spaces and blank-line lint errors.
yamllintflags 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: trueCLAUDE.md (3)
17-18: Pinningpnpmversion may create unnecessary churn
Hard-pinning topnpm@10.12.1forces 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 criticalThis keeps local developer experience flexible while CI still guarantees deterministic builds.
30-33: Clarify Prisma dependency scope
The doc statesnpx zenstack db pushand 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
Becausezenstack generatemust be rerun after every schema edit, add a tip to hook it into Turbo’s watch pipeline orpnpm devso contributors don’t forget. Small DX win.packages/runtime/test/client-api/raw-query.test.ts (1)
3-3: Type-only import – can beimport type
schemais 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 toimport typeto drop unused runtime code when transpiled.packages/language/tsup.config.ts (1)
7-7: Consider enabling code-splitting to avoid duplicate bundlesWith a third entry point (
utils) added andsplitting: false, common code will be duplicated acrossindex.js,ast.js, andutils.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/climoves to3.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 deletesWhile 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 behaviorReturning
nullfor 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" directorypackages/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
CommonFieldstype definition containsid,createdAt, andupdatedAtfields 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_modulesbut 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:
- Add unique identifiers to test data to prevent conflicts if tests run in parallel
- 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
WithClauseandExtendsClausein any order is convenient, it might lead to inconsistent code styles across the codebase. Consider enforcing a single canonical order (e.g., alwaysextendsbeforewith) 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
DataFieldAttributecorrectly replaces the previous field-specific attribute types. However, there's a TODO comment at line 255 about renamingDataModelAttributesince 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
DataModelAttributethat 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
buildSelectAllFieldsmethod 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
⛔ Files ignored due to path filters (3)
packages/language/src/generated/ast.tsis excluded by!**/generated/**packages/language/src/generated/grammar.tsis excluded by!**/generated/**pnpm-lock.yamlis 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 ofcatalog:placeholder for TypeScript
Using the pseudo-specifiercatalog: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 typescriptpackages/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: Confirmpnpm watchscript exists.
tasks.jsonnow invokespnpm 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/**andsamples/**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 listsbetter-sqlite3as the SQLite driver, yet Kysely’s official adapter for better-sqlite3 is still community status andkysely0.25+ defaults to@sqlite.org/sqlite. Ensure the driver mentioned matches what@zenstackhq/runtimeactually 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/basicreplaces../test-schema. Verify thatpackages/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 tobasicschema 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 sharedbasicschema – looks goodImporting from
../schemas/basicaligns this test with the new centralized schema package and the relative path resolves correctly fromclient-api/. No further changes needed.packages/runtime/test/plugin/mutation-hooks.test.ts (1)
5-5: Schema path updated to shared module – no issues foundThe switch to
../schemas/basickeeps the plugin tests in sync with the new unified schema while preserving the exportedschemaidentifier. Looks correct.packages/runtime/test/client-api/group-by.test.ts (1)
3-3: Unified schema import enhances consistencyPath change to
../schemas/basicis accurate for theclient-api/group-bydirectory and matches other tests. Good cleanup.packages/runtime/test/client-api/aggregate.test.ts (1)
3-3: Import path refactor verifiedThe 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/basicis the correct relative path fromclient-api/transactionand 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/basickeeps the suite consistent with other tests.packages/runtime/test/policy/read.test.ts (1)
5-5: Consistent schema source.Good move to the shared
basicschema – 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
basicschema 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 correctThe switch to
../schemas/basickeeps 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 moveImporting
schemafrom the unified../schemas/basicmodule 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 correctlyThis 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 goodUsing the shared
basicschema 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 goodThe switch to
../schemas/basickeeps 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 verifiedImporting
schemafrom the consolidated../schemas/basicmodule is correct and compiles cleanly.packages/runtime/test/plugin/query-lifecycle.test.ts (1)
4-4: Schema source updated successfullyThe 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 confirmedThe test now relies on the shared
basicschema; this aligns with other updated tests.packages/runtime/test/schemas/todo/todo.zmodel (1)
76-76: LGTM: Nullable bio field adjustmentMaking the
biofield nullable is appropriate since it's marked with@ignoreand 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 supportThe new
DELEGATE_JOINED_FIELD_PREFIXconstant 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 patternThis 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 clarityAdding 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 consistencyAdding explicit
nameproperties to theidandxfields 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 setupRecording the start timestamp is a clean way to measure the generation process duration for user feedback.
45-45: LGTM: Helpful performance feedback for usersAdding 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
isDataModelFieldtoisDataFieldis consistent with the broader refactoring to unify field handling under theDataFieldabstraction.
31-32: LGTM! Type guard usage updated correctly.The function logic remains intact while using the new
isDataFieldtype guard. The filtering logic for inherited fields (checkingx.$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?.listsinstead ofr.listsprevents 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?.listsmaintains 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
validateaction 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
getSchemafunction 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.12to3.0.0-alpha.13is appropriate for continued alpha releases.
7-7: LGTM: Build script enhancement ensures generated files are current.Adding
pnpm test:generateaftertsup-nodeensures 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.tstotest/scripts/generate.tssuggests better organization of test utilities.
76-81: LGTM: Dependency restructuring aligns with peer dependency pattern.Moving
zodfrom direct dependencies to peer dependencies is appropriate since it's used internally but allows consumers to control the version. Addingpgas a peer dependency follows the same pattern asbetter-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
$ModelResulttype- 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.originModelappropriately 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
IdentityandIdentityProvidertype definitions are well-structured:
Identityappropriately contains an array of identity providersIdentityProviderhas a requiredidand optionalnamefield- 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
identityfield on theUsermodel correctly uses the@jsonannotation to store the customIdentitytype 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
Usermodel 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
DataModelFieldAttributetoDataFieldAttributeand 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
DataModelAttributeandDataFieldAttributetypes, maintaining backward compatibility while enabling the new unified field handling.
179-179: LGTM! Function reference updated consistently with unified field abstraction.The change from
isDataModelFieldReferencetoisDataFieldReferencemaintains 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
isDataModelFieldReferencetoisDataFieldReferencealigns 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
isDataFieldReferenceinstead ofisDataModelFieldReferencemaintains 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-schemato../schemas/basicaligns 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 negativetaketests 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
validateActionfunction 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
validatecommand 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.13is 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 ofsrc/utils.tsas a new entry point in the build configuration.
64-64: LGTM!Addition of
@zenstackhq/common-helpersas 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
@@idcannot 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
nameproperties 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
ExpressionBuilderimport 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:
- Collects fields from aggregation body (keys starting with '_')
- Filters out '_all' and only includes explicitly requested fields
- Uses
buildSelectFieldfor dialect-aware field selection- 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
@@idcan 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
isDelegateandbaseModel.packages/language/src/ast.ts (2)
2-2: LGTM! Updated imports for unified field types.The import correctly includes
DataFieldfrom 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[]toDataField[]is consistent with the broader refactoring to unify field types under theDataFieldabstraction.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
IdentityandIdentityProviderare 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
IdentityandIdentityProvidertypes, 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
isDataFieldto replace separate field type predicates, along withgetAllFieldsandgetRecursiveBases, 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
isDataFieldis 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
isDataFieldfor 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
getModelFieldsWithBaseswithgetAllFieldsaligns 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
originModelproperties- 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
@@allowand@@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
clientproperty to the$allOperationshook context improves consistency with theOnQueryHookContexttype 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 supportThe 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 namingPrefixing 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 operationsThe implementation correctly handles both policy violations and cascade delete scenarios. The distinction between these cases based on
hasPolicyEnabledis appropriate.packages/runtime/src/client/contract.ts (1)
218-774: Excellent type-safe enforcement for delegate modelsThe 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
IdentityandIdentityProviderwith proper nesting and the@jsonattribute on theidentityfield 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
idfield 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.urlis 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.buildSelectModelfor 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
subQueryNamevariable 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
nameproperties 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
identityfield is correctly configured with theIdentitytype and@jsonattribute for storing JSON data.
296-321: LGTM! Well-structured type definitions for identity management.The new
IdentityandIdentityProvidertype definitions are well-structured for authentication scenarios. TheIdentitytype with aprovidersarray andIdentityProviderwith requiredidand optionalnamefields 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 typedClientContract<Schema>, while string inputs returnPromise<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, andgetDelegateDescendantModelsare correctly implemented with proper error handling and validation. The recursive implementation ingetDelegateDescendantModelscorrectly 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
buildSelectModelandbuildSelectAllFieldsprovides better control over field selection and properly respects theomitoption. 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
transformPrimitivemethod now correctly identifies and serializes user-defined types as JSON, while maintaining the existing behavior for built-in types. The defensive check fortypeDefsexistence 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
ToKyselyTabletype properly excludes fields whereoriginModelis 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
DataModelFieldandDataModelFieldTypehave been properly replaced with the unifiedDataFieldandDataFieldTypetypes 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
@@@onceattribute 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/@metaattributes provide flexible metadata attachment capabilities, while@@@deprecatedenables 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
CommonFieldstype 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
DataModelFieldandTypeDefFieldintoDataFieldfor bothReferenceTargetandMemberAccessTargettypes simplifies the grammar and aligns with the broader refactoring effort.Also applies to: 98-98
183-198: LGTM! Well-structured field definitions.The unified
DataFieldandDataFieldTyperules provide a clean abstraction for fields across both data models and type definitions. The addition of mixin support toTypeDefis consistent with the overall design.packages/language/src/validators/attribute-application-validator.ts (5)
55-73: LGTM! Good addition of validation context.The optional
contextDataModelparameter 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
@@@onceconstraint 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
@@uniqueand@@idattributes- Prevention of using inherited delegate fields in unique constraints
378-434: LGTM! Thorough field type validation.The
isValidAttributeTargetfunction 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
getAllFieldsto 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
@relationfor 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
fieldsorreferences, which aligns with standard ORM behavior.packages/language/src/utils.ts (3)
532-555: LGTM! Robust recursive field collection.The
getAllFieldsimplementation correctly:
- Prevents infinite recursion with cycle detection
- Maintains proper field precedence (mixins → base → own)
- Safely handles unresolved references with invariants
- Respects the
@ignoreattribute
557-579: LGTM! Consistent attribute collection.The
getAllAttributesimplementation properly mirrors thegetAllFieldspattern, maintaining consistency in the codebase while correctly handling inheritance and mixins.
3-3: Abstract file system operations for browser compatibilityThe import of Node.js
fsin packages/language/src/utils.ts (line 3) and its use inresolveImport(lines 401–402) may break if this code is ever run in a browser environment. If browser support is required, consider:
- Replacing direct
fscalls with a pluggable file‐system interface (e.g., Langium’sFSabstraction)- 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
buildSelectModelmethod 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
originModelproperly 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:
IsDelegateModelcheck routes to appropriate result typeDelegateUnionResultcreates 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
MapModelFieldTypeandMapTypeDefFieldTypeprovides better type specificity compared to generic field accessors. Key improvements:
MapFieldDefTypenow supports enums, type definitions (TypeDefResult), and base types- Type definition support via
GetTypeDefs<Schema>andTypeDefResult<Schema, T['type']>- Maintains proper optional/array wrapping with
WrapTypeThis refactoring significantly improves type safety and enables custom type definition support.
190-200: Well-designed TypeDefResult for custom type definitions.The
TypeDefResulttype effectively handles custom type definitions with:
- Proper field mapping via
MapTypeDefFieldType- Conditional optionality using
TypeDefFieldIsOptional- Clean use of
Optionalutility 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:
FieldIsDelegateDiscriminatorcheck 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, andconnectOrCreateoperations 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
connectoperations remain available for referencing existing concrete instancesThis 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
GetModelFieldsandGetModelFieldTypemaintains 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
buildSelectModelandbuildSelectAllFieldsproperly 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
buildIdFieldRefsand helper methods likeisNumericIncrementalUpdateandisIdFilterimprove code clarity and support the polymorphic model operations.Also applies to: 1201-1218
There was a problem hiding this 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” subsectionThis 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
📒 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)
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests
Chores
Refactor