Skip to content

fix(orm): handle self-referential relations in delegate models during schema push#2449

Merged
ymc9 merged 1 commit into
devfrom
fix/issue-2435-delegate-self-ref-cyclic-dependency
Mar 5, 2026
Merged

fix(orm): handle self-referential relations in delegate models during schema push#2449
ymc9 merged 1 commit into
devfrom
fix/issue-2435-delegate-self-ref-cyclic-dependency

Conversation

@ymc9
Copy link
Copy Markdown
Member

@ymc9 ymc9 commented Mar 5, 2026

Summary

  • Fixes a cyclic dependency error thrown by toposort when a model uses @@delegate inheritance and also has a self-referential relation (e.g. a parent/replies pattern)
  • Root cause: SchemaDbPusher.sortModels was adding a [Post, Post] edge to the dependency graph for self-referential FKs, which toposort correctly rejects as a cycle
  • Fix: skip self-referential relations (field.type === model.name) when building the topological sort graph

Test plan

  • Added regression test tests/regression/test/issue-2435.test.ts that reproduces the exact schema from the issue report
  • Test confirmed failing before fix, passing after fix

Closes #2435

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Fixed incorrect cyclic dependency detection when models contain self-referential relations. These relations no longer trigger false cycle warnings that previously blocked schema compilation.
  • Tests

    • Added regression test to ensure models with self-referential relations compile without cyclic dependency errors.

… schema push

Skip self-referential FK relations when building the topological sort graph
in SchemaDbPusher, preventing a false cycle error when a model using
@@DeleGate inheritance also has a self-referential relation.

Fixes #2435

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@claude
Copy link
Copy Markdown
Contributor

claude Bot commented Mar 5, 2026

Claude finished @ymc9's task —— View job


Code Review in Progress

Reviewing PR #2449 for:

  • Code quality and best practices
  • Potential bugs or issues
  • Performance considerations
  • Security concerns
  • Test coverage

Summary

This PR fixes a cyclic dependency error in toposort when models use both @@delegate inheritance and self-referential relations. The fix is clean, targeted, and well-tested.

Detailed Review

Code Quality & Best Practices

  • Clean implementation: The fix at packages/orm/src/client/helpers/schema-db-pusher.ts:87-90 is minimal and surgical
  • Clear intent: The comment clearly explains why self-referential relations are skipped
  • Consistent style: Follows existing code patterns and indentation
  • Appropriate placement: The check is positioned correctly before creating the graph edge

Bug Fix Analysis

  • Root cause correctly identified: The issue was [Post, Post] edges being added to the topological sort graph for self-referential foreign keys
  • Logical solution: Self-referential relations don't need topological ordering since a table can reference itself
  • Targeted fix: Only affects the specific problematic case without impacting other relation handling

Performance Considerations

  • Minimal overhead: Simple string comparison field.type === model.name is very efficient
  • Reduced complexity: Avoiding false cycles actually improves toposort performance
  • No algorithmic changes: The core sorting logic remains the same

Security Assessment

  • No security implications: This is a build-time schema processing fix
  • Input validation preserved: All existing checks remain in place
  • No data exposure: The change only affects internal dependency graph construction

Test Coverage

  • Comprehensive regression test: tests/regression/test/issue-2435.test.ts reproduces the exact failing scenario
  • Real-world schema: Uses delegate inheritance with self-referential relations (Post with replies)
  • Proper test structure: Follows repository conventions for regression tests
  • Validates fix: Test should fail before the fix and pass after

💡 Minor Suggestions

  1. Consider edge case documentation: While unlikely, the comment could mention that this assumes model names match their types consistently

  2. Potential test enhancement: Could add a test case with multiple levels of delegate inheritance + self-refs to ensure robustness

🔍 Code Deep Dive

The fix is in the sortModels method where dependency edges are built for topological sorting:

// Before: This would create [Post, Post] edge for self-referential FK
// After: Skip self-referential relations
if (field.type === model.name) {
    continue;
}

This is the correct approach because:

  • Self-referential FKs don't require ordering constraints
  • The table can reference itself once created
  • Skipping prevents false cycles in toposort

Verdict: ✅ APPROVED

This is a well-executed fix that:

  • ✅ Correctly identifies and solves the root cause
  • ✅ Uses minimal, clean code changes
  • ✅ Includes comprehensive regression testing
  • ✅ Has no performance or security concerns
  • ✅ Follows repository best practices

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 5, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 56e7f58c-c59b-429e-86f7-ea233a474797

📥 Commits

Reviewing files that changed from the base of the PR and between 3c181f6 and 79a6d60.

📒 Files selected for processing (2)
  • packages/orm/src/client/helpers/schema-db-pusher.ts
  • tests/regression/test/issue-2435.test.ts

📝 Walkthrough

Walkthrough

Fixes a cyclic dependency error in delegate models with self-referential relations by adding a guard in the topological sort logic to skip self-edges. Includes a regression test validating that delegate models can now safely reference themselves without triggering false cycle detection.

Changes

Cohort / File(s) Summary
Self-Reference Guard
packages/orm/src/client/helpers/schema-db-pusher.ts
Adds a conditional check to skip adding edges for self-referential relations when a field's type matches the model's own name, preventing false cycles in topological sorting.
Regression Test
tests/regression/test/issue-2435.test.ts
Adds a test case verifying that delegate models with self-referential relations (e.g., Post → Post replies) compile without cyclic dependency errors. Schema includes Content base model with delegation and Post/Post1 derived models.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

  • #1821: Addresses handling of self-referential relations in delegate and polymorphic models by fixing generation of inherited relation fields.

Poem

🐰 A rabbit hops through cycles round,
Self-edges tangled, loops abound!
But skip the self, the guard rings true,
Now delegates can reference too!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and specifically describes the main change: fixing handling of self-referential relations in delegate models during schema push.
Linked Issues check ✅ Passed The pull request fully addresses issue #2435 by skipping self-referential relations when building the topological sort graph and includes a regression test demonstrating the fix resolves the reported cyclic dependency error.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the self-referential relation handling in delegate models; the schema-db-pusher.ts modification and regression test are both necessary and tightly focused on resolving issue #2435.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/issue-2435-delegate-self-ref-cyclic-dependency

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@ymc9 ymc9 merged commit 75d77de into dev Mar 5, 2026
8 checks passed
@ymc9 ymc9 deleted the fix/issue-2435-delegate-self-ref-cyclic-dependency branch March 5, 2026 03:17
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.

Bug Report: Cyclic Dependency with Self-Referential Relations in Delegate Models

1 participant