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

fix(policy): revers lookup condition to parent entity is not properly built with compound id fields #2053

Merged
merged 7 commits into from
Mar 23, 2025

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Mar 21, 2025

fixes #1964

Copy link
Contributor

coderabbitai bot commented Mar 21, 2025

📝 Walkthrough

Walkthrough

This pull request updates several classes to require explicit passing of the database context when constructing query conditions. Methods in both the delegate and policy handlers now call an updated asynchronous version of buildReversedQuery that accepts a db parameter, ensuring consistency in query construction. The QueryUtils class has been modified to include a new logger property and to update its method signature and internal logic. Additionally, new regression tests have been introduced to verify that the changes address issues related to nested operations under strict undefined checks.

Changes

File(s) Change Summary
packages/runtime/src/enhancements/node/delegate.ts
packages/runtime/src/enhancements/node/policy/handler.ts
Updated calls to buildReversedQuery to include an extra db parameter and use the await keyword to ensure the asynchronous query is fully resolved before proceeding.
packages/runtime/src/enhancements/node/query-utils.ts Added a logger property; updated the buildReversedQuery method signature to include the db parameter and renamed unsafeOperation to uncheckedOperation; enhanced internal logging and query condition handling.
tests/regression/tests/issue-1964.test.ts Introduced a new test suite with regression tests to validate proper handling of nested operations under the strictUndefinedCheck feature.
packages/runtime/src/enhancements/node/policy/policy-utils.ts Removed the Logger import and logger property from the PolicyUtil class, indicating the removal of logging functionality in this context.
packages/testtools/src/schema.ts Modified logic for setting the previewFeatures property to ensure it always has a defined value, either from options or as a default.
packages/server/src/api/rest/index.ts Updated the count method call to use args.where ?? {} to prevent passing null or undefined to the method.
tests/regression/tests/issue-765.test.ts Updated loadSchema function call to include an object parameter for previewFeatures, enhancing schema loading capabilities.
tests/integration/tests/enhancements/with-policy/unique-as-id.test.ts Added two new test cases to verify the functionality of unique fields in nested updates for one-to-many and one-to-one relationships.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Handler
    participant QueryUtils
    participant Database
    Client->>Handler: Invoke update/delete operation (with db, context)
    Handler->>QueryUtils: await buildReversedQuery(db, context, options)
    QueryUtils->>Database: Execute query logic with logging
    Database-->>QueryUtils: Return query conditions/result
    QueryUtils-->>Handler: Provide reversed query
    Handler-->>Client: Return operation result
Loading

Assessment against linked issues

