Skip to content

Conversation

@ymc9
Copy link
Member

@ymc9 ymc9 commented Aug 31, 2025

Summary by CodeRabbit

  • New Features

    • Support naming composite unique/ID keys via a name argument; consistent key generation for composite constraints.
  • Bug Fixes

    • Validation now prevents relation fields inside type definitions, with a clear error message.
  • Tests

    • Expanded coverage for policy behavior with composite-unique constraints and relation connects.
    • Updated extension identifiers in client extension tests.
  • Chores

    • Updated TODOs: added CLI REPL item; removed strict undefined checks.

Copilot AI review requested due to automatic review settings August 31, 2025 14:49
@coderabbitai
Copy link

coderabbitai bot commented Aug 31, 2025

Walkthrough

Adds a relation-field guard to type validation, updates SDK composite-unique key generation to honor named constraints, adjusts test plugin IDs, and introduces new runtime tests for mixins and multi-field unique constraints. Also updates TODOs.

Changes

Cohort / File(s) Summary of Changes
Docs/TODO
TODO.md
Added TODO: “CLI repl” under V3 Alpha; removed “Strict undefined checks” from Misc.
Language: typedef validation
packages/language/src/validators/typedef-validator.ts
Added isDataModel import and a guard rejecting relation types in type fields with error “Type field cannot be a relation”.
Language: tests
packages/language/test/mixin.test.ts
Added test asserting relation fields in type definitions are disallowed.
Runtime: policy tests
packages/runtime/test/policy/client-extensions.test.ts, packages/runtime/test/policy/mixin.test.ts, packages/runtime/test/policy/multi-field-unique.test.ts
Updated plugin IDs in client-extensions tests; added mixin connect tests under policy; added comprehensive tests for composite unique constraints (unnamed, named, and nested).
SDK: TS schema generator
packages/sdk/src/ts-schema-generator.ts
Composite unique key naming now uses helper getCompoundUniqueKey to support explicit name argument; de-duplication and object keys updated accordingly.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • feat: generate input types #94 — Also modifies packages/sdk/src/ts-schema-generator.ts around type/input generation; likely adjacent to composite-unique handling.

Poem

In burrows of code where schemas sleep,
I thump my paws and take a leap—
No sneaky relations in types today,
Unique keys named, in tidy array.
Policies guard, connections align,
Tests hop green—oh what a sign!
Carrots for CI, everything’s fine. 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/misc-4

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

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

Status, Documentation and Community

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

@claude
Copy link

claude bot commented Aug 31, 2025

Claude finished @ymc9's task —— View job


Pull Request Review

Reviewing PR: fix: stricter type def validation and compound unique field fix

Todo List

  • Read and analyze all changed files (7 files)
  • Understand the context of stricter type def validation changes
  • Understand the compound unique field fix changes
  • Evaluate code quality and best practices
  • Check for potential bugs or issues
  • Assess performance considerations
  • Review security concerns
  • Evaluate test coverage
  • Provide comprehensive feedback

Review Feedback

This PR implements two main fixes: stricter type definition validation and compound unique field handling improvements. Overall, the changes are well-structured and properly tested.

Code Quality & Best Practices

Strengths:

  • Clean separation of concerns with dedicated validator class
  • Comprehensive test coverage for both fixes
  • Follows existing codebase patterns and conventions
  • Good use of TypeScript factory methods for AST generation

Minor suggestions:

  • Consider extracting the compound key generation logic in ts-schema-generator.ts:829-836 to a separate method for better readability

Potential Issues ⚠️

Type Definition Validation (typedef-validator.ts:24-31):

  • The validation correctly prevents relation fields in type definitions
  • Logic is sound: isDataModel(field.type.reference?.ref) properly identifies model references
  • Error message is clear and helpful

Compound Unique Key Fix (ts-schema-generator.ts:829-836):

  • The fallback logic fieldNames.join('_') is appropriate
  • Properly handles both named and unnamed unique constraints
  • Consistent with Prisma's naming conventions

Performance Considerations

  • No performance concerns identified
  • New validation logic has O(n) complexity which is acceptable
  • AST generation changes are minimal and efficient
  • Test additions don't introduce performance bottlenecks

Security Concerns

No security issues identified. The changes are purely internal validation and schema generation improvements.

Test Coverage

Excellent test coverage:

Type Definition Tests (mixin.test.ts:110-124):

  • ✅ Tests relation field validation in type definitions
  • ✅ Clear error message validation
  • ✅ Covers the exact validation scenario

Compound Unique Tests (multi-field-unique.test.ts):

  • ✅ Comprehensive testing of unnamed constraints (a_b format)
  • ✅ Named constraint testing (myconstraint format)
  • ✅ Nested CRUD operations with compound keys
  • ✅ Policy integration testing
  • ✅ ConnectOrCreate scenarios
  • ✅ Update/delete operations

Additional test improvements in existing files:

  • Updated client extension tests maintain compatibility
  • New mixin policy tests cover inheritance scenarios

Architecture Alignment

