Skip to content

merge dev to main (v2.11.3) #1963

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

Merged
merged 3 commits into from
Jan 14, 2025
Merged

merge dev to main (v2.11.3) #1963

merged 3 commits into from
Jan 14, 2025

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Jan 14, 2025

No description provided.

Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

📝 Walkthrough

Walkthrough

This pull request introduces support for a new Prisma operation called updateManyAndReturn, which allows batch updates of multiple records while returning the updated results. The changes span multiple files across the runtime and schema packages, adding the new action type to constants, types, and proxy handlers. Integration and regression tests have been added to validate the functionality of this new method, ensuring it works correctly with model-level and field-level policies.

Changes

File Change Summary
packages/ide/jetbrains/build.gradle.kts Version bumped from "2.11.2" to "2.11.3"
packages/runtime/src/constants.ts Added 'updateManyAndReturn' to ACTIONS_WITH_WRITE_PAYLOAD
packages/runtime/src/cross/nested-write-visitor.ts Added handling for updateManyAndReturn action in doVisit method
packages/runtime/src/cross/types.ts Added 'updateManyAndReturn' to PrismaWriteActions
packages/runtime/src/enhancements/node/policy/handler.ts Implemented updateMany and updateManyAndReturn methods in PolicyProxyHandler
packages/runtime/src/enhancements/node/proxy.ts Added updateManyAndReturn method to PrismaProxyHandler and DefaultPrismaProxyHandler
packages/runtime/src/types.ts Added updateManyAndReturn method to DbOperations interface
packages/schema/src/plugins/prisma/schema-generator.ts Added setDummyDefault method for handling default values
tests/... Added integration and regression tests for updateManyAndReturn functionality

Sequence Diagram

sequenceDiagram
    participant Client
    participant PrismaProxyHandler
    participant PolicyProxyHandler
    participant Database

    Client->>PrismaProxyHandler: updateManyAndReturn(args)
    PrismaProxyHandler->>PolicyProxyHandler: updateManyAndReturn(args)
    PolicyProxyHandler->>PolicyProxyHandler: doUpdateMany(args, 'updateManyAndReturn')
    PolicyProxyHandler->>Database: Perform batch update
    Database-->>PolicyProxyHandler: Return updated records
    PolicyProxyHandler-->>PrismaProxyHandler: Return updated records
    PrismaProxyHandler-->>Client: Return updated records
Loading

Possibly related PRs

Finishing Touches

  • 📝 CodeRabbit is generating docstrings... (♻️ Check again to generate again)

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: 0

🧹 Nitpick comments (6)
tests/regression/tests/issue-1955.test.ts (1)

43-52: Enhance test coverage for updateManyAndReturn.

While the basic functionality is tested, consider adding test cases for:

  • Updates with where clause conditions
  • Verification of relationship fields after update
  • Edge cases with empty result sets

Example test case:

 await expect(
     db.post.updateManyAndReturn({
         data: { name: 'foo' },
+        where: { name: { startsWith: 'bl' } }
     })
 ).resolves.toEqual(
     expect.arrayContaining([
         expect.objectContaining({ name: 'foo' }),
         expect.objectContaining({ name: 'foo' }),
     ])
 );
+
+// Test empty result set
+await expect(
+    db.post.updateManyAndReturn({
+        data: { name: 'foo' },
+        where: { name: 'nonexistent' }
+    })
+).resolves.toEqual([]);

Also applies to: 106-115

tests/integration/tests/enhancements/with-policy/update-many-and-return.test.ts (1)

3-140: LGTM! Comprehensive test coverage with room for enhancement.

The test suite thoroughly covers both model-level and field-level policies, including read-back restrictions and relation handling. Consider adding explicit error cases:

// Add error case tests
it('handles invalid updates', async () => {
    const db = enhance();
    
    // Test invalid data
    await expect(
        db.post.updateManyAndReturn({
            data: { nonexistentField: 'value' }
        })
    ).rejects.toThrow();

    // Test invalid where condition
    await expect(
        db.post.updateManyAndReturn({
            where: { nonexistentField: 'value' },
            data: { title: 'foo' }
        })
    ).rejects.toThrow();
});
packages/schema/src/plugins/prisma/schema-generator.ts (1)

883-898: Consider using constants for default values.

The implementation is robust, but could benefit from defining constants for the default values to improve maintainability.

