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.12.0) #2013

Merged
merged 14 commits into from
Feb 25, 2025
Merged

merge dev to main (v2.12.0) #2013

merged 14 commits into from
Feb 25, 2025

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Feb 24, 2025

No description provided.

Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

📝 Walkthrough

Walkthrough

This pull request introduces several enhancements and updates. It adds a new changelog entry about regex pattern validation in ZModel and bumps the version to 2.12.0. The modifications include additional type exports, updates to method signatures to propagate a new context parameter in nested writes, improvements in handling compound keys for deletion, refined policy checks for foreign key relationships, and enhanced validation for regex attributes. Several new tests have also been added to validate these changes across various modules and functionalities, and utility functions related to relation backlinks have been refactored.

Changes

File(s) Change Summary
packages/ide/jetbrains/CHANGELOG.md
packages/ide/jetbrains/build.gradle.kts
Added new changelog entry for "Validating regex patterns in ZModel" and updated project version from 2.11.6 to 2.12.0.
packages/runtime/res/enhance.d.ts
packages/runtime/src/enhance.d.ts
Expanded the export declarations to include type Enhanced (and PrismaClient in one file) to support enhanced typings.
packages/runtime/src/enhancements/node/default-auth.ts Updated method signatures in DefaultAuthHandler and nested write visitor functions to include a new context parameter for enhanced nested payload processing.
packages/runtime/src/enhancements/node/delegate.ts Enhanced deletion logic for models with compound ID fields by composing a proper compound key filter.
packages/runtime/src/enhancements/node/policy/handler.ts
packages/runtime/src/enhancements/node/policy/policy-utils.ts
Modified methods to map foreign key payloads for update/delete operations and updated parameter usage from general args to specific field arrays.
packages/runtime/src/enhancements/node/query-utils.ts Added a new method getFieldsWithDefinedValues to extract defined keys from an object.
packages/schema/src/language-server/validator/attribute-application-validator.ts Added a new private method _checkRegex for validating regex patterns within attribute validations.
packages/schema/src/plugins/enhancer/enhance/index.ts
packages/schema/src/plugins/prisma/schema-generator.ts
packages/schema/src/plugins/zod/generator.ts
packages/schema/src/plugins/zod/transformer.ts
Introduced enhancements for handling JSON type fields, delegate auxiliary types, and delegate input type mapping; added a new type Enhanced<Client>.
packages/sdk/src/model-meta-generator.ts
packages/sdk/src/utils.ts
Removed redundant backlink and relation name extraction functions and added new implementations in utils.ts.
script/test-scaffold.ts
tests/integration/tests/cli/plugins.test.ts
Updated dependency versions for prisma and @prisma/client from 6.3.x to 6.4.x.
Various test files under tests/integration/, tests/regression/ Added new test cases and suites validating regex functionality, type enhancements, and regression tests for issues 1991, 1992, 1993, 1997, 1998, 2000, and 2007.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant NestedWriteVisitor
  participant DefaultAuthHandler
  participant Database

  Client->>NestedWriteVisitor: Create/Update/Upsert Request with Data & Context
  NestedWriteVisitor->>DefaultAuthHandler: processCreatePayload(model, data, context)
  DefaultAuthHandler-->>NestedWriteVisitor: Processed Payload Returned
  NestedWriteVisitor->>Database: Execute Write Operation with Context
Loading
sequenceDiagram
  participant Client
  participant PolicyProxyHandler
  participant PolicyUtil

  Client->>PolicyProxyHandler: Request (connect, update, delete)
  PolicyProxyHandler->>PolicyUtil: checkPolicyForUnique(model, filter, operation, db, fieldsToUpdate)
  PolicyUtil-->>PolicyProxyHandler: Policy Check Result
  PolicyProxyHandler->>Client: Return Operation Result
Loading

Possibly related PRs

Warning

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

🔧 detekt (1.23.7)
packages/ide/jetbrains/build.gradle.kts

