Skip to content

fix(delegate): simulate cascade delete #2120

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
May 19, 2025
Merged

fix(delegate): simulate cascade delete #2120

merged 3 commits into from
May 19, 2025

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented May 19, 2025

fixes #2102

Copy link
Contributor

coderabbitai bot commented May 19, 2025

📝 Walkthrough

"""

Walkthrough

The changes introduce support for cascade deletion in polymorphic model hierarchies. New metadata properties for relation actions were added, the delegate deletion logic was updated to recursively cascade deletes to related entities and their base models, and integration tests were expanded to verify correct cascade deletion behavior across model inheritance.

Changes

File(s) Change Summary
packages/runtime/src/cross/model-meta.ts Added RelationAction type and optional onDeleteAction/onUpdateAction properties to FieldInfo for relation action metadata.
packages/runtime/src/enhancements/node/delegate.ts Enhanced doDelete to support recursive cascade deletion of related delegate entities and their base models. Added helpers for cascade detection and relation traversal.
packages/sdk/src/model-meta-generator.ts Added extraction and output of onDeleteAction and onUpdateAction metadata for relational fields via new helper functions in the metadata generator.
tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts Renamed an existing delete test and added a new test verifying cascade deletes in a polymorphic delegate hierarchy, including assertions for base and derived model deletions.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DelegateProxyHandler
    participant CrudContract
    participant RelatedDelegate
    participant BaseDelegate

    Client->>DelegateProxyHandler: delete(entity)
    DelegateProxyHandler->>CrudContract: injectWhereAndSelect()
    DelegateProxyHandler->>DelegateProxyHandler: getRelationDelegateEntitiesForCascadeDelete()
    alt Related entities with Cascade
        loop For each related entity
            DelegateProxyHandler->>DelegateProxyHandler: doDelete(related entity, readBack=false)
        end
    end
    DelegateProxyHandler->>CrudContract: delete main entity
    alt Need to delete base entity
        DelegateProxyHandler->>DelegateProxyHandler: doDelete(base entity, readBack=false)
    end
    DelegateProxyHandler-->>Client: return result
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure cascade delete of an extended model item also deletes its base model item (#2102)
Correctly propagate cascade deletes through polymorphic delegate model hierarchies (#2102)
Add and utilize metadata for relation actions (onDelete/onUpdate) in model and runtime (#2102)
Add integration tests to verify cascade deletion for base and extended models (#2102)
"""

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 632f10e and c38469c.

📒 Files selected for processing (1)
  • packages/runtime/src/enhancements/node/delegate.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/runtime/src/enhancements/node/delegate.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: dependency-review
  • GitHub Check: build-test (20.x)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: build-test (20.x)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: build-test (20.x)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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: 2

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

1227-1236: Inefficient N × M querying – combine look-ups

For every qualifying relation field the code performs a standalone findMany, which explodes to N database round-trips per parent delete.
When deleting a batch of parents (deleteManydoDeleteMany → per-entity doDelete) this balloons to N × M queries.

Consider aggregating the look-ups:

  1. Collect all relation models in one pass.
  2. Issue a single findMany per relation model with an in filter on the compound ids of the parent set.

This reduces DB chatter and speeds up cascade deletes on large data sets.

[performance]


1243-1245: Hard-coded literal 'Cascade' – favour enum safety

onDeleteAction is typed as RelationAction; hard-coding the string makes the comparison brittle to future enum renames or casing changes.

-return fieldInfo.onDeleteAction === 'Cascade';
+return fieldInfo.onDeleteAction === 'Cascade'; // TODO: replace with constant e.g., RelationAction.Cascade

Export a constant (or reuse Prisma’s) so the compiler flags typos automatically.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 03d6f7f and 4347fdb.

📒 Files selected for processing (4)
  • packages/runtime/src/cross/model-meta.ts (2 hunks)
  • packages/runtime/src/enhancements/node/delegate.ts (1 hunks)
  • packages/sdk/src/model-meta-generator.ts (2 hunks)
  • tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts (1)
packages/testtools/src/schema.ts (1)
  • loadSchema (163-369)
packages/sdk/src/model-meta-generator.ts (1)
packages/sdk/src/utils.ts (3)
  • getAttribute (141-157)
  • getAttributeArg (172-182)
  • isEnumFieldReference (196-198)
packages/runtime/src/enhancements/node/delegate.ts (3)
packages/runtime/src/types.ts (1)
  • CrudContract (86-86)
packages/runtime/src/enhancements/node/utils.ts (1)
  • formatObject (9-11)
packages/runtime/src/cross/model-meta.ts (2)
  • getFields (237-239)
  • FieldInfo (31-122)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: build-test (20.x)
  • GitHub Check: dependency-review
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (7)
packages/runtime/src/cross/model-meta.ts (2)

23-26: Good addition of the RelationAction type

The new RelationAction type correctly defines all standard Prisma relation action values for cascade behaviors.


82-90: Appropriate metadata extension for relation actions

The addition of onDeleteAction and onUpdateAction properties to the FieldInfo type correctly enables tracking relation behaviors at runtime. This is essential for implementing cascade operations across the model hierarchy.

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

314-325: Well implemented extraction of relation actions

The code correctly extracts onDeleteAction and onUpdateAction values from model fields and adds them to the generated metadata. This enables the runtime to properly handle cascading operations.


584-593: Good extraction of onDelete relation attribute

The getOnDeleteAction helper function properly retrieves the onDelete argument from the @relation attribute if it exists and is an enum reference.


595-604: Good extraction of onUpdate relation attribute

The getOnUpdateAction helper function properly retrieves the onUpdate argument from the @relation attribute if it exists and is an enum reference. This complements the onDeleteAction support for complete relation action handling.

tests/integration/tests/enhancements/with-delegate/enhanced-client.test.ts (2)

1060-1060: Appropriate test renaming

Renaming the test from delete to delete simple improves clarity and differentiates it from the new cascade delete test.


1109-1156: Comprehensive cascade delete test implementation

The new test case thoroughly validates the cascade delete functionality across a polymorphic model hierarchy. It:

  1. Creates a schema with proper inheritance relationships
  2. Establishes onDelete: Cascade relations between models
  3. Creates nested records and verifies that deleting the parent cascades to children
  4. Checks both the enhanced client and the underlying Prisma client for proper deletion

This test effectively verifies that cascade delete works as expected through delegate enhancements.

@ymc9 ymc9 merged commit 4900d08 into dev May 19, 2025
11 checks passed
@ymc9 ymc9 deleted the fix/issue-2102 branch May 19, 2025 22:37
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