+const DEFAULT_VALUES = {
+    STRING: '',
+    NUMBER: '0',
+    BOOLEAN: 'false',
+    JSON: '{}',
+    BYTES: ''
+} as const;

 private setDummyDefault(result: ModelField, field: DataModelField) {
     const dummyDefaultValue = match(field.type.type)
-        .with('String', () => new AttributeArgValue('String', ''))
-        .with(P.union('Int', 'BigInt', 'Float', 'Decimal'), () => new AttributeArgValue('Number', '0'))
-        .with('Boolean', () => new AttributeArgValue('Boolean', 'false'))
+        .with('String', () => new AttributeArgValue('String', DEFAULT_VALUES.STRING))
+        .with(P.union('Int', 'BigInt', 'Float', 'Decimal'), () => new AttributeArgValue('Number', DEFAULT_VALUES.NUMBER))
+        .with('Boolean', () => new AttributeArgValue('Boolean', DEFAULT_VALUES.BOOLEAN))
         .with('DateTime', () => new AttributeArgValue('FunctionCall', new PrismaFunctionCall('now')))
-        .with('Json', () => new AttributeArgValue('String', '{}'))
-        .with('Bytes', () => new AttributeArgValue('String', ''))
+        .with('Json', () => new AttributeArgValue('String', DEFAULT_VALUES.JSON))
+        .with('Bytes', () => new AttributeArgValue('String', DEFAULT_VALUES.BYTES))
         .otherwise(() => {
             throw new PluginError(name, `Unsupported field type with default value: ${field.type.type}`);
         });
packages/runtime/src/enhancements/node/policy/handler.ts (3)

1317-1324: Consider adding a comment explaining the select optimization.

The code optimizes the select clause to only return ID fields for read-back checks, but this important optimization could be better documented.

 // make sure only id fields are returned so we can directly use the result
-// for read-back check
+// for read-back check. This optimization reduces the amount of data
+// transferred and processed during the operation.
 const updatedArg = {
     ...args,
     select: this.policyUtils.makeIdSelection(this.model),
     include: undefined,
 };

1331-1337: Consider consolidating error handling patterns.

The error handling pattern for read-back operations is repeated in multiple places. Consider extracting it into a utility method for better maintainability.

+private handleReadBackErrors(results: Array<{error?: Error; result: unknown}>): unknown[] {
+    const error = results.find((r) => !!r.error)?.error;
+    if (error) {
+        throw error;
+    }
+    return results.map((r) => r.result);
+}

-// throw read-back error if any of create result read-back fails
-const error = result.find((r) => !!r.error)?.error;
-if (error) {
-    throw error;
-} else {
-    return result.map((r) => r.result);
-}
+return this.handleReadBackErrors(result);

1419-1425: Consider adding logging for read-back errors.

When read-back operations fail, it would be helpful to log the error before throwing it, to aid in debugging.

 const error = readBackResult.find((r) => !!r.error)?.error;
 if (error) {
+    if (this.shouldLogQuery) {
+        this.logger.error(`[policy] Read-back failed for ${this.model}: ${error.message}`);
+    }
     throw error;
 } else {
     return readBackResult.map((r) => r.result);
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ba80eda and 506cf99.

⛔ Files ignored due to path filters (13)
  • 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/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 (10)
  • packages/ide/jetbrains/build.gradle.kts (1 hunks)
  • packages/runtime/src/constants.ts (1 hunks)
  • packages/runtime/src/cross/nested-write-visitor.ts (1 hunks)
  • packages/runtime/src/cross/types.ts (1 hunks)
  • packages/runtime/src/enhancements/node/policy/handler.ts (5 hunks)
  • packages/runtime/src/enhancements/node/proxy.ts (2 hunks)
  • packages/runtime/src/types.ts (1 hunks)
  • packages/schema/src/plugins/prisma/schema-generator.ts (2 hunks)
  • tests/integration/tests/enhancements/with-policy/update-many-and-return.test.ts (1 hunks)
  • tests/regression/tests/issue-1955.test.ts (4 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 (7)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (11)
packages/runtime/src/cross/types.ts (1)

11-11: LGTM! Type definition is consistent.

The addition of 'updateManyAndReturn' to PrismaWriteActions is well-placed and maintains type safety through PrismaWriteActionType.

packages/runtime/src/constants.ts (1)

80-80: LGTM! Constant definition aligns with types.

The addition to ACTIONS_WITH_WRITE_PAYLOAD is consistent with the type definition and maintains the expected behavior for write operations.

packages/runtime/src/types.ts (1)

22-22: LGTM! The interface addition is well-designed.

The new updateManyAndReturn method follows the established patterns:

  • Consistent argument type with other methods
  • Return type appropriately reflects batch operation results
  • Positioned logically in the interface
packages/runtime/src/cross/nested-write-visitor.ts (1)

Line range hint 250-263: LGTM! The visitor implementation is robust and consistent.

The updateManyAndReturn case correctly:

  • Reuses the existing updateMany callback
  • Maintains the visitor pattern integrity
  • Preserves the batch operation behavior
packages/runtime/src/enhancements/node/proxy.ts (2)

38-39: LGTM! The interface addition is well-defined.

The method signature in PrismaProxyHandler interface is consistent with the DbOperations interface.


137-140: LGTM! The implementation follows best practices.

The implementation:

  • Uses the deferred pattern consistently
  • Maintains proper type safety
  • Follows the established method implementation pattern
packages/schema/src/plugins/prisma/schema-generator.ts (1)

872-879: LGTM! The logical mode handling is well-implemented.

The conditional logic for handling auth-based defaults is clear and properly scoped.

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

514-514: LGTM! Grammar improvement in error message.

The addition of the article "the" improves the readability of the error message.


1271-1276: LGTM! Clean method declarations.

The separation of concerns using a shared private implementation is well-designed. The method signatures are clear and consistent with the rest of the codebase.


Line range hint 1290-1338: Excellent optimization for simple updates!

The code optimizes performance by avoiding transactions when possible, specifically when:

  • No post-update rules exist
  • No Zod schema validation is needed
  • No entity checker is present

This optimization can significantly improve performance for simple update operations.


Line range hint 1344-1407: Robust transaction handling with comprehensive policy checks.

The implementation properly handles:

  1. Pre-update value collection
  2. Entity checker integration
  3. Post-write checks
  4. Transaction management

This ensures data consistency and policy compliance throughout the update operation.

Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Caution

No docstrings were generated.

@ymc9 ymc9 merged commit b220213 into main Jan 14, 2025
11 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