Skip to content

fix(schema): default many-to-many inverse foreign key to CASCADE - #12663

Merged
alumni merged 4 commits into
typeorm:masterfrom
kyungseopk1m:fix/manytomany-inverse-relation-cascade-default
Jul 20, 2026
Merged

alumni merged 4 commits into
typeorm:masterfrom
kyungseopk1m:fix/manytomany-inverse-relation-cascade-default

Conversation

@kyungseopk1m

Copy link
Copy Markdown
Contributor

Description of change

Bidirectional many-to-many relations generate two junction foreign keys, and the default onDelete/onUpdate was inconsistent between them. The owning side falls back to CASCADE when no options are given, but the inverse side did not — it used the inverse relation's onDelete/onUpdate directly, which is undefined when the inverse @ManyToMany declares no options, so it ended up as NO ACTION.

For a plain bidirectional relation this means:

  • owning FK: ON DELETE CASCADE ON UPDATE CASCADE
  • inverse FK: ON DELETE NO ACTION ON UPDATE NO ACTION

This applies the same fallback used on the owning side to the inverse branches, so both foreign keys default to CASCADE. Unidirectional relations are unaffected (they already went through the CASCADE branch), and an inverse side with explicit options keeps its values.

Verified with a new test under test/github-issues/11738 that builds the metadata for a bidirectional @ManyToMany and asserts both junction foreign keys use CASCADE. It fails on the current code (inverse FK is NO ACTION) and passes with the fix. tsc --noEmit, Prettier and ESLint are clean.

Closes #11738

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links a relevant issue using a closing keyword: Closes #11738
  • There are new or updated tests validating the change (test/github-issues/11738/issue-11738.test.ts)
  • Documentation has been updated to reflect this change — N/A, restores the already-documented CASCADE default

The owning-side junction foreign key falls back to `relation.onDelete ?? "CASCADE"`,
but the inverse side had no such fallback and used the inverse relation's onDelete/onUpdate
directly. A bidirectional @manytomany without explicit options therefore generated an
inverse foreign key with NO ACTION instead of CASCADE, so the two sides of the same join
table disagreed.

Apply the same CASCADE fallback to the inverse branches.
@github-actions github-actions Bot added the linked-issue PR references an issue label Jul 7, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm@12663
    

commit: a9a0748

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Junction FK default undocumented 📘 Rule violation ⚙ Maintainability
Description
This PR changes the default onDelete/onUpdate behavior for inverse-side many-to-many junction
foreign keys to fall back to CASCADE, which is a user-facing schema-generation change. No
documentation updates were included to reflect/clarify this behavior (and related driver
exceptions), increasing risk of user confusion and unexpected migrations.
Code

src/metadata-builder/JunctionEntityMetadataBuilder.ts[R239-249]

                   onDelete:
                       this.dataSource.driver.options.type === "spanner"
                           ? "NO ACTION"
-                              : relation.inverseRelation
-                                ? relation.inverseRelation.onDelete
-                                : "CASCADE",
+                              : (relation.inverseRelation?.onDelete ??
+                                "CASCADE"),
                   onUpdate:
                       this.dataSource.driver.options.type === "oracle" ||
                       this.dataSource.driver.options.type === "spanner"
                           ? "NO ACTION"
-                              : relation.inverseRelation
-                                ? relation.inverseRelation.onUpdate
-                                : "CASCADE",
+                              : (relation.inverseRelation?.onUpdate ??
+                                "CASCADE"),
Evidence
The PR changes inverse-side junction foreign key defaults to use `relation.inverseRelation?.onDelete
?? "CASCADE" and relation.inverseRelation?.onUpdate ?? "CASCADE"`, making the implicit schema
behavior different for users who did not set these options. The docs describe a general onDelete
default of RESTRICT and do not document the many-to-many junction foreign key default
behavior/driver exceptions, so the user-facing change is not reflected in documentation.