Exception in thread "main" com.beust.jcommander.ParameterException: Provided path 'packages/ide/jetbrains/build.gradle.kts' does not exist!
at io.gitlab.arturbosch.detekt.cli.ExistingPathConverter.convert(ArgumentConverters.kt:16)
at io.gitlab.arturbosch.detekt.cli.ExistingPathConverter.convert(ArgumentConverters.kt:11)
at io.gitlab.arturbosch.detekt.cli.DetektInputPathConverter$DefaultImpls.convert$lambda$1(ArgumentConverters.kt:31)
at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:210)
at kotlin.sequences.SequencesKt___SequencesKt.toList(_Sequences.kt:815)
at io.gitlab.arturbosch.detekt.cli.DetektInputPathConverter$DefaultImpls.convert(ArgumentConverters.kt:32)
at io.gitlab.arturbosch.detekt.cli.MultipleExistingPathConverter.convert(ArgumentConverters.kt:41)
at io.gitlab.arturbosch.detekt.cli.CliArgs.inputPaths_delegate$lambda$0(CliArgs.kt:193)
at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
at io.gitlab.arturbosch.detekt.cli.CliArgs.getInputPaths(CliArgs.kt:192)
at io.gitlab.arturbosch.detekt.cli.SpecKt.createSpec$lambda$15$lambda$1(Spec.kt:18)
at io.github.detekt.tooling.dsl.ProcessingSpecBuilder.project(ProcessingSpecBuilder.kt:37)
at io.gitlab.arturbosch.detekt.cli.SpecKt.createSpec$lambda$15(Spec.kt:16)
at io.github.detekt.tooling.dsl.ProcessingSpecBuilderKt.processingSpec(ProcessingSpecBuilder.kt:15)
at io.github.detekt.tooling.api.spec.ProcessingSpec$Companion.invoke(ProcessingSpec.kt:23)
at io.gitlab.arturbosch.detekt.cli.SpecKt.createSpec(Spec.kt:9)
at io.gitlab.arturbosch.detekt.cli.runners.Runner.(Runner.kt:20)
at io.gitlab.arturbosch.detekt.cli.CliRunner.run(CliRunner.kt:31)
at io.gitlab.arturbosch.detekt.cli.CliRunner.run(CliRunner.kt:14)
at io.gitlab.arturbosch.detekt.cli.Main.main(Main.kt:20)

🔧 markdownlint-cli2 (0.17.2)
packages/ide/jetbrains/CHANGELOG.md