The changes align well with ZenStack's architecture:

  • Language validation follows existing patterns
  • Schema generation maintains consistency with current approach
  • Runtime behavior properly integrates with policy system

Specific File Analysis

  1. typedef-validator.ts - Solid implementation of relation field validation
  2. ts-schema-generator.ts - Clean fix for compound unique key naming
  3. Test files - Comprehensive coverage of edge cases and integration scenarios
  4. TODO.md - Minor task completion update

Recommendations

  1. Consider edge case: What happens with deeply nested type mixins that might indirectly introduce model references? Current validation might not catch this.

  2. Documentation: Consider adding JSDoc comments to the new validation method explaining why relation fields aren't allowed in type definitions.

  3. Error handling: The compound unique key logic is robust, but consider logging when fallback naming is used for debugging purposes.

Overall Assessment

Score: 9/10 - Well-implemented fixes with excellent test coverage. The changes are focused, solve real problems, and maintain code quality standards. Minor suggestions for improvement but no blocking issues.


Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR improves type definition validation and fixes compound unique field handling. The main changes enhance schema generation by supporting named compound unique constraints and add stricter validation for type definitions.

  • Support for named compound unique constraints using the 'name' parameter
  • Prevention of relation fields in type definitions
  • Updated test plugin IDs to remove vendor prefixes

Reviewed Changes

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

Show a summary per file
File Description
packages/sdk/src/ts-schema-generator.ts Adds support for named compound unique constraints through new getCompoundUniqueKey method
packages/language/src/validators/typedef-validator.ts Adds validation to prevent relation fields in type definitions
packages/language/test/mixin.test.ts Adds test case for the new type definition validation
packages/runtime/test/policy/multi-field-unique.test.ts New comprehensive test file for multi-field unique constraints
packages/runtime/test/policy/mixin.test.ts New test file for abstract model functionality
packages/runtime/test/policy/client-extensions.test.ts Updates plugin IDs to remove vendor prefixes
TODO.md Minor documentation updates

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/sdk/src/ts-schema-generator.ts (1)

775-777: Deduplicate multi-field constraints by canonical field-set key
Current logic uses the display key from getCompoundUniqueKey for deduplication, which can still emit duplicates when the same fields appear in both @@id and @@unique or when multiple constraints share a custom name. Change to use a sorted join of the field names as the dedup key, preserving the display key only for the emitted property name.

-        // it's possible to have the same set of fields in both `@@id` and `@@unique`
-        // so we need to deduplicate them
-        const seenKeys = new Set<string>();
+        // it's possible to have the same set of fields in both `@@id` and `@@unique`
+        // so we need to deduplicate them by field-set, not by display key
+        const seenKeys = new Set<string>(); // stores sorted field-set key

