Skip to content

fix: prefer user-defined junction metadata over auto-generated - #11720

Open
ashwintemkar wants to merge 13 commits into
typeorm:masterfrom
ashwintemkar:fix/junction-metadata-precedence-11637
Open

ashwintemkar wants to merge 13 commits into
typeorm:masterfrom
ashwintemkar:fix/junction-metadata-precedence-11637

Conversation

@ashwintemkar

@ashwintemkar ashwintemkar commented Oct 10, 2025 •

Copy link
Copy Markdown

Description of change

Fix related issue: #11637

So when a user defined junction entity exists, 0.3.26 regressed many to many persistence and inserted DEFAULT/NULL into the junction table FKs. There the root cause was metadata resolution favoring the auto generated junction metadata over the user defined junction entity when both were present (via how entityMetadatasMap was consulted).

So now I have updated DataSource lookup logic to prefer the user defined junction metadata, restoring correct FK values in the junction table and keeping entityMetadatasMap conflict-free.

Tests included

Verification

Notes

  • No behavior change for projects that use only auto generated junction tables.
  • No documentation impact expected.

Pull-Request Checklist

Summary by CodeRabbit

  • New Features

    • Improved handling of user-defined junction tables for many-to-many relations, ensuring correct metadata resolution.
  • Bug Fixes

    • Prevents errors when querying relations that use custom junction table entities.
  • Tests

    • Added functional tests covering user-defined junction table scenarios and persistence/metadata correctness.

…serve m2m inserts

0.3.26 regressed many to many persistence when a custom junction entity exists: the ORM
inserted rows into the junction table with DEFAULT/NULL FK values. Root cause was metadata
resolution selecting auto generated junction metadata over the user defined entity when both
were present, due to how entityMetadatasMap was consulted.

Change:
- DataSource: prefer user defined junction metadata over auto generated so m2m persistence
  keeps working while entityMetadatasMap still avoids conflicts

Tests:
- Added regression coverage for typeorm#11637 to ensure junction rows receive proper FK values when a
  custom junction entity exists.
- Restored the earlier typeorm#11114 regression tests to confirm repositories built from EntitySchema
  junction tables still expose relations correctly

Closes typeorm#11637
Refs typeorm#11114
@coderabbitai

coderabbitai Bot commented Oct 10, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a protected method on DataSource that deduplicates auto-generated junction entity metadatas by promoting user-defined junction metadata, remapping columns/foreign keys, updating relation references, and removing duplicate junction entries; includes tests exercising user-defined junction tables and the regression from issue #11637.

Changes

Cohort / File(s) Summary
Core deduplication logic
src/data-source/DataSource.ts
Adds protected deduplicateJunctionEntityMetadatas(entityMetadatas: EntityMetadata[]): EntityMetadata[] and associated column/foreign-key mapping logic; invokes it during buildMetadatas to replace entity metadata with deduplicated set.
Junction table test entities
test/functional/entity-metadata/entity/junction-table/entities.ts
Adds three EntitySchema definitions (User, Document, DocumentRelation) modeling a many-to-many via an explicit junction table with snake_case columns and explicit join/inverse column mappings.
Functional test coverage
test/functional/entity-metadata/entity-metadata-builder.ts
New functional test suite that initializes data sources with the junction entities and asserts repository metadata and find-with-relations do not throw for user-defined junction tables.
Issue regression test
test/github-issues/11637/issue-11637.ts
Adds regression test reproducing #11637: persists many-to-many via a user-defined junction entity and asserts junction rows contain correct foreign keys and relations load.

Sequence Diagram(s)

sequenceDiagram
    participant DS as DataSource
    participant EMB as EntityMetadataBuilder
    participant DED as deduplicateJunctionEntityMetadatas()

    DS->>EMB: buildMetadatas()
    EMB-->>DS: returns entityMetadatas (auto-generated + user-defined)
    DS->>DED: deduplicateJunctionEntityMetadatas(entityMetadatas)
    DED->>DED: identify duplicate junction metadatas
    DED->>DED: promote user-defined junction metadata
    DED->>DED: remap columns & foreign keys to user metadata
    DED->>DED: update relation metadata to reference promoted metadata
    DED->>DED: remove superseded auto-generated junction metadatas
    DED-->>DS: deduplicated entityMetadatas
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

comp: relations, need review help, size-m

Suggested reviewers

  • alumni
  • sgarner
  • gioboa

Poem

🐰
I hopped through metadatas, neat and spry,
Found duplicates hiding, gave them a try.
I stitched columns and keys in a tidy line,
So junction rows hold what they should: keys that align.
Rejoice — no more NULLs — a rabbit's small rhyme.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "fix: prefers user defined junction metadata over auto generated for many to many and added regression tests" accurately summarizes the main changes in the changeset. The title clearly identifies the primary fix (preferring user-defined over auto-generated junction metadata) and explicitly mentions the addition of regression tests, which directly corresponds to the code changes: the new deduplicateJunctionEntityMetadatas method in DataSource.ts and the three new test files added to validate the fix. The title is specific, concise, and sufficiently clear that a developer reviewing pull request history would understand this addresses a many-to-many relationship regression with junction entity metadata precedence.
Linked Issues Check ✅ Passed The code changes directly address all primary coding objectives from linked issue #11637. The implementation adds a deduplicateJunctionEntityMetadatas method to DataSource.ts that promotes user-defined junction entity metadata over auto-generated synthetic metadata by remapping columns and foreign keys, updating relations, and removing duplicate metadata entries—directly fixing the regression where junction table inserts were using DEFAULT/NULL values instead of proper foreign key relationships. The PR also includes three new test files that validate the fix: a regression test specifically for issue #11637 that confirms junction tables contain correct FK values, an entity-metadata-builder functional test that verifies metadata deduplication prevents duplicate relations, and EntitySchema-based entity definitions supporting the test scenarios. These changes collectively restore pre-0.3.26 behavior and ensure framework preference for user-defined junction metadata while preserving compatibility with auto-generated junction tables.
Out of Scope Changes Check ✅ Passed All code changes in this pull request are directly in scope for fixing issue #11637 and implementing the stated PR objectives. The modification to src/data-source/DataSource.ts implements the core deduplication logic to resolve the junction metadata precedence issue, while the three new test files (entity-metadata-builder.ts, junction-table/entities.ts, and issue-11637.ts) provide regression and functional testing to validate the fix and ensure EntitySchema-based junction tables function correctly. No changes to documentation, public API surface beyond an internal protected method, or unrelated features are present. The PR scope remains tightly focused on resolving the many-to-many relationship regression with user-defined junction entities and validating the solution through comprehensive testing.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@pkg-pr-new

pkg-pr-new Bot commented Oct 11, 2025 •

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

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

commit: b7f6e1a

@coveralls

coveralls commented Oct 11, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 81.22% (+0.04%) from 81.176%
when pulling b7f6e1a on ashwintemkar:fix/junction-metadata-precedence-11637
into 1fa4129 on typeorm:master.

@ashwintemkar
ashwintemkar marked this pull request as ready for review October 13, 2025 15:24
@ashwintemkar
ashwintemkar marked this pull request as draft October 13, 2025 15:25
@ashwintemkar

Copy link
Copy Markdown
Author

@sgarner @ragrag pardon me for tagging,

I have opened this Draft PR to check whether anything more is needed out of the fix I have put up, please let me know if this is ready for review, as the core problem is fixed

@ragrag ragrag left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

overall i think this approach looks cogent and should behave more consistently than the previous implementation 🙏🏻

Comment thread src/data-source/DataSource.ts Resolved
Comment thread src/data-source/DataSource.ts Resolved
@ashwintemkar

