Skip to content
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

merge dev to main (v2.8.1) #1838

Merged
merged 2 commits into from
Nov 7, 2024
Merged

merge dev to main (v2.8.1) #1838

merged 2 commits into from
Nov 7, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Nov 7, 2024

No description provided.

Copy link
Contributor

coderabbitai bot commented Nov 7, 2024

📝 Walkthrough

Walkthrough

This pull request introduces a series of changes across multiple files, primarily focusing on version updates, grammar modifications, validation logic enhancements, and the addition of new test cases. The version number for the JetBrains plugin is incremented from "2.8.0" to "2.8.1". The grammar for the ZModel language is refined to allow more flexible type definitions. Validation logic in the DataModelValidator is adjusted to remove restrictions on data source providers, and new functions are added to improve enum handling in schema generation. Additionally, new integration tests are added to validate these changes.

Changes

File Path Change Summary
packages/ide/jetbrains/build.gradle.kts Version updated from "2.8.0" to "2.8.1".
packages/language/src/zmodel.langium Modified TypeDef rule to allow optional TypeDefField. Added type alias TypeDefFieldTypes. Updated TypeDefField to reference TypeDefFieldTypes.
packages/schema/src/language-server/validator/datamodel-validator.ts Removed check for 'postgresql' in validateField method, allowing more flexibility in data source providers.
packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts Added makeEnumTypeReference function for enum handling. Updated zmodelTypeToTsType for better type reference handling.
packages/schema/src/plugins/prisma/schema-generator.ts Added ensureSupportingTypeDefFields method for validation based on data source provider. Introduced PROVIDERS_SUPPORTING_TYPEDEF_FIELDS constant.
packages/schema/src/plugins/zod/transformer.ts Updated generateEnumSchemas method to handle additional enums not referenced by data models. Imported Enum type.
tests/integration/tests/enhancements/json/crud.test.ts Added tests for enums used and unused by data models.
tests/integration/tests/enhancements/json/typing.test.ts Added tests for handling enums in models and string values.
tests/integration/tests/enhancements/json/validation.test.ts Updated to use loadSchema instead of loadModelWithError for error handling in tests.

Possibly related PRs


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

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

Copy link
Contributor

@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: 2

🧹 Outside diff range and nitpick comments (8)
tests/integration/tests/enhancements/json/validation.test.ts (1)

Line range hint 6-19: LGTM! Improved error handling with loadSchema.

The switch from loadModelWithError to loadSchema provides more specific error handling for provider compatibility checks. The error message clearly indicates that SQLite doesn't support @json fields.

Consider documenting these provider limitations in the main documentation to help developers choose the appropriate database provider based on their JSON field requirements.

packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts (2)

39-43: Consider adding type validation for non-enum references

The enum handling logic is well-implemented. However, for non-enum references, we might want to validate that the referenced type is actually a TypeDef to prevent potential runtime issues.

Consider adding a type check:

 if (isEnum(type.reference.ref)) {
     result = makeEnumTypeReference(type.reference.ref);
 } else {
+    if (!type.reference.ref.$type === 'TypeDef') {
+        throw new PluginError(name, `Invalid type reference: expected TypeDef, got ${type.reference.ref.$type}`);
+    }
     result = type.reference.ref.name;
 }

69-81: Consider adding error handling and performance optimization

The function implementation is clean and well-documented. However, there are a few potential improvements to consider:

  1. Error handling for edge cases (e.g., empty enums)
  2. Performance optimization for large models by caching the model traversal results

Consider this enhanced implementation:

+const enumUsageCache = new WeakMap<Enum, boolean>();
+
 function makeEnumTypeReference(enumDecl: Enum) {
+    if (enumDecl.fields.length === 0) {
+        throw new PluginError(name, `Empty enum ${enumDecl.name} is not supported`);
+    }
+
+    // Check cache first
+    const cachedResult = enumUsageCache.get(enumDecl);
+    if (cachedResult !== undefined) {
+        return cachedResult ? enumDecl.name : enumDecl.fields.map((field) => `'${field.name}'`).join(' | ');
+    }
+
     const zmodel = enumDecl.$container;
     const models = getDataModels(zmodel);
+    const isUsedInModels = models.some((model) => 
+        model.fields.some((field) => field.type.reference?.ref === enumDecl)
+    );
 
-    if (models.some((model) => model.fields.some((field) => field.type.reference?.ref === enumDecl))) {
+    // Cache the result
+    enumUsageCache.set(enumDecl, isUsedInModels);
+
+    if (isUsedInModels) {
         // if the enum is referenced by any data model, Prisma already generates its type,
         // we just need to reference it
         return enumDecl.name;
tests/integration/tests/enhancements/json/typing.test.ts (2)

182-234: Enhance test coverage for enum handling.

While the test successfully validates basic enum functionality, consider expanding it to:

  1. Test both enum values (USER and ADMIN)
  2. Add negative test cases for invalid enum values
  3. Include tests for the Foo model since it's defined but not used

Here's a suggested addition to the test:

// Test both enum values
await db.user.create({ data: { profile: { role: Role.USER } } });
const userWithUserRole = await db.user.findFirstOrThrow();
console.log(userWithUserRole.profile.role === Role.USER);

// Test Foo model
await db.foo.create({ data: { role: Role.ADMIN } });
const foo = await db.foo.findFirstOrThrow();
console.log(foo.role === Role.ADMIN);

// Negative test
await expect(
    db.user.create({ data: { profile: { role: 'INVALID_ROLE' } } })
).rejects.toThrow();

236-237: Rename test case for clarity.

The test name "works with enums unused in models" is misleading since the enum is used in the Profile type. Consider renaming to "works with enum string literals" or "works with string-based enum values" to better reflect the test's purpose.

tests/integration/tests/enhancements/json/crud.test.ts (1)

194-233: Enhance test coverage for enum validation.

While the test covers basic enum validation, consider adding the following test cases for more comprehensive coverage:

  1. Test the 'USER' enum value
  2. Test updating enum values
  3. Test the interaction between JSON field (profile.role) and regular field (Foo.role)

Here's a suggested addition:

// Test USER enum value
await expect(db.user.create({ data: { profile: { role: 'USER' } } })).resolves.toMatchObject({
    profile: { role: 'USER' },
});

// Test updating enum values
const user = await db.user.create({ data: { profile: { role: 'USER' } } });
await expect(db.user.update({
    where: { id: user.id },
    data: { profile: { role: 'ADMIN' } }
})).resolves.toMatchObject({
    profile: { role: 'ADMIN' },
});

// Test interaction with regular enum field
await expect(db.foo.create({
    data: { role: 'ADMIN' }
})).resolves.toMatchObject({
    role: 'ADMIN'
});
packages/schema/src/plugins/prisma/schema-generator.ts (1)

852-857: Method should be marked as private.

The method is only used internally within the class and should be marked as private for better encapsulation.

-    private ensureSupportingTypeDefFields(zmodel: Model) {
+    private ensureSupportingTypeDefFields(zmodel: Model) {
         const dsProvider = getDataSourceProvider(zmodel);
         if (dsProvider && !PROVIDERS_SUPPORTING_TYPEDEF_FIELDS.includes(dsProvider)) {
-            throw new PluginError(name, `Datasource provider "${dsProvider}" does not support "@json" fields`);
+            throw new PluginError(name, `Datasource provider "${dsProvider}" does not support type definition fields`);
         }
     }
packages/schema/src/plugins/zod/transformer.ts (1)

Line range hint 56-86: Use a Set for 'generated' to improve lookup performance and prevent duplicates

As the number of enums increases, using an array with includes for checking existing enum names in generated can become inefficient. Switching to a Set improves performance for lookups and ensures that duplicates are not possible.

Apply the following changes:

-    const generated: string[] = [];
+    const generated: Set<string> = new Set();

...

-        generated.push(enumType.name);
+        generated.add(enumType.name);

...

-        generated.push(enumDecl.name);
+        generated.add(enumDecl.name);

...

-    const extraEnums = this.zmodel.declarations.filter((d): d is Enum => isEnum(d) && !generated.includes(d.name));
+    const extraEnums = this.zmodel.declarations.filter((d): d is Enum => isEnum(d) && !generated.has(d.name));

...

-                generated.map((name) => `export * from './${upperCaseFirst(name)}.schema';`).join('\n'),
+                Array.from(generated).map((name) => `export * from './${upperCaseFirst(name)}.schema';`).join('\n'),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 59fe945 and 1bd1b8f.

⛔ Files ignored due to path filters (15)
  • package.json is excluded by !**/*.json
  • packages/ide/jetbrains/package.json is excluded by !**/*.json
  • packages/language/package.json is excluded by !**/*.json
  • packages/language/src/generated/ast.ts is excluded by !**/generated/**, !**/generated/**
  • packages/language/src/generated/grammar.ts is excluded by !**/generated/**, !**/generated/**
  • packages/misc/redwood/package.json is excluded by !**/*.json
  • packages/plugins/openapi/package.json is excluded by !**/*.json
  • packages/plugins/swr/package.json is excluded by !**/*.json
  • packages/plugins/tanstack-query/package.json is excluded by !**/*.json
  • packages/plugins/trpc/package.json is excluded by !**/*.json
  • packages/runtime/package.json is excluded by !**/*.json
  • packages/schema/package.json is excluded by !**/*.json
  • packages/sdk/package.json is excluded by !**/*.json
  • packages/server/package.json is excluded by !**/*.json
  • packages/testtools/package.json is excluded by !**/*.json
📒 Files selected for processing (9)
  • packages/ide/jetbrains/build.gradle.kts (1 hunks)
  • packages/language/src/zmodel.langium (1 hunks)
  • packages/schema/src/language-server/validator/datamodel-validator.ts (0 hunks)
  • packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts (3 hunks)
  • packages/schema/src/plugins/prisma/schema-generator.ts (4 hunks)
  • packages/schema/src/plugins/zod/transformer.ts (3 hunks)
  • tests/integration/tests/enhancements/json/crud.test.ts (1 hunks)
  • tests/integration/tests/enhancements/json/typing.test.ts (1 hunks)
  • tests/integration/tests/enhancements/json/validation.test.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • packages/schema/src/language-server/validator/datamodel-validator.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/ide/jetbrains/build.gradle.kts
🔇 Additional comments (10)
tests/integration/tests/enhancements/json/validation.test.ts (1)

1-1: LGTM! Clean import statement.

The import statement correctly includes both required functions from the test tools package.

packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts (1)

1-1: LGTM: Import addition is appropriate

The addition of getDataModels import is well-placed and necessary for the new enum reference functionality.

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

189-190: LGTM! Well-structured type alias addition.

The new TypeDefFieldTypes type alias effectively groups related type references, improving code organization.


192-192: LGTM! Improved comment handling.

The explicit whitespace handling for comments improves grammar consistency.


196-196: LGTM! Enhanced type reference flexibility.

The update to use TypeDefFieldTypes allows fields to reference both TypeDef and Enum types, which aligns with the goal of improving type definition flexibility.

Let's verify existing type references are compatible:

#!/bin/bash
# Search for existing type references to ensure they're compatible
# with the new TypeDefFieldTypes system
rg -A 2 'type\s+\w+\s*\{.*\btype\b.*:.*\b(enum|type)\b'

186-186: Verify the impact of allowing empty type definitions.

The cardinality change from + to * means type definitions can now be empty. While this adds flexibility, it's a potentially breaking change that might affect existing code that assumes types always have fields.

Consider:

  1. Documenting this change in the changelog
  2. Adding validation rules if empty types should be restricted in certain contexts
✅ Verification successful

Based on the search results, I can now make a definitive assessment. The grammar changes and AST definitions show that:

  1. The TypeDef model is a core part of the language structure, used in multiple places including abstract declarations and type references
  2. There are no existing empty type definitions in the codebase
  3. The change from '+' to '*' is intentional to support optional fields in type definitions

Empty type definitions are now supported by design

The cardinality change from + to * for TypeDef fields is a deliberate enhancement to support empty type definitions, not a breaking change. This aligns with common type system practices where empty types can serve valid use cases like:

  • Marker types
  • Future extensibility
  • Placeholder types in API contracts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing empty type definitions that might now be valid
# and type validation logic that might need updates
rg -l 'type\s+\w+\s*\{\s*\}' 
ast-grep --pattern 'type $name {}'

Length of output: 156


Script:

#!/bin/bash
# Let's try a more comprehensive search strategy:

# 1. Look for type definitions in test files that might demonstrate empty types
rg -A 5 "type\s+\w+\s*\{" test/ || true

# 2. Search for validation rules or constraints related to type definitions
rg -A 3 "validateType|TypeDef" packages/language/src/ || true

# 3. Look for any documentation or examples mentioning type definitions
fd "README|CHANGELOG" --exec cat {} || true

# 4. Check for existing type definition usages
ast-grep --pattern 'type $name {
  $$$
}'

Length of output: 56914

tests/integration/tests/enhancements/json/typing.test.ts (1)

213-217: LGTM: Proper import structure.

The import statements are well-organized and include all necessary dependencies for type safety and database operations.

Also applies to: 262-264

packages/schema/src/plugins/prisma/schema-generator.ts (2)

85-85: LGTM: Provider support constant is well-defined.

The constant follows the existing naming convention and clearly defines PostgreSQL as the only supported provider for typedef fields.


799-799: LGTM: Validation is called at the right place.

The validation is appropriately placed before processing typedef fields in the generateModelField method.

packages/schema/src/plugins/zod/transformer.ts (1)

3-3: Necessary import of 'Enum' type for enum processing

The addition of the Enum type import is appropriate for handling enums not referenced by data models.

@ymc9 ymc9 merged commit d2554f2 into main Nov 7, 2024
16 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.

1 participant