Objective (from #1964) Addressed Explanation
Error calling enhanced Prisma method with strictUndefinedCheck (#1964)

Possibly related issues

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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: 1

🧹 Nitpick comments (2)
packages/runtime/src/enhancements/node/delegate.ts (2)

1029-1029: Consider using undefined assignment instead of delete operator.

According to the static analysis hint, using the delete operator can impact performance. Consider replacing delete context.parent['delete'] with context.parent['delete'] = undefined for better performance.

- delete context.parent['delete'];
+ context.parent['delete'] = undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 1029-1029: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


1037-1037: Consider using undefined assignment instead of delete operator.

Similar to the previous suggestion, consider replacing delete context.parent['deleteMany'] with context.parent['deleteMany'] = undefined for better performance.

- delete context.parent['deleteMany'];
+ context.parent['deleteMany'] = undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 1037-1037: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e0676f2 and a16bb9d.

📒 Files selected for processing (4)
  • packages/runtime/src/enhancements/node/delegate.ts (2 hunks)
  • packages/runtime/src/enhancements/node/policy/handler.ts (10 hunks)
  • packages/runtime/src/enhancements/node/query-utils.ts (3 hunks)
  • tests/regression/tests/issue-1964.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
packages/runtime/src/enhancements/node/query-utils.ts (4)
packages/runtime/src/enhancements/node/logger.ts (1) (1)
  • Logger (8-66)
packages/runtime/src/types.ts (2) (2)
  • DbClientContract (91-93)
  • CrudContract (86-86)
packages/runtime/src/enhancements/node/create-enhancement.ts (1) (1)
  • InternalEnhancementOptions (31-64)
packages/runtime/src/enhancements/edge/utils.ts (1) (1)
  • formatObject (9-11)
🪛 Biome (1.9.4)
packages/runtime/src/enhancements/node/delegate.ts

[error] 1029-1029: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (17)
packages/runtime/src/enhancements/node/query-utils.ts (4)

13-15: Updated dependencies to support new logging functionality.

The new import of Logger and update to use formatObject from edge are necessary to support the enhanced logging functionality added to this class.


19-23: Added logger property to QueryUtils class.

A new logger property has been added and properly initialized in the constructor. This change allows for consistent logging throughout the class, specifically when executing queries during reverse lookups.


69-74: Modified buildReversedQuery method signature to include database context.

The method signature has been updated to:

  1. Accept a database context parameter (db: CrudContract)
  2. Make the method asynchronous
  3. Rename unsafeOperation to uncheckedOperation for better clarity

These changes ensure the method can execute database queries when needed to resolve compound ID fields.


116-118: Improved readability of condition check.

Renamed unsafeOperation to uncheckedOperation for better semantic clarity throughout the codebase. This makes the code more maintainable and easier to understand.

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

812-813: Updated buildReversedQuery call to pass database context.

The method call has been properly updated to pass the database context and await the result, in line with the method signature changes in QueryUtils.


888-889: Correctly awaiting buildReversedQuery with database context.

This update ensures that the database context is passed to the buildReversedQuery method when checking for duplicate constraints, which is critical for proper operation with compound ID fields.


939-940: Updated buildReversedQuery call for update operation.

Properly updated to pass the database context and await the result when building a unique filter for update operations with nested writing.


1000-1001: Updated buildReversedQuery call for updateMany operation.

Updated to pass the database context and properly await the result when handling the reverse query for updateMany operations.


1069-1070: Updated buildReversedQuery call for upsert operation.

Correctly passing the database context and awaiting the result when building a unique filter for upsert operations.


1146-1147: Updated buildReversedQuery call for set operation.

Database context is now correctly passed and the result awaited when building the reverse query for set operations.


1165-1166: Updated buildReversedQuery call for delete operation.

The method call has been updated to pass the database context parameter and properly await the result for delete operations.


1182-1183: Updated buildReversedQuery call for deleteMany operation.

Properly updated to include the database context parameter and await the result when building the query for deleteMany operations.

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

962-963: Updated buildReversedQuery call in updateMany handler.

The call has been correctly updated to pass the database context and await the result, aligning with the method signature changes in QueryUtils.


1025-1026: Updated buildReversedQuery call in delete handler.

Properly passing the database context and awaiting the result when building the where clause for delete operations, ensuring correct behavior with compound ID fields.


1033-1034: Updated buildReversedQuery call in deleteMany handler.

The method call now correctly passes the database context and awaits the result when building the where clause for deleteMany operations.

tests/regression/tests/issue-1964.test.ts (2)

1-60: Well-designed regression test for compound ID lookup issue.

Excellent test case that verifies the fix for compound ID fields in reverse lookup conditions. This test:

  1. Creates a schema with Author and Post models with a relationship
  2. Defines a compound unique key (@@unique([orgId, name])) on the Author model
  3. Tests the scenario where an update operation needs to delete related posts
  4. Uses the compound key orgId_name in the where clause of the update operation

This effectively tests the scenario where the policy handler needs to correctly build a reverse lookup condition with a compound ID field.


61-128: Comprehensive regression test for nested update operations.

This test case provides thorough coverage for:

  1. Nested updates across multiple levels of relationships (User → Profile → Address)
  2. Verifies that deleteMany operation works correctly in a nested context
  3. Validates the result by checking that the Address entity was properly deleted

The test uses strictUndefinedChecks preview feature, which likely helps expose the issue with compound ID fields and undefined values during reverse lookups.

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 (1)
packages/runtime/src/enhancements/node/delegate.ts (1)

905-905: Added null check for safer object handling

This change properly handles the case when args.where is undefined by using the nullish coalescing operator, preventing potential errors when operating on a missing where clause.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2826974 and 4180576.

📒 Files selected for processing (3)
  • packages/runtime/src/enhancements/node/delegate.ts (4 hunks)
  • packages/runtime/src/enhancements/node/policy/handler.ts (11 hunks)
  • packages/testtools/src/schema.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/runtime/src/enhancements/node/delegate.ts

[error] 1029-1029: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (8)
packages/testtools/src/schema.ts (1)

99-103: Always enabling strictUndefinedChecks makes sense for reliable testing

This change ensures that strictUndefinedChecks is always enabled in the preview features for test environments when no preview features are explicitly provided. This is a good improvement as it creates more consistent test behavior and helps prevent issues with undefined values in complex queries - which is likely related to the PR's goal of fixing reverse lookup conditions with compound ID fields.

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

962-962: Updated to correctly pass database context in buildReversedQuery

The function call now includes the database context parameter and uses await since the method has been updated to be asynchronous. This ensures proper database context is available when building compound ID field conditions.


1025-1025: Updated to correctly pass database context in delete operation

Similar to the other instances, this ensures the database context is properly passed to the query builder for delete operations.


1033-1033: Updated to correctly pass database context in deleteMany operation

The function call now includes the database context parameter and uses await since the method is asynchronous, ensuring proper query construction.


1098-1098: Added null check for safer object handling in doDeleteMany

Similar to the earlier change, this properly handles undefined values for the where parameter by using the nullish coalescing operator.

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

812-812: Updated to correctly pass database context in policy handler

The function call now includes the database context parameter and uses await for the asynchronous method. This aligns with the changes in the delegate handler to ensure proper handling of compound ID fields.


888-889: Consistently updated buildReversedQuery calls to include database context

All instances of buildReversedQuery calls have been updated to include the database context parameter and to use await for handling the asynchronous nature of the method. This comprehensive update ensures consistency throughout the codebase and properly handles compound ID field conditions.

Also applies to: 900-900, 940-940, 1000-1000, 1033-1033, 1066-1066, 1146-1146, 1165-1165, 1182-1182


1093-1093: Added null check for safer handling of where clause

The added nullish coalescing operator ensures that an empty object is used when args.where is undefined, preventing potential errors in downstream operations.

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 (1)
tests/integration/tests/enhancements/with-policy/unique-as-id.test.ts (1)

199-199: Consider standardizing the logPrismaQuery option across tests

This test includes a new option { logPrismaQuery: true } which isn't used in other test cases. This might be intentional for debugging purposes, but it creates inconsistency in the test configuration.

If this was added for debugging, consider either:

  • Removing it before merging if no longer needed
  • Adding it to all tests for consistency
  • Moving it to a common configuration if you want to enable it globally
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 935d539 and 215e359.

📒 Files selected for processing (1)
  • tests/integration/tests/enhancements/with-policy/unique-as-id.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: build-test (20.x)
🔇 Additional comments (3)
tests/integration/tests/enhancements/with-policy/unique-as-id.test.ts (3)

175-233: Good test case for compound unique keys with one-to-many relationships

This test effectively verifies that nested operations on to-many relationships work correctly when using compound unique fields as identifiers. It properly tests both update and delete operations, ensuring that only the targeted records are affected.

The test structure is clear and follows a good pattern:

  1. Setup data with two parent-child relationships
  2. Perform operations on one relationship
  3. Verify both the affected and unaffected relationships

235-296: Good test case for compound unique keys with one-to-one relationships

This test effectively verifies that nested operations on to-one relationships work correctly when using compound unique fields as identifiers. It provides good coverage for both update and delete operations.

The test properly validates both the direct effects (deletion/update of the targeted record) and the absence of side effects (other relationships remaining intact).


175-296: Comprehensive regression tests for PR #2053

These test cases thoroughly validate the fix for issue #1964 by demonstrating correct behavior for both one-to-many and one-to-one relationships when using compound unique fields as identifiers in parent models.

The tests are well-structured and cover:

  1. Nested update operations through compound unique keys
  2. Nested delete operations through compound unique keys
  3. Verification that operations don't affect unrelated records

This provides good coverage for the "reverse lookup condition to parent entity" issue mentioned in the PR description.

@ymc9 ymc9 merged commit 8a1289c into dev Mar 23, 2025
11 checks passed
@ymc9 ymc9 deleted the fix/issue-1964 branch March 23, 2025 20:19
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