Copy link
Copy Markdown
Author

Thanks for pointing those out! @ragrag , I pulled the stray junction-table regression test back out and added inline comments explaining why we prefer user-defined metadata over the synthetic junction entry. Let me know if you’d like any more detail there.

@ragrag

ragrag commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor

Thanks for pointing those out! @ragrag , I pulled the stray junction-table regression test back out and added inline comments explaining why we prefer user-defined metadata over the synthetic junction entry. Let me know if you’d like any more detail there.

sorry i meant to only remove the enabledDrivers: ['sqlite'] part (the line my comment was on initially) we should keep the tests for sure, rest lgtm!

@ashwintemkar

Copy link
Copy Markdown
Author

so dropping the explicit enabledDrivers override I hit the Postgres-only failure I saw constraint "... does not exist", which meant the auto-generated junction metadata was still hanging around alongside the user-defined entity. That’s why I extended EntityMetadataBuilder

We now merge the auto-generated junction metadata back into the user-defined entity, reuse its columns, and drop the duplicate entry. Without that, Postgres tries to create the same PK/FKs twice and the regression resurfaces.
Relations that were wired to the synthetic junction metadata are re-pointed to the user entity so many-to-many inserts keep their FK values vet_specialty, feed_resources_categories, etc.
Existing coverage for the #11114 scenario is still passing, and the new regression test for #11637 passes on Postgres with the fix npm test -- --grep "junction".

So the earlier logic from commit 95baf98 is still there, and the new builder hook just finishes the job by reconciling the actual metadata objects.

@ragrag

ragrag commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor

We now merge the auto-generated junction metadata back into the user-defined entity, reuse its columns, and drop the duplicate entry. Without that, Postgres tries to create the same PK/FKs twice and the regression resurfaces. Relations that were wired to the synthetic junction metadata are re-pointed to the user entity so many-to-many inserts keep their FK values vet_specialty, feed_resources_categories, etc. Existing coverage for the #11114 scenario is still passing, and the new regression test for #11637 passes on Postgres with the fix npm test -- --grep "junction".

could we perhaps do this merging once for all conflicting junction metadatas during metaDatasMap registration (or merging such tables before the metadata generation step)? that would be a much simpler single change, you think something like that could work?

e.g:

entityMetadatasMap: new Map(
    withDeduplicatedJunctionTables(entityMetadatas).map((metadata) => [metadata.target, metadata]),
),

also it could be worth investigating if typeorm already has some internal method for metadata merging or table merging that we could instead of mergeWithUserDefinedJunctions

@ragrag

ragrag commented Oct 15, 2025 •

Copy link
Copy Markdown
Contributor

throwing other ideas i feel that might solve this more straightforwardly. originally entityMetaDatasMap was introduced in f12a95c to make metadata lookups faster, we could potentially explore some variants that would maintain the fast lookups that have potential to work:

1 - use the previous metadata logic that loops over entityMetadatas and adding a cache on top in favor of entityMetadatasMap, so the initial lookup will have similar result pre 3.13 and consequent lookups will be resolved from the cache to the correct metadata. essentially having entityMetadatasMap but building it in a lazy fashion (imho the most straight forward)

2 - in findMetadata, if entity found in entityMetadatasMap is a junction entity (or an entity we know is a potential duplicate junction entity from some precalculation we did) do not return it and, fallback to old logic that loops over entityMetadatas from the commit above

3 - gathering a set of user defined tables that have a junction pair in entityMetadatas, in findMetadata check if target is part of that set and if that's the case fallback to old logic that loops over entityMetadatas from the commit above

4- wild idea and not sure if it'll work but constructing entityMetadatasMap from the reverse of entityMetadatas, my guess is that junction and virtual tables are pushed to the end of entityMetadatas causing the map overriding to happen

theoretically all of those solutions should maintain the same behaviour as before the regression introduced in 3.13 (from the commit above) and would avoid potentially error prone metadata merging, let me know what you think

@ashwintemkar

Copy link
Copy Markdown
Author

Hey @ragrag thanks for the detailed suggestions!

I moved the reconciliation to metadata registration:

  1. we now deduplicate the auto-generated junction metadata before entityMetadatasMap is built
  2. reuse the junction FK definitions on the user entity
  3. repoint the relations to the user metadata.

That keeps the map fast, avoids the extra builder hook, and resolves the Postgres constraint/index failures.

Happy to iterate further!! if you spot anything else.

also for your reference

throwing other ideas i feel that might solve this more straightforwardly. originally entityMetaDatasMap was introduced in f12a95c to make metadata lookups faster, we could potentially explore some variants that would maintain the fast lookups that have potential to work:

1 - use the previous metadata logic that loops over entityMetadatas and adding a cache on top in favor of entityMetadatasMap, so the initial lookup will have similar result pre 3.13 and consequent lookups will be resolved from the cache to the correct metadata. essentially having entityMetadatasMap but building it in a lazy fashion (imho the most straight forward)

2 - in findMetadata, if entity found in entityMetadatasMap is a junction entity (or an entity we know is a potential duplicate junction entity from some precalculation we did) do not return it and, fallback to old logic that loops over entityMetadatas from the commit above

3 - gathering a set of user defined tables that have a junction pair in entityMetadatas, in findMetadata check if target is part of that set and if that's the case fallback to old logic that loops over entityMetadatas from the commit above

4- wild idea and not sure if it'll work but constructing entityMetadatasMap from the reverse of entityMetadatas, my guess is that junction and virtual tables are pushed to the end of entityMetadatas causing the map overriding to happen

theoretically all of those solutions should maintain the same behaviour as before the regression introduced in 3.13 (from the commit above) and would avoid potentially error prone metadata merging, let me know what you think

A lazy cache (option 1) and the targeted fallbacks (options 2 & 3) still leave duplicate metadata in entityMetadatas, so the schema builder continued to create duplicate PK/FK definitions in Postgres.

Reversing the insertion order (option 4) depends on incidental ordering and still risks selecting the wrong metadata.

Hence the new deduplication step keeps the fast lookups from entityMetadatasMap, avoids metadata merging inside the builder, and gives us a single, predictable place to reconcile the two metadata sources.

@ragrag

ragrag commented Oct 16, 2025 •

Copy link
Copy Markdown
Contributor

Amazing work!

Hence the new deduplication step keeps the fast lookups from entityMetadatasMap, avoids metadata merging inside the builder, and gives us a single, predictable place to reconcile the two metadata sources.

just wondering if we still need all the other changes done now (the change in findMetadata, and buildMetadata), shouldn't the metadata merging with deduplicateJunctionEntityMetadatas alone pre-registration with the old way fix the issue?

btw did you manage to find any typeorm internals that do the metadata merging?

@ashwintemkar

ashwintemkar commented Oct 16, 2025 •

Copy link
Copy Markdown
Author

just wondering if we still need all the other changes done now (the change in findMetadata, and buildMetadata),

so I initally thought that the ideas were good when this #11720 (comment) was suggested but then I thought deduplicateJunctionEntityMetadatas would bring the edge here.

shouldn't the metadata merging with deduplicateJunctionEntityMetadatas alone pre-registration with the old way fix the issue?

and you’re right that the heavy lifting happens in the new deduplicateJunctionEntityMetadatas step. I reverted the tweaks to findMetadata and to the entityMetadatasMap construction so they’re back to the exact logic we had with the synthetic junction metadata removed before the map is built, those extra guard rails aren’t needed.

btw did you manage to find any typeorm internals that do the metadata merging?

