-
-
Notifications
You must be signed in to change notification settings - Fork 95
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
Conversation
) Co-authored-by: Youssef Gaber <[email protected]> Co-authored-by: ymc9 <[email protected]>
📝 WalkthroughWalkthroughThis 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
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
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
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.ktsException in thread "main" com.beust.jcommander.ParameterException: Provided path 'packages/ide/jetbrains/build.gradle.kts' does not exist! 🔧 markdownlint-cli2 (0.17.2)packages/ide/jetbrains/CHANGELOG.mdmarkdownlint-cli2 v0.17.2 (markdownlint v0.37.4) ✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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
CodeRabbit Configuration File (
|
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: 2
🔭 Outside diff range comments (1)
packages/ide/jetbrains/CHANGELOG.md (1)
3-8
: 🛠️ Refactor suggestionRemove 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:
- Negative test cases to verify validation failures
- Structure validation of parsed data
- Test cases for
UserGoogle
model- 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:
- More descriptive error messages
- Common pattern validation
- 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:
- More descriptive error message
- 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:
- Centralize filtering logic in a utility function
- 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 toPromise.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
ordeleted
properties, to ensure that all policy constraints remain consistent and validated.packages/schema/src/plugins/enhancer/enhance/index.ts (1)
787-836
: Consider refactoring thefixJsonFieldType
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 inmapDelegateInputType
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
: EnhancesetDefaultValueForModelData
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
⛔ 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/expectUint8Array
instead of Node.js’sBuffer
[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 codeP2025
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 ofBuffer
withUint8Array** 3️⃣ Update error handling logic where **
NotFoundError` was used
4️⃣ Validate model names against new reserved keywordsAlways test thoroughly after upgrading[1][5][7].
Citations:
- 1: https://github.com/prisma/prisma/releases
- 2: https://docs.paloaltonetworks.com/content/techdocs/en_US/prisma-sd-wan/release-notes/6-4/prisma-sd-wan-ion-device-release-6-4/upgrade-downgrade-considerations-in-prisma-sd-wan-ion-release-6-4
- 3: https://www.prisma.io/docs/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-4
- 4: https://www.answeroverflow.com/m/1342180886870884352
- 5: https://www.prisma.io/changelog
- 6: https://docs.paloaltonetworks.com/prisma/prisma-sd-wan/6-4/prisma-sd-wan-ion-release-notes/prisma-sd-wan-ion-device-release-6-4/known-issues-in-prisma-sd-wan-ion-release-6-4
- 7: https://www.gitclear.com/open_repos/prisma/prisma/release/6.4.0
- 8: https://www.gitclear.com/open_repos/prisma/prisma/release/6.4.1
- 9: https://www.npmjs.com/package/@prisma/migrate/v/6.4.0-dev.9
- 10: Cannot upgrade from 5.x.x to 6.x.x using Express, Prisma and Multer uploads lukeautry/tsoa#1651
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 withUint8Array
instead of Node’sBuffer
. Ensure all related code is updated accordingly.- Error Handling: The removal of
NotFoundError
means that error handling using methods likefindUniqueOrThrow()
should now rely onPrismaClientKnownRequestError
with codeP2025
.- 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
andprisma
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 updatesregression2
: Verifies denied updates due to policy constraintspackages/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:
- Validates that regex patterns must be string literals
- 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 theupdatable
field.
40-57
: LGTM! Comprehensive test coverage.The test cases effectively validate both positive and negative scenarios:
- Successful deletion when both entities are updatable
- 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 fieldsmodelsWithJsonTypeFieldsInputOutputPattern
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 withDELEGATE_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 invokesmapDelegateInputType
, 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
Usingthis.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
: NewfieldsToUpdate
parameter
AddingfieldsToUpdate
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
Whenoperation === '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
Thecontext: 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
No description provided.