markdownlint-cli2 v0.17.2 (markdownlint v0.37.4)
Finding: packages/ide/jetbrains/CHANGELOG.md
Linting: 0 file(s)
Summary: 0 error(s)
Error: ENOSPC: no space left on device, write
at async write (node:internal/fs/promises:743:8)
at async writeFileHandle (node:internal/fs/promises:500:7)
at async Promise.all (index 0)
at async outputSummary (file:///usr/local/lib/node_modules/markdownlint-cli2/markdownlint-cli2.mjs:867:5)
at async main (file:///usr/local/lib/node_modules/markdownlint-cli2/markdownlint-cli2.mjs:1043:25)
at async file:///usr/local/lib/node_modules/markdownlint-cli2/markdownlint-cli2-bin.mjs:12:22 {
errno: -28,
code: 'ENOSPC',
syscall: 'write'
}

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 comments (1)
packages/ide/jetbrains/CHANGELOG.md (1)

3-8: 🛠️ Refactor suggestion

Remove duplicate content from the Unreleased section.

The entry about regex pattern validation appears in both the Unreleased section and the 2.12.0 section. Since this is part of the 2.12.0 release, it should only appear in the 2.12.0 section.

Apply this diff to remove the duplicate content:

## [Unreleased]

### Added

-   Validating regex patterns in ZModel.
🧹 Nitpick comments (14)
tests/regression/tests/issue-1993.test.ts (1)

3-63: Enhance test coverage for comprehensive validation.

The test suite could be improved with additional test cases:

  1. Negative test cases to verify validation failures
  2. Structure validation of parsed data
  3. Test cases for UserGoogle model
  4. Test cases for invalid relation data

Consider adding these test cases:

it('validates input data structure', async () => {
    const { zodSchemas } = await loadSchema(`...`);
    
    // Test UserLocal validation failure
    expect(
        zodSchemas.input.UserLocalInputSchema.create.safeParse({
            data: {
                email: 'invalid-email',
                password: '',
            },
        })
    ).toMatchObject({ success: false });

    // Test UserGoogle validation
    expect(
        zodSchemas.input.UserGoogleInputSchema.create.safeParse({
            data: {
                googleId: '123',
            },
        })
    ).toMatchObject({ success: true });

    // Test invalid relation data
    expect(
        zodSchemas.input.UserFolderInputSchema.create.safeParse({
            data: {
                path: '/',
                userId: '', // Invalid ID
            },
        })
    ).toMatchObject({ success: false });
});
packages/schema/src/language-server/validator/attribute-application-validator.ts (1)

215-228: Enhance regex pattern validation.

The regex validation could be improved with:

  1. More descriptive error messages
  2. Common pattern validation
  3. Security checks for potential regex DoS vulnerabilities

Consider enhancing the validation:

@check('@regex')
private _checkRegex(attr: AttributeApplication, accept: ValidationAcceptor) {
    const regex = getStringLiteral(attr.args[0]?.value);
    if (regex === undefined) {
-       accept('error', `Expecting a string literal`, { node: attr.args[0] ?? attr });
+       accept('error', `@regex attribute requires a string literal pattern`, { node: attr.args[0] ?? attr });
        return;
    }

+   // Check for common regex anti-patterns
+   if (regex.length > 0 && regex.startsWith('.*')) {
+       accept('warning', 'Pattern starting with .* is inefficient', { node: attr.args[0] });
+   }
+
+   // Check for potential regex DoS
+   if (regex.match(/([a-z])+\1/i)) {
+       accept('warning', 'Pattern might be vulnerable to ReDoS attacks', { node: attr.args[0] });
+   }

    try {
        new RegExp(regex);
    } catch (e) {
-       accept('error', `${e}`, { node: attr.args[0] });
+       accept('error', `Invalid regex pattern: ${e}`, { node: attr.args[0] });
    }
}
packages/schema/src/plugins/prisma/schema-generator.ts (1)

531-563: Improve error handling and constraint naming.

The error handling and constraint naming could be enhanced:

  1. More descriptive error message
  2. More robust constraint name generation with validation

Consider these improvements:

for (const arg of fields.items) {
-   if (!isReferenceExpr(arg)) {
-       throw new PluginError(name, 'Unexpected field reference in @@unique attribute');
-   }
+   if (!isReferenceExpr(arg)) {
+       throw new PluginError(
+           name,
+           `Expected a field reference in @@unique attribute but got ${arg.$type}`
+       );
+   }

    if (arg.target.ref === origForeignKey) {
        fieldNames.push(addedFkField.name);
        args.push(
            new PrismaAttributeArgValue(
                'FieldReference',
                new PrismaFieldReference(addedFkField.name)
            )
        );
    } else {
        fieldNames.push(arg.target.$refText);
        args.push(
            new PrismaAttributeArgValue(
                'FieldReference',
                new PrismaFieldReference(arg.target.$refText)
            )
        );
    }
}

-const constraintName = this.truncate(`${dataModel.name}_${fieldNames.join('_')}_unique`);
+// Ensure constraint name is valid and unique
+const baseConstraintName = `${dataModel.name}_${fieldNames.join('_')}_unique`;
+const constraintName = this.truncate(
+   baseConstraintName.replace(/[^a-zA-Z0-9_]/g, '_')
+);
packages/schema/src/plugins/zod/generator.ts (3)

92-97: Centralize and document delegate type filtering logic.

The filtering logic for delegate auxiliary types could be improved:

  1. Centralize filtering logic in a utility function
  2. Add more descriptive comments explaining the purpose

Consider refactoring the filtering logic:

+/**
+ * Checks if a type should be excluded from schema generation.
+ * @param typeName The name of the type to check
+ * @param excludedModels List of models to exclude
+ * @returns true if the type should be excluded
+ */
+private shouldExcludeType(typeName: string, excludedModels: string[]): boolean {
+    const lowerTypeName = typeName.toLowerCase();
+    return (
+        excludedModels.some(e => lowerTypeName.startsWith(e.toLowerCase())) ||
+        lowerTypeName.includes(DELEGATE_AUX_RELATION_PREFIX)
+    );
+}

const inputObjectTypes = prismaClientDmmf.schema.inputObjectTypes.prisma.filter(
-   (type) =>
-       !excludeModels.some((e) => type.name.toLowerCase().startsWith(e.toLocaleLowerCase())) &&
-       // exclude delegate aux related types
-       !type.name.toLowerCase().includes(DELEGATE_AUX_RELATION_PREFIX)
+   (type) => !this.shouldExcludeType(type.name, excludeModels)
);

99-104: Apply consistent filtering logic to output types.

The same filtering logic should be applied consistently to output types.

Apply the centralized filtering:

const outputObjectTypes = prismaClientDmmf.schema.outputObjectTypes.prisma.filter(
-   (type) =>
-       !excludeModels.some((e) => type.name.toLowerCase().startsWith(e.toLowerCase())) &&
-       // exclude delegate aux related types
-       !type.name.toLowerCase().includes(DELEGATE_AUX_RELATION_PREFIX)
+   (type) => !this.shouldExcludeType(type.name, excludeModels)
);

246-248: Apply consistent filtering logic to fields.

The field filtering logic should follow the same pattern.

Apply the centralized filtering:

-// exclude delegate aux fields
-const fields = inputObjectTypes[i]?.fields?.filter((f) => !f.name.startsWith(DELEGATE_AUX_RELATION_PREFIX));
+/**
+ * Checks if a field should be excluded from schema generation.
+ * @param fieldName The name of the field to check
+ * @returns true if the field should be excluded
+ */
+private shouldExcludeField(fieldName: string): boolean {
+    return fieldName.startsWith(DELEGATE_AUX_RELATION_PREFIX);
+}
+
+const fields = inputObjectTypes[i]?.fields?.filter(
+    (f) => !this.shouldExcludeField(f.name)
+);
tests/regression/tests/issue-1997.test.ts (1)

82-129: Consider adding negative test cases.

While the current test cases validate successful creation scenarios, consider adding negative test cases to verify:

  • Creation attempts with invalid tenant IDs
  • Creation attempts with invalid user IDs
tests/regression/tests/issue-1991.test.ts (1)

4-46: Add explicit assertions for database operations.

Within this test, the code executes db.fooOption.create(...) without directly verifying the outcome of that creation. Although the test might fail if an exception is thrown, adding an explicit assertion (e.g., verifying the returned object or checking for expected side effects) can improve test clarity and coverage.

packages/runtime/src/enhancements/node/delegate.ts (1)

1109-1120: Consider more robust error handling within Promise.all.

Currently, all deletion calls run in parallel via Promise.all(...). If one deletion fails, the transaction will roll back. This is acceptable for an all-or-nothing approach. However, if partial deletions should be tolerable in the future, switching to Promise.allSettled and collecting individual errors might be beneficial. Otherwise, this looks correct for a "fail fast" transactional flow.

tests/regression/tests/issue-2000.test.ts (1)

58-66: Expand coverage of policy and validation checks.

The test successfully verifies that an attempt to activate a user without a name is rejected. Consider testing additional edge cases, such as toggling published or deleted properties, to ensure that all policy constraints remain consistent and validated.

packages/schema/src/plugins/enhancer/enhance/index.ts (1)

787-836: Consider refactoring the fixJsonFieldType method for better maintainability.

The method is quite long and handles multiple responsibilities. Consider breaking it down into smaller, focused methods:

  • Extract the field replacement logic into a separate method
  • Split payload type and input/output type handling into separate methods

Apply this diff to improve maintainability:

 private fixJsonFieldType(typeAlias: TypeAliasDeclaration, source: string) {
     const typeName = typeAlias.getName();

     const getTypedJsonFields = (model: DataModel) => {
         return model.fields.filter((f) => isTypeDef(f.type.reference?.ref));
     };

     const replacePrismaJson = (source: string, field: DataModelField) => {
         return source.replace(
             new RegExp(`(${field.name}\\??\\s*):[^\\n]+`),
             `$1: ${field.type.reference!.$refText}${field.type.array ? '[]' : ''}${
                 field.type.optional ? ' | null' : ''
             }`
         );
     };

+    const fixPayloadType = (source: string) => {
+        const payloadModelMatch = this.modelsWithJsonTypeFields.find((m) => `$${m.name}Payload` === typeName);
+        if (!payloadModelMatch) {
+            return source;
+        }
+
+        const scalars = typeAlias
+            .getDescendantsOfKind(SyntaxKind.PropertySignature)
+            .find((p) => p.getName() === 'scalars');
+        if (!scalars) {
+            return source;
+        }
+
+        const fieldsToFix = getTypedJsonFields(payloadModelMatch);
+        for (const field of fieldsToFix) {
+            source = replacePrismaJson(source, field);
+        }
+        return source;
+    };
+
+    const fixInputOutputType = (source: string) => {
+        for (const pattern of this.modelsWithJsonTypeFieldsInputOutputPattern) {
+            const match = typeName.match(pattern);
+            if (!match) {
+                continue;
+            }
+            const modelName = match[1];
+            const model = this.modelsWithJsonTypeFields.find((m) => m.name === modelName);
+            const fieldsToFix = getTypedJsonFields(model!);
+            for (const field of fieldsToFix) {
+                source = replacePrismaJson(source, field);
+            }
+            break;
+        }
+        return source;
+    };

-    // fix "$[Model]Payload" type
-    const payloadModelMatch = this.modelsWithJsonTypeFields.find((m) => `$${m.name}Payload` === typeName);
-    if (payloadModelMatch) {
-        const scalars = typeAlias
-            .getDescendantsOfKind(SyntaxKind.PropertySignature)
-            .find((p) => p.getName() === 'scalars');
-        if (!scalars) {
-            return source;
-        }
-
-        const fieldsToFix = getTypedJsonFields(payloadModelMatch);
-        for (const field of fieldsToFix) {
-            source = replacePrismaJson(source, field);
-        }
-    }
-
-    // fix input/output types, "[Model]CreateInput", etc.
-    for (const pattern of this.modelsWithJsonTypeFieldsInputOutputPattern) {
-        const match = typeName.match(pattern);
-        if (!match) {
-            continue;
-        }
-        const modelName = match[1];
-        const model = this.modelsWithJsonTypeFields.find((m) => m.name === modelName);
-        const fieldsToFix = getTypedJsonFields(model!);
-        for (const field of fieldsToFix) {
-            source = replacePrismaJson(source, field);
-        }
-        break;
-    }

+    source = fixPayloadType(source);
+    source = fixInputOutputType(source);

     return source;
 }
packages/schema/src/plugins/zod/transformer.ts (1)

306-344: Consider edge cases in mapDelegateInputType
This method’s pattern matching logic might not handle unconventional naming or partial matches. Ensure you have test coverage for possible edge cases like missing or unexpected suffixes to avoid incorrect mappings.

packages/runtime/src/enhancements/node/policy/policy-utils.ts (1)

833-834: Clarify inline documentation
The added doc comment referencing mutation operations is helpful. Consider expanding any rationale or preconditions regarding how this method is utilized within mutations for future maintainers.

packages/runtime/src/enhancements/node/default-auth.ts (1)

114-189: Enhance setDefaultValueForModelData with creation context awareness
The extended logic checks for a parent’s implied foreign key context and prevents overwriting default values in nested structures. Be sure to test complex nesting scenarios (e.g., multiple levels of child creations) to confirm correct default assignment or bypassing.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 584d8af and 82b8d25.

⛔ Files ignored due to path filters (21)
  • .github/workflows/security-scorecard.yml is excluded by !**/*.yml
  • package.json is excluded by !**/*.json
  • packages/ide/jetbrains/package.json is excluded by !**/*.json
  • packages/language/package.json is excluded by !**/*.json
  • 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/plugins/trpc/tests/projects/nuxt-trpc-v10/package.json is excluded by !**/*.json
  • packages/plugins/trpc/tests/projects/nuxt-trpc-v11/package.json is excluded by !**/*.json
  • packages/plugins/trpc/tests/projects/t3-trpc-v11/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
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/*.yaml
  • tests/integration/test-run/package.json is excluded by !**/*.json
  • tests/integration/tests/frameworks/nextjs/test-project/package.json is excluded by !**/*.json
  • tests/integration/tests/frameworks/trpc/test-project/package.json is excluded by !**/*.json
📒 Files selected for processing (27)
  • packages/ide/jetbrains/CHANGELOG.md (1 hunks)
  • packages/ide/jetbrains/build.gradle.kts (1 hunks)
  • packages/runtime/res/enhance.d.ts (1 hunks)
  • packages/runtime/src/enhance.d.ts (1 hunks)
  • packages/runtime/src/enhancements/node/default-auth.ts (4 hunks)
  • packages/runtime/src/enhancements/node/delegate.ts (1 hunks)
  • packages/runtime/src/enhancements/node/policy/handler.ts (8 hunks)
  • packages/runtime/src/enhancements/node/policy/policy-utils.ts (5 hunks)
  • packages/runtime/src/enhancements/node/query-utils.ts (1 hunks)
  • packages/schema/src/language-server/validator/attribute-application-validator.ts (1 hunks)
  • packages/schema/src/plugins/enhancer/enhance/index.ts (5 hunks)
  • packages/schema/src/plugins/prisma/schema-generator.ts (2 hunks)
  • packages/schema/src/plugins/zod/generator.ts (3 hunks)
  • packages/schema/src/plugins/zod/transformer.ts (4 hunks)
  • packages/schema/tests/schema/validation/attribute-validation.test.ts (1 hunks)
  • packages/sdk/src/model-meta-generator.ts (2 hunks)
  • packages/sdk/src/utils.ts (1 hunks)
  • script/test-scaffold.ts (1 hunks)
  • tests/integration/tests/cli/plugins.test.ts (2 hunks)
  • tests/integration/tests/enhancements/typing/enhancement-typing.test.ts (1 hunks)
  • tests/regression/tests/issue-1991.test.ts (1 hunks)
  • tests/regression/tests/issue-1992.test.ts (1 hunks)
  • tests/regression/tests/issue-1993.test.ts (1 hunks)
  • tests/regression/tests/issue-1997.test.ts (1 hunks)
  • tests/regression/tests/issue-1998.test.ts (1 hunks)
  • tests/regression/tests/issue-2000.test.ts (1 hunks)
  • tests/regression/tests/issue-2007.test.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/ide/jetbrains/build.gradle.kts
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: build-test (20.x)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (31)
packages/runtime/res/enhance.d.ts (1)

1-1: LGTM!

The export statement correctly includes the new Enhanced type, maintaining consistency with the type system enhancements mentioned in the PR summary.

script/test-scaffold.ts (1)

22-22:

❓ Verification inconclusive

Verify Prisma version update compatibility.

The update from Prisma 6.3.x to 6.4.x might introduce breaking changes. Please ensure this update is intentional and compatible with the codebase.


🌐 Web query:

What are the breaking changes in Prisma 6.4.x compared to 6.3.x?

💡 Result:

Prisma ORM versions between v6.3.x and v.4.x introduce several notable breaking changes:


Schema & Client Changes

Full-Text Search Changes

  • The fullTextSearch Preview feature now only works with MySQL by default[1][5].
  • PostgreSQL users must enable the new fullTextSearchPostgres Preview feature instead[1].

Buffer → Uint8Array Migration

  • Fields using Bytes now return/expect Uint8Array instead of Node.js’s Buffer[1][5].
  • Requires updating all code using Buffer with these fields[1][5].

Error Handling Updates

  • NotFoundError has been removed entirely[1][5].
  • Use PrismaClientKnownRequestError with error code P2025 when handling errors from methods like:
    findUniqueOrThrow()
    findFirstOrThrow()

Reserved Keywords

The following can no longer be used as model names:

model async {} // ❌ Invalid
model await {} // ❌ Invalid
model using {} // ❌ Invalid

Migration Engine Fixes (CockroachDB)

  • Improved migration performance for CockroachDB by resolving inefficiencies[7].

Patch Fixes (v**...**)

  • CLI Flags: Added support for --no-hints flag compatibility[8].
  • NPS Survey: Fixed issues causing unintended survey prompts[8].

For upgrades:
1️⃣ Check your usage of full-text search features
2️⃣ Replace all instances of Buffer with Uint8Array** 3️⃣ Update error handling logic where **NotFoundError` was used
4️⃣ Validate model names against new reserved keywords

Always test thoroughly after upgrading[1][5][7].

Citations:


Action: Verify Prisma 6.4.x Compatibility

The following command installs Prisma 6.4.x:

run('npm i --no-audit --no-fund typescript [email protected] @prisma/[email protected] zod@^3.22.4 decimal.js @types/node');

Please note that the upgrade from Prisma 6.3.x to 6.4.x introduces several breaking changes, including:

  • Full-Text Search: The preview feature now defaults to MySQL; PostgreSQL users must enable the fullTextSearchPostgres preview.
  • Buffer to Uint8Array Migration: Fields of type Bytes now work with Uint8Array instead of Node’s Buffer. Ensure all related code is updated accordingly.
  • Error Handling: The removal of NotFoundError means that error handling using methods like findUniqueOrThrow() should now rely on PrismaClientKnownRequestError with code P2025.
  • Reserved Keywords: Certain model names (e.g., async, await, using) are now disallowed.

Please double-check the codebase for any dependencies on these behaviors to confirm that the upgrade is intentional and compatible with your current implementations.

packages/runtime/src/enhance.d.ts (1)

2-2: LGTM!

The export statement correctly mirrors the changes in packages/runtime/res/enhance.d.ts, maintaining type system consistency.

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

257-267: LGTM! Clean implementation of the utility method.

The implementation is concise and handles edge cases properly. The method name clearly describes its purpose, and the implementation follows functional programming principles.

tests/integration/tests/cli/plugins.test.ts (1)

78-78: LGTM! Consistent version updates.

The Prisma package versions have been updated consistently from 6.3.x to 6.4.x for both @prisma/client and prisma packages.

Also applies to: 88-88

tests/regression/tests/issue-2007.test.ts (1)

1-94: LGTM! Well-structured regression tests.

The tests effectively cover both positive and negative cases for policy rules:

  • regression1: Verifies allowed updates
  • regression2: Verifies denied updates due to policy constraints
packages/schema/tests/schema/validation/attribute-validation.test.ts (1)

1373-1393: LGTM! Comprehensive regex validation tests.

The tests effectively cover important validation cases for the @regex attribute:

  1. Validates that regex patterns must be string literals
  2. Validates that regex patterns must be syntactically valid
tests/regression/tests/issue-1998.test.ts (2)

7-34: LGTM! Well-structured schema definition.

The schema effectively models entity relationships with proper permission rules. The use of @@delegate and @@allow attributes provides clear access control based on the updatable field.


40-57: LGTM! Comprehensive test coverage.

The test cases effectively validate both positive and negative scenarios:

  1. Successful deletion when both entities are updatable
  2. Failed deletion when both entities are non-updatable
tests/regression/tests/issue-1997.test.ts (2)

7-68: LGTM! Well-designed multi-tenant schema.

The schema effectively implements:

  • Proper tenant isolation using tenantId
  • Correct foreign key relationships
  • Appropriate permission rules

73-80: LGTM! Proper test setup.

The test setup correctly:

  • Creates tenant and user entities
  • Enhances DB context with proper authentication
packages/sdk/src/utils.ts (2)

636-674: LGTM! Well-implemented backlink resolution.

The getRelationBackLink function effectively:

  • Validates field type reference
  • Handles inheritance from delegate models
  • Properly matches relation names

676-685: LGTM! Clean utility function.

The getRelationName function is concise and focused on a single responsibility.

packages/sdk/src/model-meta-generator.ts (1)

291-291: LGTM! Improved code organization.

Good refactoring to use the consolidated getRelationBackLink function from utils.ts instead of local implementations.

packages/runtime/src/enhancements/node/delegate.ts (1)

1128-1135: Ensure compound key usage is consistent across all ID lookups.

The code checks idValues for multiple keys and composes a compound unique filter if needed. This approach is consistent with the logic for regular deletions. Make sure all paths that delete base records take advantage of this helper to avoid partial or inconsistent deletions when IDs are compound.

tests/regression/tests/issue-2000.test.ts (1)

7-20: Validate intended behavior for @deny('update').

The abstract model Base includes @deny('update', true) on several fields (e.g., id, createdAt). Ensure that this fully aligns with your requirements. If your workflow allows certain updates to these fields under exceptional conditions, you might need more granular rules or conditional policies.

packages/schema/src/plugins/enhancer/enhance/index.ts (3)

67-71: LGTM! Well-structured properties for JSON type fields.

The new properties are well-organized and clearly documented:

  • modelsWithJsonTypeFields stores models with JSON type fields
  • modelsWithJsonTypeFieldsInputOutputPattern stores regex patterns for matching input/output types

87-102: LGTM! Efficient initialization of JSON type fields.

The constructor efficiently initializes the new properties:

  • Filters models with JSON type fields
  • Builds regex patterns for relevant type suffixes
  • Uses a single regex pattern per model for better performance

270-281: LGTM! Well-documented type for enhanced PrismaClient.

The new Enhanced<Client> type:

  • Is well-documented with JSDoc comments and examples
  • Correctly handles different PrismaClient variants
  • Preserves client extensions and options
packages/schema/src/plugins/zod/transformer.ts (3)

2-2: New imports for delegate handling
These added imports look correct and align with the purpose of filtering and mapping delegate input types.

Also applies to: 5-5, 8-8


73-77: Confirm exclusion of delegate-related enum values
The filter effectively removes enum values starting with DELEGATE_AUX_RELATION_PREFIX. Ensure this exclusion aligns with all intended use cases and doesn't omit other legitimate enum values.


253-266: Verify the impact of mapping delegate input types
The additional logic within this block invokes mapDelegateInputType, which transforms certain nested input types. Confirm that all delegate and non-delegate input types are still resolved correctly, and no unexpected transformations occur for non-delegate models.

packages/runtime/src/enhancements/node/policy/policy-utils.ts (3)

454-458: Validate field-level update guard usage
Using this.getFieldsWithDefinedValues(args.data ?? args) helps narrow guard checks to only defined fields. Confirm that no undefined or null fields slip through if partial updates are intended.


837-838: New fieldsToUpdate parameter
Adding fieldsToUpdate clarifies which fields are targeted for updates, ensuring more focused and accurate policy checks. Confirm that callers always supply the correct list of fields to avoid under-enforcement or missed checks.

Also applies to: 840-840


856-858: Conditional field-level guard enforcement
When operation === 'update' && fieldsToUpdate.length > 0, the guard checks are now stricter. Make sure that empty field arrays (e.g. no fields to update) default to the correct behavior and don’t inadvertently block updates.

packages/runtime/src/enhancements/node/default-auth.ts (1)

66-66: Add context parameter in nested writes
The context: NestedWriteVisitorContext addition correctly propagates nesting information for create/upsert/createMany. This should allow more precise default setting logic.

Also applies to: 94-94, 98-98, 102-102

packages/runtime/src/enhancements/node/policy/handler.ts (5)

287-296: LGTM! Improved foreign key policy checking.

The changes enhance policy checking accuracy by mapping "connect" operations to their actual foreign key updates, ensuring that only the relevant fields are checked against the policies.


331-334: LGTM! Consistent policy checking for connect operations.

The implementation correctly maps connect operations to their underlying foreign key updates, maintaining consistency with the connectOrCreate implementation.


974-980: LGTM! More precise update policy checking.

The implementation now only checks policies for fields that have defined values in the update payload, making the policy checks more precise and efficient.


924-926: LGTM! Consistent foreign key policy checking in connect/disconnect operations.

The implementation maintains consistency with other methods by correctly identifying and checking policies for the affected foreign key fields.


1171-1171: LGTM! Clarified field checking for delete operations.

The implementation now explicitly passes an empty array for delete operations, correctly indicating that delete operations affect the entire entity rather than specific fields.

Also applies to: 1788-1788

@ymc9 ymc9 merged commit 0107e1c into main Feb 25, 2025
13 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.

3 participants