And also I didn’t find an existing helper in TypeORM that performs this reconciliation. I checked the metadata builders and schema helpers, but nothing exposed the junction metadata we needed to reuse.

so currently
deduplicateJunctionEntityMetadatas runs right after buildEntityMetadatas, strips out the auto generated junction entries, and rewires any relations that were pointing at them and because the duplicates are gone, findMetadata’s original implementation is returning the correct user defined entity without the additional filtering.

for now I think this can go in as the original findMetadata logic behaves exactly like pre‑3.13, and both the #11114 functional coverage and the #11637 regression test pass npm test -- --grep "entity-metadata-builder" and npm test -- --grep "junction"

Comment thread src/data-source/DataSource.ts Resolved
@ragrag

ragrag commented Oct 16, 2025

Copy link
Copy Markdown
Contributor

so currently deduplicateJunctionEntityMetadatas runs right after buildEntityMetadatas, strips out the auto generated junction entries, and rewires any relations that were pointing at them and because the duplicates are gone, findMetadata’s original implementation is returning the correct user defined entity without the additional filtering.

coool, seems like this covers all the edges so looks good from my side, perhaps other maintainers are more familiar in the matter of metadata merging

@ashwintemkar

ashwintemkar commented Oct 16, 2025 •

Copy link
Copy Markdown
Author

so currently deduplicateJunctionEntityMetadatas runs right after buildEntityMetadatas, strips out the auto generated junction entries, and rewires any relations that were pointing at them and because the duplicates are gone, findMetadata’s original implementation is returning the correct user defined entity without the additional filtering.

coool, seems like this covers all the edges so looks good from my side, perhaps other maintainers are more familiar in the matter of metadata merging

alright so should I mark this ready for review?, I mean turn into actual PR from draft?

@ragrag

ragrag commented Oct 16, 2025

Copy link
Copy Markdown
Contributor

alright so should I mark this ready for review?, I mean turn into actual PR from draft?

sure feel free to!

@ashwintemkar
ashwintemkar marked this pull request as ready for review October 16, 2025 17:37

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 181154a and b06d688.

📒 Files selected for processing (4)
  • src/data-source/DataSource.ts (3 hunks)
  • test/functional/entity-metadata/entity-metadata-builder.ts (1 hunks)
  • test/functional/entity-metadata/entity/junction-table/entities.ts (1 hunks)
  • test/github-issues/11637/issue-11637.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
test/functional/entity-metadata/entity-metadata-builder.ts (3)
src/data-source/DataSource.ts (1)
  • DataSource (58-944)
test/utils/test-utils.ts (3)
  • createTestingConnections (388-482)
  • reloadTestingDatabases (504-509)
  • closeTestingConnections (487-499)
test/functional/entity-metadata/entity/junction-table/entities.ts (1)
  • documentRelationEntitySchema (65-87)
test/github-issues/11637/issue-11637.ts (4)
src/decorator/relations/ManyToMany.ts (1)
  • ManyToMany (33-77)
src/decorator/relations/JoinTable.ts (1)
  • JoinTable (30-56)
src/data-source/DataSource.ts (1)
  • DataSource (58-944)
test/utils/test-utils.ts (3)
  • createTestingConnections (388-482)
  • reloadTestingDatabases (504-509)
  • closeTestingConnections (487-499)
src/data-source/DataSource.ts (4)
src/metadata/EntityMetadata.ts (1)
  • EntityMetadata (30-1139)
src/metadata/ColumnMetadata.ts (1)
  • ColumnMetadata (18-1003)
src/error/TypeORMError.ts (1)
  • TypeORMError (1-17)
src/metadata/ForeignKeyMetadata.ts (1)
  • ForeignKeyMetadata (11-127)
test/functional/entity-metadata/entity/junction-table/entities.ts (2)
src/driver/mongodb/typings.ts (1)
  • Document (3147-3147)
src/index.ts (1)
  • EntitySchema (182-182)

Comment thread src/data-source/DataSource.ts Resolved
… (referencedColumn / relationMetadata) and leave any user-defined column options untouched.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
src/data-source/DataSource.ts (1)

739-754: Consider adding an inline comment for the mapColumn helper.

While the logic is clear, a brief comment explaining that this helper maps junction columns to their corresponding user-entity columns (by database name) would improve maintainability.

Apply this diff to add an inline comment:

+        // Maps a junction column to its corresponding column in the user entity by database name
         const mapColumn = (column: ColumnMetadata): ColumnMetadata => {
             const match = userMetadata.columns.find(
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b06d688 and 064bef3.

📒 Files selected for processing (1)
  • src/data-source/DataSource.ts (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/data-source/DataSource.ts (4)
src/metadata/EntityMetadata.ts (1)
  • EntityMetadata (30-1139)
src/metadata/ColumnMetadata.ts (1)
  • ColumnMetadata (18-1003)
src/error/TypeORMError.ts (1)
  • TypeORMError (1-17)
src/metadata/ForeignKeyMetadata.ts (1)
  • ForeignKeyMetadata (11-127)
🔇 Additional comments (8)
src/data-source/DataSource.ts (8)

19-20: LGTM: Required imports for metadata handling.

The new imports for ColumnMetadata and ForeignKeyMetadata are necessary for the junction deduplication logic that follows.


714-719: LGTM: Clear documentation of purpose.

The method signature and comment clearly explain the deduplication strategy and why it's needed (favoring user-defined metadata over auto-generated).


723-730: LGTM: Efficient early-return optimization.

Building a map of user metadata by table path and returning early when no user entities exist is a good optimization.


750-751: LGTM: Correctly preserves user-defined column options.

The code now only copies the wiring properties (referencedColumn, relationMetadata) without overwriting user-configured structural column options (isNullable, type, length, etc.). This properly addresses the past review concern about clobbering user-provided settings.


756-808: LGTM: Comprehensive promotion logic.

The promotion sequence correctly:

  • Maps owner/inverse columns via the helper
  • Clones foreign keys with updated entity references
  • Deduplicates FKs using signature-based comparison (column names + referenced table)
  • Updates user metadata flags to mark it as a junction
  • Registers the deduplicated FKs

The signature generation (lines 781-785, 791-795) properly uses sorted column names to ensure order-independence.


810-829: LGTM: Relation update scope is comprehensive.

Iterating all entity metadatas to find and update relations that reference the synthetic junction is thorough. While this has O(n²) complexity in the number of entities and relations, it's necessary for correctness and acceptable for typical applications.

The relation update correctly:

  • Filters out old foreign keys from the synthetic junction
  • Registers new foreign keys mapped to the user entity
  • Re-registers join columns with the mapped columns
  • Updates the junction reference to point to the user metadata

834-848: LGTM: Main deduplication loop and filtering.

The loop correctly identifies synthetic junctions with matching user entities and promotes them, then filters out the superseded synthetic metadata. The Set-based removal tracking ensures clean deduplication.


871-876: LGTM: Proper integration into metadata build pipeline.

Invoking deduplicateJunctionEntityMetadatas immediately after building entity metadatas and before populating entityMetadatasMap ensures:

  • Synthetic duplicates are removed before fast-lookup structures are built
  • Downstream validation and schema sync see only the promoted user metadata
  • No duplicate PK/FK constraints are created

This addresses the core regression from issue #11637.

@gioboa
gioboa requested a review from sgarner October 24, 2025 18:30
@ashwintemkar

Copy link
Copy Markdown
Author

Hey @gioboa and @ragrag , since @sgarner and @alumni might take some time to review according to their availability, as all checks have passed, I had a small request, as maintainers could y'all add a hacktoberfest accepted tag onto this PR, since I have participated in the hacktoberfest, I think adding the tag might count as contribution, just want to see if that works.

@ashwintemkar

Copy link
Copy Markdown
Author

thanks a tonne @gioboa

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

qodo-free-for-open-source-projects Bot commented Jan 3, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to b7f6e1a

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix inverse join columns mapping

Swap the ownerColumns and inverseColumns when registering join columns for the
inverse side of a many-to-many relation by checking the relation.isOwning
property.

src/data-source/DataSource.ts [829-848]

 entityMetadatas.forEach((metadata) => {
     metadata.relations
         .filter(
             (relation) =>
                 relation.junctionEntityMetadata ===
                 junctionMetadata,
         )
         .forEach((relation) => {
             relation.foreignKeys = relation.foreignKeys.filter(
                 (foreignKey) =>
                     foreignKey.entityMetadata !== junctionMetadata,
             )
             relation.registerForeignKeys(...foreignKeysToRegister)
-            relation.registerJoinColumns(
-                ownerColumns,
-                inverseColumns,
-            )
+
+            const joinCols = relation.isOwning ? ownerColumns : inverseColumns
+            const inverseJoinCols = relation.isOwning ? inverseColumns : ownerColumns
+            relation.registerJoinColumns(joinCols, inverseJoinCols)
+
             relation.registerJunctionEntityMetadata(userMetadata)
         })
 })
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a bug in the new logic where join columns for the inverse side of a many-to-many relation are not registered correctly, which would lead to incorrect queries and data persistence.

High
Prevent ambiguous junction promotion

Prevent promoting an entity to a junction table if multiple non-junction
entities map to the same table path, as this can lead to metadata corruption.

src/data-source/DataSource.ts [742-747]

 const userMetadatasByTable = new Map<string, EntityMetadata>()
+const ambiguousUserTables = new Set<string>()
+
 for (const metadata of entityMetadatas) {
-    if (!metadata.isJunction) {
-        userMetadatasByTable.set(metadata.tablePath, metadata)
+    if (metadata.isJunction) continue
+
+    if (userMetadatasByTable.has(metadata.tablePath)) {
+        ambiguousUserTables.add(metadata.tablePath)
+        continue
     }
+
+    userMetadatasByTable.set(metadata.tablePath, metadata)
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion addresses a valid edge case where multiple entities map to the same table, preventing potential metadata corruption by avoiding ambiguous junction promotion. This improves the robustness of the new feature.

Medium
General
Improve join column matching

Improve column matching logic by also comparing databaseNameWithoutPrefixes to
handle potential discrepancies from database-specific prefixes or quoting.

src/data-source/DataSource.ts [758-773]

 const mapColumn = (column: ColumnMetadata): ColumnMetadata => {
-    const match = userMetadata.columns.find(
-        (candidate) =>
-            candidate.databaseName === column.databaseName,
-    )
+    const match = userMetadata.columns.find((candidate) => {
+        if (candidate.databaseName === column.databaseName) return true
+        if (
+            candidate.databaseNameWithoutPrefixes &&
+            column.databaseNameWithoutPrefixes &&
+            candidate.databaseNameWithoutPrefixes ===
+                column.databaseNameWithoutPrefixes
+        ) {
+            return true
+        }
+        return false
+    })
+
     if (!match) {
         throw new TypeORMError(
             `Column "${column.databaseName}" referenced by the join table "${junctionMetadata.tableName}" was not found in the user-defined entity "${userMetadata.name}".`,
         )
     }
 
     match.referencedColumn = column.referencedColumn
     match.relationMetadata = column.relationMetadata
 
     return match
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion improves the robustness of column matching by considering databaseNameWithoutPrefixes, which handles cases with different naming strategies or database drivers more gracefully.

Medium
  • Update

Previous suggestions

Suggestions up to commit 7f2174b
CategorySuggestion                                                                                                                                    Impact
General
Include cascade options in signature

Improve the foreign key signature generation by including onDelete, onUpdate,
and deferrable properties. This ensures more accurate deduplication of foreign
keys.

src/data-source/DataSource.ts [779-787]

 const existingForeignKeySignatures = new Set(
     userMetadata.foreignKeys.map((foreignKey) => {
         const columnSignature = foreignKey.columns
             .map((column) => column.databaseName)
             .sort()
             .join(",")
-        return `${columnSignature}->${foreignKey.referencedEntityMetadata.tablePath}`
+        return `${columnSignature}->${foreignKey.referencedEntityMetadata.tablePath}:${foreignKey.onDelete}:${foreignKey.onUpdate}:${foreignKey.deferrable}`
     }),
 )
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that the foreign key signature is incomplete, which could lead to incorrectly identifying foreign keys as duplicates. Including onDelete, onUpdate, and deferrable in the signature makes the deduplication logic more accurate and robust.

Medium
Validate entity compatibility before promotion

Add a validation check to ensure a user-defined entity is not already a special
type (e.g., 'closure') before promoting it to a 'junction' table. This prevents
potential misconfigurations.

src/data-source/DataSource.ts [803-808]

+if (userMetadata.tableMetadataArgs.type && userMetadata.tableMetadataArgs.type !== "junction") {
+    throw new TypeORMError(
+        `Cannot promote entity "${userMetadata.name}" to junction table: entity is already defined as type "${userMetadata.tableMetadataArgs.type}".`,
+    )
+}
 userMetadata.tableMetadataArgs.type = "junction"
 userMetadata.tableType = "junction"
 userMetadata.isJunction = true
 userMetadata.ownerColumns = ownerColumns
 userMetadata.inverseColumns = inverseColumns
 userMetadata.foreignKeys.push(...foreignKeysToRegister)
Suggestion importance[1-10]: 4

__

Why: The suggestion proposes adding a defensive check before modifying an entity's metadata type. While this could prevent misconfiguration, an entity that matches a junction table's path but has another special type (like 'closure') is an unlikely edge case. The improvement is minor.

Low
Possible issue
Avoid mutating shared column metadata

Avoid mutating shared column metadata by cloning the ColumnMetadata object
within the mapColumn function before modifying its properties. This prevents
potential side effects.

src/data-source/DataSource.ts [739-754]

 const mapColumn = (column: ColumnMetadata): ColumnMetadata => {
     const match = userMetadata.columns.find(
         (candidate) =>
             candidate.databaseName === column.databaseName,
     )
     if (!match) {
         throw new TypeORMError(
             `Column "${column.databaseName}" referenced by the join table "${junctionMetadata.tableName}" was not found in the user-defined entity "${userMetadata.name}".`,
         )
     }
 
-    match.referencedColumn = column.referencedColumn
-    match.relationMetadata = column.relationMetadata
+    const clonedColumn = Object.create(Object.getPrototypeOf(match))
+    Object.assign(clonedColumn, match)
+    clonedColumn.referencedColumn = column.referencedColumn
+    clonedColumn.relationMetadata = column.relationMetadata
 
-    return match
+    return clonedColumn
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that mutating the match object, which is an element of userMetadata.columns, can lead to unintended side effects. Cloning the object before mutation is a good practice for robustness and prevents potential bugs that are hard to trace.

Low

gioboa
gioboa previously requested changes Jan 7, 2026

@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.

The test file must have .test.ts extension to be considered.

@ashwintemkar

Copy link
Copy Markdown
Author

The test file must have .test.ts extension to be considered.

sure @gioboa I will look into the changes needed

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

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

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

🐞 Bugs (2) 📘 Rule Violations (0) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider


Action Required

1. Missing indices transfer in junction deduplication 🐞 Bug
Description
• The deduplicateJunctionEntityMetadatas method transfers foreign keys and columns from
  auto-generated junction metadata to user-defined metadata, but does not transfer the indices
• Junction tables automatically get two indices created (one for owner columns, one for inverse
  columns) by JunctionEntityMetadataBuilder
• These indices are critical for query performance on many-to-many relations and are used by
  EntityMetadataBuilder when registering join columns via junctionEntityMetadata.ownIndices[0].columns
  and junctionEntityMetadata.ownIndices[1].columns
• When a user-defined entity replaces the auto-generated junction, these indices are lost,
  potentially causing severe performance degradation on many-to-many queries

performance

Code

src/data-source/DataSource.ts[R803-808]

+            userMetadata.tableMetadataArgs.type = "junction"
+            userMetadata.tableType = "junction"
+            userMetadata.isJunction = true
+            userMetadata.ownerColumns = ownerColumns
+            userMetadata.inverseColumns = inverseColumns
+            userMetadata.foreignKeys.push(...foreignKeysToRegister)
Evidence
The code transfers ownerColumns, inverseColumns, and foreignKeys to userMetadata but does not
transfer ownIndices. Junction tables require two indices for proper query performance, and these are
used by the relation registration process.

src/metadata-builder/JunctionEntityMetadataBuilder.ts[266-284]
src/metadata-builder/EntityMetadataBuilder.ts[304-307]

Agent Prompt
## Issue Description
The deduplicateJunctionEntityMetadatas method does not transfer the automatically-generated indices from the junction metadata to the user-defined metadata. Junction tables require two indices (one for owner columns, one for inverse columns) for proper query performance, and these indices are used by the relation registration process.

## Issue Context
Junction tables automatically get two indices created by JunctionEntityMetadataBuilder. These indices are critical because:
1. They improve query performance on many-to-many relations
2. They are used by EntityMetadataBuilder.registerJoinColumns() which accesses junctionEntityMetadata.ownIndices[0].columns and junctionEntityMetadata.ownIndices[1].columns
3. Without these indices, many-to-many queries will have degraded performance

## Fix Focus Areas
- src/data-source/DataSource.ts[803-808] - Add code to transfer indices after transferring foreign keys
- src/data-source/DataSource.ts[739-754] - Consider if the mapColumn function needs to be used to map index columns to user metadata columns

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


2. Column metadata mutation without validation 🐞 Bug
Description
• The mapColumn function unconditionally overwrites ColumnMetadata.referencedColumn and
  ColumnMetadata.relationMetadata properties on user-defined columns
• These properties are critical for column behavior and are used extensively in
  ColumnMetadata.getEntityValue() and other methods
• If user-defined columns already have these properties set (e.g., if the user defined their own
  relations on the junction entity), this code will overwrite them without validation
• This could break existing column configurations and relation mappings in the user-defined entity

correctness

Code

src/data-source/DataSource.ts[R750-751]

+                match.referencedColumn = column.referencedColumn
+                match.relationMetadata = column.relationMetadata
Evidence
The code directly assigns to match.referencedColumn and match.relationMetadata without checking if
these properties are already set. This could overwrite existing metadata if the user-defined
junction entity has its own relation definitions.

src/metadata/ColumnMetadata.ts[298-301]
src/metadata/ColumnMetadata.ts[44-48]
src/data-source/DataSource.ts[750-751]

Agent Prompt
## Issue Description
The mapColumn function unconditionally overwrites ColumnMetadata.referencedColumn and ColumnMetadata.relationMetadata properties without checking if they&#x27;re already set. This could break existing column configurations if the user-defined junction entity has its own relation definitions.

## Issue Context
The referencedColumn and relationMetadata properties are critical for column behavior:
- referencedColumn: Points to the column this foreign key references
- relationMetadata: Points to the relation this column belongs to
- Both are used extensively in ColumnMetadata.getEntityValue() and other methods
- Overwriting them could break existing functionality

## Fix Focus Areas
- src/data-source/DataSource.ts[750-751] - Add validation before overwriting these properties
- Consider: Should we skip assignment if already set, merge metadata, or throw an error on conflict?

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


Grey Divider

Qodo Logo

@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.

I fixed the test file name.

@ashwintemkar

Copy link
Copy Markdown
Author

I fixed the test file name.

okay, so is this pr now waiting only for approvals right?

@gioboa
gioboa dismissed their stale review January 15, 2026 10:26

Fixed.

@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.

okay, so is this pr now waiting only for approvals right?

That's correct. the PR now is ready with a green pipeline 💪

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

qodo-free-for-open-source-projects Bot commented Feb 20, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (5)   📘 Rule violations (1)   📎 Requirement gaps (0)   🎨 UX Issues (0)
🐞\ ≡ Correctness (3) ☼ Reliability (1) ➹ Performance (1) ⭐ New (2)
📘\ ≡ Correctness (1)

Grey Divider


Action required

1. Junction flag alters save semantics 🐞 ☼ ⭐
Description
Promotion forces userMetadata.isJunction = true, which makes persistence treat the user-defined
entity as a junction table globally. On drivers without multi-row RETURNING support, this can
re-enable bulk inserts for entities with generated/default columns (e.g. PrimaryGeneratedColumn),
risking incorrect/missing generated value mapping when users save multiple junction-entity instances
directly.
Code

src/data-source/DataSource.ts[R795-801]

+            userMetadata.tableMetadataArgs.type = "junction"
+            userMetadata.tableType = "junction"
+            userMetadata.isJunction = true
+            userMetadata.ownerColumns = ownerColumns
+            userMetadata.inverseColumns = inverseColumns
+            userMetadata.foreignKeys.push(...foreignKeysToRegister)
+
Evidence
The PR sets isJunction on the user entity metadata. SubjectExecutor explicitly uses
metadata.isJunction to allow bulk inserts even when it would otherwise be disallowed due to
generated/default columns that need per-row returning; the code comment explains this is only safe
for true junction tables. The added regression test’s junction entity uses
@PrimaryGeneratedColumn(), demonstrating a realistic configuration for a user-defined join table
entity.

src/data-source/DataSource.ts[795-800]
src/persistence/SubjectExecutor.ts[1101-1142]
test/github-issues/11637/issue-11637.test.ts[53-63]

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

## Issue description
Marking a user-defined entity as `isJunction` changes global persistence behavior for that entity. In particular, bulk insert grouping becomes allowed even when the entity has insertion-returning dependent columns (e.g. generated PK), which is exactly what TypeORM tries to avoid for non-junction entities on drivers without multi-row RETURNING.

## Issue Context
Many-to-many join-row subjects do not need generated values back, but users can also call `repository.save([junction1, junction2])` and expect generated ids to be assigned correctly.

## Fix Focus Areas
- src/data-source/DataSource.ts[795-800]
- src/persistence/SubjectExecutor.ts[1115-1136]

## Suggested direction
- Tighten the grouping condition in `groupBulkSubjects` so `subject.metadata.isJunction` only bypasses grouping restrictions when `subject.metadata.getInsertionReturningColumns().length === 0`.
- Alternatively, avoid flipping `userMetadata.isJunction` and instead keep a separate internal junction-only metadata for many-to-many persistence, while leaving the user entity metadata as a regular entity for direct repository operations.

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


2. Issue test added under github-issues 📘 ≡
Description
The fix for #11637 adds a new test only under test/github-issues, which conflicts with the
requirement to keep issue fixes in the functional test suite. This can fragment coverage and make
long-term maintenance harder compared to placing the regression in test/functional.
Code

test/github-issues/11637/issue-11637.test.ts[R65-112]

+describe("github issues > #11637 many-to-many relations broken when user-defined junction entity exists", () => {
+    let dataSources: DataSource[]
+
+    before(
+        async () =>
+            (dataSources = await createTestingConnections({
+                entities: [Specialty, Vet, VetSpecialty],
+                enabledDrivers: ["sqlite"],
+            })),
+    )
+
+    beforeEach(() => reloadTestingDatabases(dataSources))
+
+    after(() => closeTestingConnections(dataSources))
+
+    it("should populate junction table with foreign key values when saving many-to-many relation", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const specialtyRepo = dataSource.getRepository(Specialty)
+                const vetRepo = dataSource.getRepository(Vet)
+                const junctionRepo = dataSource.getRepository(VetSpecialty)
+
+                const dogs = specialtyRepo.create({ name: "dogs" })
+                const cats = specialtyRepo.create({ name: "cats" })
+                await specialtyRepo.save([dogs, cats])
+
+                const vet = vetRepo.create({
+                    name: "Carlos Salazar",
+                    specialties: [dogs, cats],
+                })
+                await vetRepo.save(vet)
+
+                const persistedVet = await vetRepo.findOneOrFail({
+                    where: { id: vet.id },
+                    relations: { specialties: true },
+                })
+
+                expect(persistedVet.specialties).to.have.length(2)
+
+                const junctionRows = await junctionRepo.find()
+                expect(junctionRows).to.have.length(2)
+                junctionRows.forEach((row) => {
+                    expect(row.vetId).to.equal(vet.id)
+                    expect(["dogs", "cats"]).to.include(row.specialtyName)
+                })
+            }),
+        ))
+})
Evidence
Compliance rule 3 requires issue fix tests to live in test/functional (with issue reference
comments when applicable). This PR introduces the #11637 regression test under
test/github-issues/11637/, and the diff does not show a clear reason why it cannot be placed under
test/functional.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/11637/issue-11637.test.ts[65-112]

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 an issue fix (#11637) was added under `test/github-issues/11637/`, but the compliance requirement prefers issue-fix coverage to live in `test/functional`.
## Issue Context
The PR already adds functional coverage elsewhere; this #11637 regression should be incorporated into the functional suite (with an issue reference comment) unless there is a concrete reason it cannot run there.
## Fix Focus Areas
- test/github-issues/11637/issue-11637.test.ts[1-112]

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


3. Inverse side becomes owner 🐞 ≡
Description
deduplicateJunctionEntityMetadatas calls registerJoinColumns for every relation that points at the
original junction metadata (including the inverse many-to-many relation).
RelationMetadata.registerJoinColumns derives ownership from joinColumns.length, so inverse sides can
become owning sides and then many-to-many persistence can swap which entity populates owner vs
inverse FK columns.
Code

src/data-source/DataSource.ts[R829-846]

+            entityMetadatas.forEach((metadata) => {
+                metadata.relations
+                    .filter(
+                        (relation) =>
+                            relation.junctionEntityMetadata ===
+                            junctionMetadata,
+                    )
+                    .forEach((relation) => {
+                        relation.foreignKeys = relation.foreignKeys.filter(
+                            (foreignKey) =>
+                                foreignKey.entityMetadata !== junctionMetadata,
+                        )
+                        relation.registerForeignKeys(...foreignKeysToRegister)
+                        relation.registerJoinColumns(
+                            ownerColumns,
+                            inverseColumns,
+                        )
+                        relation.registerJunctionEntityMetadata(userMetadata)
Evidence
The new dedupe loop updates all relations whose junctionEntityMetadata equals the auto junction
metadata, and it unconditionally calls registerJoinColumns(ownerColumns, inverseColumns). In
RelationMetadata, registerJoinColumns sets isOwning/isManyToManyOwner based on joinColumns being
non-empty. ManyToManySubjectBuilder uses relation.isOwning to decide which side is the owner vs
inverse when building junction row inserts—so flipping isOwning on the inverse side can swap FK
values when saving from that side.

src/data-source/DataSource.ts[822-847]
src/metadata/RelationMetadata.ts[594-609]
src/persistence/subject-builder/ManyToManySubjectBuilder.ts[171-176]
src/metadata/RelationMetadata.ts[264-279]

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

## Issue description
`deduplicateJunctionEntityMetadatas` re-registers join columns on **all** relations that reference the auto-generated junction metadata. Because `registerJoinColumns` recomputes `isOwning` from `joinColumns.length`, this can incorrectly convert the inverse side of a many-to-many into an owning side, which can swap the owner/inverse values used when building junction inserts.
### Issue Context
Many-to-many persistence uses `relation.isOwning` to decide which entity contributes values for `junctionEntityMetadata.ownerColumns` vs `inverseColumns`. If the inverse relation is accidentally made owning, junction rows can be written with swapped FK values when saving from that side.
### Fix Focus Areas
- src/data-source/DataSource.ts[829-847]
- src/metadata/RelationMetadata.ts[594-609]
- src/persistence/subject-builder/ManyToManySubjectBuilder.ts[171-176]

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


View more (1)
4. User junction entity save breaks 🐞 ≡
Description
The code marks the user-defined entity metadata as isJunction. TypeORM’s junction persistence path
assumes every column has a referencedColumn and extracts values via referencedColumn.getEntityValue,
which breaks repository.save() for user-defined junction entities that expose scalar FK columns (and
can throw for non-FK columns like an auto id).
Code

src/data-source/DataSource.ts[R822-827]

+            userMetadata.tableMetadataArgs.type = "junction"
+            userMetadata.tableType = "junction"
+            userMetadata.isJunction = true
+            userMetadata.ownerColumns = ownerColumns
+            userMetadata.inverseColumns = inverseColumns
+            userMetadata.foreignKeys.push(...foreignKeysToRegister)
Evidence
When metadata.isJunction is true, Subject.createValueSetAndPopChangeMap always uses
changeMap.column.referencedColumn!.getEntityValue(value). For a user-defined entity, junction
columns are often scalar numeric/string columns (e.g., vetId: number) and the entity may include
additional columns (e.g., an id PK) that have no referencedColumn at all. This can (a) produce
undefined/NULL values for scalar FK columns and (b) throw when referencedColumn is absent (non-null
assertion). The PR’s new VetSpecialty entity includes such an extra id column.

src/data-source/DataSource.ts[822-827]
src/persistence/Subject.ts[258-261]
test/github-issues/11637/issue-11637.test.ts[53-63]
src/metadata/ColumnMetadata.ts[846-879]

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

## Issue description
Marking the user-defined junction entity as `isJunction` causes `Subject.createValueSetAndPopChangeMap` to assume every column has a `referencedColumn` and to extract values via `referencedColumn.getEntityValue(value)`. This breaks saving the user-defined junction entity directly (scalar FK fields become `undefined`/NULL) and can throw for non-FK columns (e.g. an auto-generated `id`).
### Issue Context
Many-to-many binding uses junction subjects whose values are entity objects/Subjects, so referencedColumn extraction is correct there. But when a user saves the junction entity itself, column values are typically scalars.
### Fix Focus Areas
- src/data-source/DataSource.ts[822-827]
- src/persistence/Subject.ts[258-264]
- test/github-issues/11637/issue-11637.test.ts[53-63]

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



Remediation recommended

5. Clobbers join-column relations 🐞 ≡ ⭐
Description
deduplicateJunctionEntityMetadatas unconditionally overwrites matched user-defined columns’
referencedColumn and relationMetadata based only on databaseName. If the user-defined junction
entity already defines relations on those columns (e.g. ManyToOne back to each side), this can
detach those columns from their original RelationMetadata and break value extraction/persistence for
the junction entity itself.
Code

src/data-source/DataSource.ts[R731-744]

+            const mapColumn = (column: ColumnMetadata): ColumnMetadata => {
+                const match = userMetadata.columns.find(
+                    (candidate) =>
+                        candidate.databaseName === column.databaseName,
+                )
+                if (!match) {
+                    throw new TypeORMError(
+                        `Column "${column.databaseName}" referenced by the join table "${junctionMetadata.tableName}" was not found in the user-defined entity "${userMetadata.name}".`,
+                    )
+                }
+
+                match.referencedColumn = column.referencedColumn
+                match.relationMetadata = column.relationMetadata
+
Evidence
The promotion step mutates the existing ColumnMetadata objects on the user entity by overwriting
relation linkage fields (referencedColumn/relationMetadata). TypeORM’s join-column builder sets
these fields for user-defined relations, and ColumnMetadata/Subject diff logic uses relationMetadata
to read relation-bound column values; overwriting it can change how values are derived from entity
objects for updates/inserts.

src/data-source/DataSource.ts[731-744]
src/metadata-builder/RelationJoinColumnBuilder.ts[266-276]
src/metadata/ColumnMetadata.ts[694-739]
src/persistence/SubjectChangedColumnsComputer.ts[64-87]

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

## Issue description
`DataSource.deduplicateJunctionEntityMetadatas()` overwrites `ColumnMetadata.relationMetadata` and `referencedColumn` on the *user-defined* junction entity columns. If those columns already participate in user-defined relations (e.g. `@ManyToOne`), this mutates/invalidates those relations.

## Issue Context
The goal is to let many-to-many persistence use the correct join columns/foreign keys, without changing how the user-defined junction entity behaves as a normal entity.

## Fix Focus Areas
- src/data-source/DataSource.ts[727-824]
- src/metadata-builder/RelationJoinColumnBuilder.ts[266-276]

## Suggested direction
- In `mapColumn`, only assign `match.referencedColumn` / `match.relationMetadata` when they are currently unset, OR
- Prefer cloning ColumnMetadata for `ownerColumns`/`inverseColumns` used by the many-to-many relation, leaving the user entity’s original ColumnMetadata objects intact (so its own relations remain valid).

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


6. Junction indexes dropped 🐞 ➹
Description
The deduplication removes the auto-generated junction EntityMetadata (which includes default indexes
on FK columns) but does not migrate those indexes to the promoted user metadata. This can change
schema synchronization output and lose expected join-table indexing (performance/schema-drift risk).
Code

src/data-source/DataSource.ts[R822-827]

+            userMetadata.tableMetadataArgs.type = "junction"
+            userMetadata.tableType = "junction"
+            userMetadata.isJunction = true
+            userMetadata.ownerColumns = ownerColumns
+            userMetadata.inverseColumns = inverseColumns
+            userMetadata.foreignKeys.push(...foreignKeysToRegister)
Evidence
JunctionEntityMetadataBuilder always creates two IndexMetadata entries (one per FK side) on the
auto-generated junction metadata. The dedupe promotes only ownerColumns/inverseColumns/foreignKeys
to the user metadata and then removes the auto junction metadata from the pool, so unless the user
explicitly defined equivalent indexes, schema sync will no longer see the defaults TypeORM would
have generated.

src/data-source/DataSource.ts[822-827]
src/metadata-builder/JunctionEntityMetadataBuilder.ts[267-286]

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

## Issue description
Auto-generated junction metadata carries default FK indexes (`ownIndices`). When the auto junction metadata is removed, these indexes are lost unless the user entity defined them explicitly.
### Issue Context
This is primarily a schema-sync / performance regression risk. Runtime many-to-many binding relies on `ownerColumns` / `inverseColumns`, not `ownIndices`.
### Fix Focus Areas
- src/data-source/DataSource.ts[822-851]
- src/metadata-builder/JunctionEntityMetadataBuilder.ts[267-286]

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


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Grey Divider

Previous review results

Review updated until commit 9c49af8

Results up to commit N/A


🐞 Bugs (3)  
📘 Rule violations (1)  
📎 Requirement gaps (0)  
🎨 UX Issues (0)

🐞\ ≡ Correctness (2) ➹ Performance (1)
📘\ ≡ Correctness (1)

Grey Divider


Action required

1. Issue test added under github-issues 📘 ≡
Description
The fix for #11637 adds a new test only under test/github-issues, which conflicts with the
requirement to keep issue fixes in the functional test suite. This can fragment coverage and make
long-term maintenance harder compared to placing the regression in test/functional.
Code

test/github-issues/11637/issue-11637.test.ts[R65-112]

+describe("github issues > #11637 many-to-many relations broken when user-defined junction entity exists", () => {
+    let dataSources: DataSource[]
+
+    before(
+        async () =>
+            (dataSources = await createTestingConnections({
+                entities: [Specialty, Vet, VetSpecialty],
+                enabledDrivers: ["sqlite"],
+            })),
+    )
+
+    beforeEach(() => reloadTestingDatabases(dataSources))
+
+    after(() => closeTestingConnections(dataSources))
+
+    it("should populate junction table with foreign key values when saving many-to-many relation", () =>
+        Promise.all(
+            dataSources.map(async (dataSource) => {
+                const specialtyRepo = dataSource.getRepository(Specialty)
+                const vetRepo = dataSource.getRepository(Vet)
+                const junctionRepo = dataSource.getRepository(VetSpecialty)
+
+                const dogs = specialtyRepo.create({ name: "dogs" })
+                const cats = specialtyRepo.create({ name: "cats" })
+                await specialtyRepo.save([dogs, cats])
+
+                const vet = vetRepo.create({
+                    name: "Carlos Salazar",
+                    specialties: [dogs, cats],
+                })
+                await vetRepo.save(vet)
+
+                const persistedVet = await vetRepo.findOneOrFail({
+                    where: { id: vet.id },
+                    relations: { specialties: true },
+                })
+
+                expect(persistedVet.specialties).to.have.length(2)
+
+                const junctionRows = await junctionRepo.find()
+                expect(junctionRows).to.have.length(2)
+                junctionRows.forEach((row) => {
+                    expect(row.vetId).to.equal(vet.id)
+                    expect(["dogs", "cats"]).to.include(row.specialtyName)
+                })
+            }),
+        ))
+})
Evidence
Compliance rule 3 requires issue fix tests to live in test/functional (with issue reference
comments when applicable). This PR introduces the #11637 regression test under
test/github-issues/11637/, and the diff does not show a clear reason why it cannot be placed under
test/functional.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/11637/issue-11637.test.ts[65-112]

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 an issue fix (#11637) was added under `test/github-issues/11637/`, but the compliance requirement prefers issue-fix coverage to live in `test/functional`.
## Issue Context
The PR already adds functional coverage elsewhere; this #11637 regression should be incorporated into the functional suite (with an issue reference comment) unless there is a concrete reason it cannot run there.
## Fix Focus Areas
- test/github-issues/11637/issue-11637.test.ts[1-112]

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


2. Inverse side becomes owner 🐞 ≡
Description
deduplicateJunctionEntityMetadatas calls registerJoinColumns for every relation that points at the
original junction metadata (including the inverse many-to-many relation).
RelationMetadata.registerJoinColumns derives ownership from joinColumns.length, so inverse sides can
become owning sides and then many-to-many persistence can swap which entity populates owner vs
inverse FK columns.
Code

src/data-source/DataSource.ts[R829-846]

+            entityMetadatas.forEach((metadata) => {
+                metadata.relations
+                    .filter(
+                        (relation) =>
+                            relation.junctionEntityMetadata ===
+                            junctionMetadata,
+                    )
+                    .forEach((relation) => {
+                        relation.foreignKeys = relation.foreignKeys.filter(
+                            (foreignKey) =>
+                                foreignKey.entityMetadata !== junctionMetadata,
+                        )
+                        relation.registerForeignKeys(...foreignKeysToRegister)
+                        relation.registerJoinColumns(
+                            ownerColumns,
+                            inverseColumns,
+                        )
+                        relation.registerJunctionEntityMetadata(userMetadata)
Evidence
The new dedupe loop updates all relations whose junctionEntityMetadata equals the auto junction
metadata, and it unconditionally calls registerJoinColumns(ownerColumns, inverseColumns). In
RelationMetadata, registerJoinColumns sets isOwning/isManyToManyOwner based on joinColumns being
non-empty. ManyToManySubjectBuilder uses relation.isOwning to decide which side is the owner vs
inverse when building junction row inserts—so flipping isOwning on the inverse side can swap FK
values when saving from that side.

src/data-source/DataSource.ts[822-847]
src/metadata/RelationMetadata.ts[594-609]
src/persistence/subject-builder/ManyToManySubjectBuilder.ts[171-176]
src/metadata/RelationMetadata.ts[264-279]

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

## Issue description
`deduplicateJunctionEntityMetadatas` re-registers join columns on **all** relations that reference the auto-generated junction metadata. Because `registerJoinColumns` recomputes `isOwning` from `joinColumns.length`, this can incorrectly convert the inverse side of a many-to-many into an owning side, which can swap the owner/inverse values used when building junction inserts.
### Issue Context
Many-to-many persistence uses `relation.isOwning` to decide which entity contributes values for `junctionEntityMetadata.ownerColumns` vs `inverseColumns`. If the inverse relation is accidentally made owning, junction rows can be written with swapped FK values when saving from that side.
### Fix Focus Areas
- src/data-source/DataSource.ts[829-847]
- src/metadata/RelationMetadata.ts[594-609]
- src/persistence/subject-builder/ManyToManySubjectBuilder.ts[171-176]

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


3. User junction entity save breaks 🐞 ≡
Description
The code marks the user-defined entity metadata as isJunction. TypeORM’s junction persistence path
assumes every column has a referencedColumn and extracts values via referencedColumn.getEntityValue,
which breaks repository.save() for user-defined junction entities that expose scalar FK columns (and
can throw for non-FK columns like an auto id).
Code

src/data-source/DataSource.ts[R822-827]

+            userMetadata.tableMetadataArgs.type = "junction"
+            userMetadata.tableType = "junction"
+            userMetadata.isJunction = true
+            userMetadata.ownerColumns = ownerColumns
+            userMetadata.inverseColumns = inverseColumns
+            userMetadata.foreignKeys.push(...foreignKeysToRegister)
Evidence
When metadata.isJunction is true, Subject.createValueSetAndPopChangeMap always uses
changeMap.column.referencedColumn!.getEntityValue(value). For a user-defined entity, junction
columns are often scalar numeric/string columns (e.g., vetId: number) and the entity may include
additional columns (e.g., an id PK) that have no referencedColumn at all. This can (a) produce
undefined/NULL values for scalar FK columns and (b) throw when referencedColumn is absent (non-null
assertion). The PR’s new VetSpecialty entity includes such an extra id column.

src/data-source/DataSource.ts[822-827]
src/persistence/Subject.ts[258-261]
test/github-issues/11637/issue-11637.test.ts[53-63]
src/metadata/ColumnMetadata.ts[846-879]

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

## Issue description
Marking the user-defined junction entity as `isJunction` causes `Subject.createValueSetAndPopChangeMap` to assume every column has a `referencedColumn` and to extract values via `referencedColumn.getEntityValue(value)`. This breaks saving the user-defined junction entity directly (scalar FK fields become `undefined`/NULL) and can throw for non-FK columns (e.g. an auto-generated `id`).
### Issue Context
Many-to-many binding uses junction subjects whose values are entity objects/Subjects, so referencedColumn extraction is correct there. But when a user saves the junction entity itself, column values are typically scalars.
### Fix Focus Areas
- src/data-source/DataSource.ts[822-827]
- src/persistence/Subject.ts[258-264]
- test/github-issues/11637/issue-11637.test.ts[53-63]

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



Remediation recommended

4. Junction indexes dropped 🐞 ➹
Description
The deduplication removes the auto-generated junction EntityMetadata (which includes default indexes
on FK columns) but does not migrate those indexes to the promoted user metadata. This can change
schema synchronization output and lose expected join-table indexing (performance/schema-drift risk).
Code

src/data-source/DataSource.ts[R822-827]

+            userMetadata.tableMetadataArgs.type = "junction"
+            userMetadata.tableType = "junction"
+            userMetadata.isJunction = true
+            userMetadata.ownerColumns = ownerColumns
+            userMetadata.inverseColumns = inverseColumns
+            userMetadata.foreignKeys.push(...foreignKeysToRegister)
Evidence
JunctionEntityMetadataBuilder always creates two IndexMetadata entries (one per FK side) on the
auto-generated junction metadata. The dedupe promotes only ownerColumns/inverseColumns/foreignKeys
to the user metadata and then removes the auto junction metadata from the pool, so unless the user
explicitly defined equivalent indexes, schema sync will no longer see the defaults TypeORM would
have generated.

src/data-source/DataSource.ts[822-827]
src/metadata-builder/JunctionEntityMetadataBuilder.ts[267-286]

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

## Issue description
Auto-generated junction metadata carries default FK indexes (`ownIndices`). When the auto junction metadata is removed, these indexes are lost unless the user entity defined them explicitly.
### Issue Context
This is primarily a schema-sync / performance regression risk. Runtime many-to-many binding relies on `ownerColumns` / `inverseColumns`, not `ownIndices`.
### Fix Focus Areas
- src/data-source/DataSource.ts[822-851]
- src/metadata-builder/JunctionEntityMetadataBuilder.ts[267-286]

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


Grey Divider

Grey Divider

Qodo Logo

# Conflicts:
#	src/data-source/DataSource.ts
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
D Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

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

Copy link
Copy Markdown

Persistent review updated to latest commit 9c49af8

@pkuczynski pkuczynski changed the title fix: prefers user defined junction metadata over auto generated for many to many and added regression tests fix: prefer user-defined junction metadata over auto-generated Apr 11, 2026
@pkuczynski pkuczynski added comp: relations regression worked in previous version and doesn't work in current and removed Marked For Double Check labels Apr 13, 2026
@michaelbromley

Copy link
Copy Markdown
Member

This repository was recently restructured into a pnpm workspace, and the typeorm package moved from the repo root into packages/typeorm (PR #12854). Everything moved as a pure rename with no content changes, so your branch should replay across the move cleanly once git's rename detection limit is raised:

git fetch origin
git -c merge.renameLimit=999999 -c diff.renameLimit=999999 rebase origin/master

If your branch has diverged enough that a full rebase isn't worth it, scripts/migrate-pr-to-packages-layout.sh --replay (run on top of master) rewrites the paths of your net diff instead. Both approaches, plus a path-mapping table and a prompt you can hand to a coding agent, are documented in scripts/migrate-pr-to-packages-layout.md.

Sorry for the disruption, and thanks for your patience.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp: relations regression worked in previous version and doesn't work in current

Development

Successfully merging this pull request may close these issues.

Many-to-many relationships broken when user-defined junction entity exists (0.3.26 regression)

6 participants