Rule 2: Docs updated for user-facing changes
src/metadata-builder/JunctionEntityMetadataBuilder.ts[239-249]
docs/docs/relations/1-relations.md[15-21]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PR changes schema-generation defaults for inverse-side many-to-many junction foreign keys to fall back to `CASCADE` when `onDelete`/`onUpdate` are not specified. This is user-facing behavior and should be documented (including exceptions like Spanner/Oracle behavior).
## Issue Context
Docs currently describe a general `onDelete` default of `RESTRICT`, but do not clearly explain the effective defaults for many-to-many junction-table foreign keys. This PR makes inverse-side behavior match the owning-side fallback, so documenting the junction-table behavior helps prevent confusion and surprises during migrations.
## Fix Focus Areas
- docs/docs/relations/4-many-to-many-relations.md[1-80]
- docs/docs/relations/1-relations.md[15-21]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Per-issue test added (#11738) ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
The fix adds a new test only under test/github-issues/11738, which conflicts with the guideline to
keep issue fixes in the functional test suite unless there is a clear reason. This can increase
long-term maintenance overhead and fragment coverage across multiple suites.
Code

test/github-issues/11738/issue-11738.test.ts[R1-43]

+import type { DataSource } from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+    reloadTestingDatabases,
+} from "../../utils/test-utils"
+import { Post } from "./entity/Post"
+import { Category } from "./entity/Category"
+import { expect } from "chai"
+
+describe("github issues > #11738 many-to-many inverse-side junction FK should default to CASCADE", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [Post, Category],
+            enabledDrivers: ["better-sqlite3"],
+        })
+    })
+
+    beforeEach(() => reloadTestingDatabases(dataSources))
+    after(() => closeTestingConnections(dataSources))
+
+    it("both junction foreign keys default to onDelete/onUpdate CASCADE", () => {
+        dataSources.forEach((dataSource) => {
+            const junctionMetadata = dataSource.entityMetadatas.find(
+                (metadata) => metadata.foreignKeys.length === 2,
+            )
+            expect(junctionMetadata, "junction entity metadata").to.not.be
+                .undefined
+
+            const foreignKeys = junctionMetadata!.foreignKeys
+            expect(foreignKeys).to.have.length(2)
+
+            // Owning-side FK and inverse-side FK must both fall back to CASCADE
+            // when no explicit onDelete/onUpdate is specified.
+            foreignKeys.forEach((foreignKey) => {
+                expect(foreignKey.onDelete).to.be.equal("CASCADE")
+                expect(foreignKey.onUpdate).to.be.equal("CASCADE")
+            })
+        })
+    })
+})
Evidence
PR Compliance ID 3 requires issue fixes to be covered by test/functional rather than adding
per-issue tests under test/github-issues unless there is a clear reason. The PR adds the new
regression test under test/github-issues/11738/issue-11738.test.ts.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/11738/issue-11738.test.ts[1-43]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A new regression test for #11738 was added under `test/github-issues/11738`, but the compliance rule prefers placing issue-fix tests in `test/functional` unless there is a clear reason.
## Issue Context
The PR introduces `test/github-issues/11738/issue-11738.test.ts` (and supporting entities) as the only added test coverage for this change.
## Fix Focus Areas
- test/github-issues/11738/issue-11738.test.ts[1-43]
- test/github-issues/11738/entity/Post.ts[1-15]
- test/github-issues/11738/entity/Category.ts[1-13]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Qodo Logo

@Cprakhar

Copy link
Copy Markdown
Collaborator

@kyungseopk1m Enable tests for other drivers as well and if possible move it functional tests.

Relocate the typeorm#11738 regression test out of test/github-issues into the
functional many-to-many suite and run it against all configured drivers
instead of better-sqlite3 only. Assertions account for Spanner (no
UPDATE/DELETE CASCADE) and Oracle (no UPDATE CASCADE), matching the
junction builder's per-driver fallbacks.
@kyungseopk1m

Copy link
Copy Markdown
Contributor Author

@Cprakhar moved to the functional suite and enabled all drivers. assertions branch for spanner/oracle since those keep NO ACTION.

@Cprakhar
Cprakhar requested a review from alumni July 19, 2026 14:28

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @kyungseopk1m 🙏

@alumni alumni added the backport This fix should be backported to a previous version label Jul 20, 2026
@alumni
alumni merged commit a68612e into typeorm:master Jul 20, 2026
46 checks passed
@github-actions github-actions Bot added this to the 2.0.next milestone Jul 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport This fix should be backported to a previous version linked-issue PR references an issue

Development

Successfully merging this pull request may close these issues.

Inconsistent default relation options with @ManyToMany relations

4 participants