@@
-                    // multi-field unique
-                    const key = this.getCompoundUniqueKey(attr, fieldNames);
-                    if (seenKeys.has(key)) {
-                        continue;
-                    }
-                    seenKeys.add(key);
-                    properties.push(
-                        ts.factory.createPropertyAssignment(
-                            key,
+                    // multi-field unique
+                    const displayKey = this.getCompoundUniqueKey(attr, fieldNames);
+                    const dedupKey = [...fieldNames].sort().join('_');
+                    if (seenKeys.has(dedupKey)) continue;
+                    seenKeys.add(dedupKey);
+                    properties.push(
+                        ts.factory.createPropertyAssignment(
+                            displayKey,

Add a test covering a model with both @@id([a,b]) and @@unique([a,b], name: "named") and assert only one schema entry is generated for that field-set, while lookup uses the named key.

🧹 Nitpick comments (6)
TODO.md (1)

10-10: Fix list indentation to satisfy markdownlint (MD007).

The new bullet uses 4 spaces; the linter expects 2. Either:

  • Re-indent nested list items to 2 spaces across the file, or
  • Update markdownlint config to allow 4-space indents.

Minimal code change (convert the CLI subsection to 2-space indents):

-    - [x] generate
-    - [x] migrate
-    - [x] info
-    - [x] init
-    - [x] validate
-    - [ ] format
-    - [ ] repl
-    - [x] plugin mechanism
-    - [x] built-in plugins
+  - [x] generate
+  - [x] migrate
+  - [x] info
+  - [x] init
+  - [x] validate
+  - [ ] format
+  - [ ] repl
+  - [x] plugin mechanism
+  - [x] built-in plugins
packages/sdk/src/ts-schema-generator.ts (1)

829-836: Helper is fine; tighten validation (optional).

getCompoundUniqueKey works. If desired, guard against non-string literals to fail fast:

-        if (nameArg && isLiteralExpr(nameArg.value)) {
-            return nameArg.value.value as string;
+        if (nameArg) {
+            invariant(isLiteralExpr(nameArg.value) && typeof nameArg.value.value === 'string', 'name must be a string literal');
+            return nameArg.value.value as string;
packages/runtime/test/policy/multi-field-unique.test.ts (2)

7-15: Remove unused cwd save/restore (optional).

beforeAll/afterEach manage process.chdir but no test changes cwd. Consider removing to reduce noise.

-    let origDir: string;
-
-    beforeAll(async () => {
-        origDir = path.resolve('.');
-    });
-
-    afterEach(() => {
-        process.chdir(origDir);
-    });

96-104: Unique violation assertion is adequate.

Asserting QueryError on duplicate composite key is correct. If you later surface specific codes, consider matching them for stronger guarantees.

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

110-123: Add coverage for array/optional relation forms.
Types like User[] and User? should also be rejected; add tests to prevent regressions.

Apply:

@@
     it('does not allow relation fields in type', async () => {
@@
     });
+
+    it('does not allow relation array fields in type', async () => {
+        await loadSchemaWithError(
+            `
+        model User {
+            id Int @id @default(autoincrement())
+        }
+
+        type T {
+            us User[]
+        }
+        `,
+            'Type field cannot be a relation',
+        );
+    });
+
+    it('does not allow optional relation fields in type', async () => {
+        await loadSchemaWithError(
+            `
+        model User {
+            id Int @id @default(autoincrement())
+        }
+
+        type T {
+            u User?
+        }
+        `,
+            'Type field cannot be a relation',
+        );
+    });
packages/language/src/validators/typedef-validator.ts (1)

25-29: Include field name in the error message for clarity.
Improves UX when multiple fields fail in one type.

Apply:

-        if (isDataModel(field.type.reference?.ref)) {
-            accept('error', 'Type field cannot be a relation', {
-                node: field.type,
-            });
-        }
+        if (isDataModel(field.type.reference?.ref)) {
+            accept('error', `Type field "${field.name}" cannot be a relation`, {
+                node: field.type,
+            });
+        }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1d1f2c9 and a1b44f3.

📒 Files selected for processing (7)
  • TODO.md (1 hunks)
  • packages/language/src/validators/typedef-validator.ts (2 hunks)
  • packages/language/test/mixin.test.ts (1 hunks)
  • packages/runtime/test/policy/client-extensions.test.ts (5 hunks)
  • packages/runtime/test/policy/mixin.test.ts (1 hunks)
  • packages/runtime/test/policy/multi-field-unique.test.ts (1 hunks)
  • packages/sdk/src/ts-schema-generator.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
{packages,samples,tests}/**

📄 CodeRabbit inference engine (CLAUDE.md)

Packages are located in packages/, samples/, and tests/

Files:

  • packages/language/test/mixin.test.ts
  • packages/runtime/test/policy/mixin.test.ts
  • packages/sdk/src/ts-schema-generator.ts
  • packages/runtime/test/policy/client-extensions.test.ts
  • packages/language/src/validators/typedef-validator.ts
  • packages/runtime/test/policy/multi-field-unique.test.ts
🧬 Code graph analysis (5)
packages/language/test/mixin.test.ts (1)
packages/language/test/utils.ts (1)
  • loadSchemaWithError (18-30)
packages/runtime/test/policy/mixin.test.ts (1)
packages/runtime/test/policy/utils.ts (1)
  • createPolicyTestClient (14-25)
packages/sdk/src/ts-schema-generator.ts (1)
packages/language/src/generated/ast.ts (3)
  • DataModelAttribute (395-400)
  • DataModelAttribute (402-402)
  • isLiteralExpr (133-135)
packages/language/src/validators/typedef-validator.ts (1)
packages/language/src/generated/ast.ts (1)
  • isDataModel (391-393)
packages/runtime/test/policy/multi-field-unique.test.ts (2)
packages/runtime/test/policy/utils.ts (1)
  • createPolicyTestClient (14-25)
packages/runtime/src/client/errors.ts (1)
  • QueryError (13-17)
🪛 markdownlint-cli2 (0.17.2)
TODO.md

10-10: 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). (1)
  • GitHub Check: build-test (20.x)
🔇 Additional comments (7)
packages/runtime/test/policy/client-extensions.test.ts (2)

25-31: Plugin id rename looks good.

Consistent change to 'queryOverride' across tests; no functional issues spotted.

Also applies to: 56-62, 87-93, 118-124


147-155: Plugin id rename looks good.

Renaming to 'resultMutation' is consistent with usage.

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

1-92: Solid coverage for policy-driven connect with mixins.

Scenarios and expectations are clear; no issues spotted.

packages/runtime/test/policy/multi-field-unique.test.ts (1)

45-71: Named composite unique test aligns with generator changes.

Good use of the named key (myconstraint) throughout CRUD paths.

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

110-123: Good negative test; message assertion fits utils’ matcher.
Covers the new validator behavior and aligns with loadSchemaWithError’s substring check.

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

2-2: Import change is correct and type-only modifiers are preserved.
Tree-shake friendly; no runtime cost for types.


25-29: Correct relational-field guard for TypeDef.
Prevents model references in types and attaches error to the type node.

@ymc9 ymc9 merged commit 774f3c4 into dev Aug 31, 2025
6 of 7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants