Skip to content

fix(query-builder): map orIgnore/orUpdate returning rows to entities by key - #13001

Open
ElwinErnst wants to merge 3 commits into
typeorm:masterfrom
ElwinErnst:fix/insert-or-ignore-row-mapping
Open

ElwinErnst wants to merge 3 commits into
typeorm:masterfrom
ElwinErnst:fix/insert-or-ignore-row-mapping

Conversation

@ElwinErnst

Copy link
Copy Markdown

Description of change

insert().orIgnore() (and orUpdate() paths that skip a row) wrote the RETURNING rows onto the wrong entities.

Current behavior

ReturningResultsEntityUpdator.insert matched returned rows to entities by array position (insertResult.raw[entityIndex]). With ON CONFLICT ... DO NOTHING, a skipped row returns no RETURNING row, so every row after the skipped one shifts up onto the previous entity:

  • a skipped entity receives the next inserted row's id (and create/update dates, defaults, and any .returning() columns);
  • the inserted entity loses its generated values;
  • with user-provided ids, two entities can even end up sharing one id.

This silently breaks the common "insert, ignore duplicates, then act on what was inserted" pattern. Same underlying bug as #5226.

New behavior

Returned rows are matched to the entities that produced them by the columns that identify the conflicting row (primary + unique columns) instead of by position:

  • EntityMetadata.getUpsertConflictIdentificationColumns() returns the primary and unique-constraint/unique-index columns;
  • for on-conflict-do-update drivers those columns are added to RETURNING when orIgnore/orUpdate is used;
  • the updator walks entities and returned rows in order (inserted rows come back in entity order, skipped ones absent) and assigns a row only when its identifying values equal the entity's, leaving skipped entities untouched.

When no row is skipped, the previous positional mapping is kept unchanged.

How it was verified

Reproduced the issue on PostgreSQL, then confirmed the fix across skip-first, skip-middle, skip-last, multi-skip and no-skip cases. New regression tests in test/github-issues/12994/ run on postgres, cockroachdb and better-sqlite3. Existing on-conflict and a broad set of insert/persistence tests pass unchanged on PostgreSQL.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md) — N/A (bug fix, no public API change)

Fixes #12994

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

qodo-free-for-open-source-projects Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (1) 📎 Requirement gaps (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Inserted rows can be assigned to skipped entities 🐞 Bug ≡ Correctness
Description
entityMatchesReturnedRow ignores an undefined component of a composite key and accepts a match on
just one other component. If an earlier entity is skipped by a separate defaulted unique key, a
later inserted entity can share the populated component but have a different value for the omitted
one, causing its returned ID to be merged into the skipped entity.
Code

packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[R375-377]

+            const entityValue = column.getEntityValue(entity)
+            if (entityValue === undefined) continue
+            if (!(column.databaseName in row)) continue
Evidence
The insert builder emits NULL for an omitted column without a default, but the matcher skips
comparing that column and accepts any positive partial comparison. The mapping loop immediately
consumes the row after that match, and the generated-map path uses the consumed row for the entity.

packages/typeorm/src/query-builder/InsertQueryBuilder.ts[1350-1370]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[340-359]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[373-387]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[202-229]

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 matcher treats an omitted component of a composite unique key as irrelevant, although the insert supplies NULL or a database default. A partial match can consume a later row for a skipped entity.
## Fix Focus Areas
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[368-388]
- packages/typeorm/src/query-builder/InsertQueryBuilder.ts[1350-1370]
## Recommended Fix
Match against the effective inserted values for a complete identifying key, rather than accepting equality on any subset of columns. If a complete key cannot be established, do not consume a returned row based on that partial match; add a regression with a defaulted conflict key and a composite key.

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


2. Issue regression uses wrong test suite ⊘ Outdated
Description
The new regression coverage is placed in test/github-issues/12994/issue-12994.test.ts instead of
the functional test suite. Because this is the only added test location for the fix, the changed
insert behavior remains outside the repository's required functional-test organization.

3. Inserted entities can lose generated IDs ⊘ Outdated
Description
entityMatchesReturnedRow compares the entity's untransformed unique value with the raw database
value, so a column transformer can make every comparison fail. When an earlier row is ignored, a
later successful insert with a transformed unique value is mapped to -1 and its returned generated
ID is not merged.

View action required (3)
4. Conflict inserts overwrite transformed values ⊘ Outdated
Description
InsertQueryBuilder now returns every unique column, and PostgreSQL's createGeneratedMap copies
each returned field into the entity without hydrating transformed values. Even when no row is
skipped, an orIgnore insert of an entity with a transformed unique column replaces its
entity-domain value with the stored representation.

5. Explicit projections lose returned values ⊘ Outdated
Description
InsertQueryBuilder places identification columns in extraReturningColumns, but
createReturningExpression omits those extras when .returning() receives a string. If a conflict
shortens a batch using .returning("id") and the input IDs are generated, the matcher sees no
comparable identification value and discards the returned rows.

6. Partial keys can assign IDs to skipped rows ⊘ Outdated
Description
getUpsertConflictIdentificationColumns includes unique-index columns without retaining the index
predicate, so the matcher treats a partial key as identifying every row. When a first input is
ignored under a partial index and a later input with the same key falls outside its predicate and
inserts successfully, the later returned row can be consumed for the skipped input.


Remediation recommended

7. Unmanaged unique indexes leave rows unmapped 🐞 Bug ≡ Correctness
Description
getUpsertConflictIdentificationColumns reads index.columns, but IndexMetadata.build leaves
that array empty for indexes declared with synchronize: false. When such an index causes an
earlier input to be ignored and the primary IDs are generated, the mapper cannot compare the later
returned row with its input entity, so that entity loses its generated values.
Code

packages/typeorm/src/metadata/EntityMetadata.ts[R1174-1177]

+        for (const index of this.indices) {
+            if (index.isUnique)
+                for (const column of index.columns) columns.add(column)
+        }
Evidence
The index constructor records uniqueness and configured column names, but its build method returns
before populating columns when synchronization is disabled. The new helper collects only that
empty array; the query builder therefore cannot return the conflict key, while the mapper requires a
comparable identifier to assign a shortened result.

packages/typeorm/src/metadata/IndexMetadata.ts[89-102]
packages/typeorm/src/metadata/IndexMetadata.ts[150-180]
packages/typeorm/src/metadata/IndexMetadata.ts[240-265]
packages/typeorm/src/metadata/EntityMetadata.ts[1172-1181]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[318-359]

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

## Issue description
Unique indexes declared with `synchronize: false` retain their configured column names but have no resolved `index.columns`. The new identifier collection therefore omits a real conflict key.
## Fix Focus Areas
- packages/typeorm/src/metadata/EntityMetadata.ts[1172-1181]
- packages/typeorm/src/metadata/IndexMetadata.ts[167-223]
## Recommended Fix
Resolve the configured property paths for non-synchronized unique indexes when collecting conflict identifiers, without changing whether TypeORM manages those indexes. Cover a skipped insert against a manually managed unique index with generated primary IDs.

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


8. Ignored rows receive another row's ID ✓ Resolved
Description
entityMatchesReturnedRow treats the string "null" and SQL NULL as equal because it falls back
to comparing their string representations. If an existing "null" key causes the first entity to be
ignored and a later entity with a nullable NULL key is inserted, the matcher consumes that later
row for the ignored entity and merges its generated ID into the wrong entity.

9. Defaulted keys leave inserted rows unmapped ⊘ Outdated
Description
entityMatchesReturnedRow skips identification columns whose input value is undefined and
requires at least one comparison to accept a row. If a batch includes a skipped row and a successful
row whose unique key and primary key are both database-generated, the successful row has no
input-side key to compare and loses its returned generated values.

View review recommended (2)
10. Conflict updates can leave entities stale ⊘ Outdated
Description
entityMatchesReturnedRow rejects a returned row when any input primary or unique value differs,
although orUpdate can leave identifying columns outside its overwrite list at their existing
database values. If another batch row is skipped and a conflict update changes only selected
columns, the updated row can fail matching and its returned values are not merged into the input
entity.

11. Insert results can expose unique secrets ⊘ Outdated
Description
InsertQueryBuilder adds every unique column to extraReturningColumns, which is appended to an
array-form .returning() projection and retained in InsertResult.raw. For a conflict insert whose
caller requests only an ID, returning the raw result to an API consumer now also exposes any unique
secret or token column on the entity, even when no row was skipped.


Informational

12. The mapper adds excessive comments 📘 Rule violation ⚙ Maintainability
Description
The new mapping methods include long comments and docstrings that restate the implementation flow
and defensive fallback behavior. The added prose spans multiple blocks around row matching and makes
the production code harder to scan without changing its runtime behavior.
Code

packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[R305-311]

+    /**
+     * Maps RETURNING rows back to the entities that produced them when a
+     * conflict clause (orIgnore / orUpdate) may have skipped some rows, which
+     * makes positional mapping wrong. Returns an array where index i holds the
+     * index into insertResult.raw for entity i, or -1 when the entity has no
+     * matching returned row (its row was skipped). Returns undefined when
+     * positional mapping is correct and should be used as before.
Evidence
The diff adds multiple lengthy explanatory comment blocks around the new mapper, including a
detailed method docstring and a multi-line fallback rationale, matching the checklist's prohibition
on extra AI-like comments and style-inconsistent noise.

Rule 4: Remove AI-generated noise
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[305-311]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[359-369]

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

The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
Issue description
The new row-mapping implementation adds lengthy comments and docstrings that repeat the code's control flow and fallback behavior, introducing avoidable maintenance noise.
Fix Focus Areas
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[305-311]
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[359-369]
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[374-385]
Recommended Fix
Replace the long explanatory blocks with concise comments that describe only the non-obvious invariant: returned rows are consumed in entity order and skipped entities remain unmapped. Remove comments that restate straightforward conditions or implementation details.

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

Grey Divider

Context sources
✅ Context preparation
  Commit messages: summarized; full text retained for this review
Review mode: Auto: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 11/18, lines 446/200; both must reach the floor). Router rationale: Complex cross-cutting mapping logic has multiple plausible independent correctness defects.

Grey Divider

Tip of the day
💡 Did you know, you can start a comment with 'qodo' or '@qodo' to chat about any finding

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Previous reviews

Review updated until commit a761dd4 ⚖️ Balanced

Results up to commit 0851c3f


🐞 Bugs (3) 📘 Rule violations (1) 📎 Requirement gaps (0) 📜 Skill insights (0)


Action required
1. Inserted rows can be assigned to skipped entities 🐞 Bug ≡ Correctness
Description
entityMatchesReturnedRow ignores an undefined component of a composite key and accepts a match on
just one other component. If an earlier entity is skipped by a separate defaulted unique key, a
later inserted entity can share the populated component but have a different value for the omitted
one, causing its returned ID to be merged into the skipped entity.
Code

packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[R375-377]

+            const entityValue = column.getEntityValue(entity)
+            if (entityValue === undefined) continue
+            if (!(column.databaseName in row)) continue
Evidence
The insert builder emits NULL for an omitted column without a default, but the matcher skips
comparing that column and accepts any positive partial comparison. The mapping loop immediately
consumes the row after that match, and the generated-map path uses the consumed row for the entity.

packages/typeorm/src/query-builder/InsertQueryBuilder.ts[1350-1370]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[340-359]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[373-387]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[202-229]

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 matcher treats an omitted component of a composite unique key as irrelevant, although the insert supplies NULL or a database default. A partial match can consume a later row for a skipped entity.
## Fix Focus Areas
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[368-388]
- packages/typeorm/src/query-builder/InsertQueryBuilder.ts[1350-1370]
## Recommended Fix
Match against the effective inserted values for a complete identifying key, rather than accepting equality on any subset of columns. If a complete key cannot be established, do not consume a returned row based on that partial match; add a regression with a defaulted conflict key and a composite key.

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


2. Issue regression uses wrong test suite ⊘ Outdated
Description
The new regression coverage is placed in test/github-issues/12994/issue-12994.test.ts instead of
the functional test suite. Because this is the only added test location for the fix, the changed
insert behavior remains outside the repository's required functional-test organization.
Code

test/github-issues/12994/issue-12994.test.ts[R12-20]

+describe("github issues > #12994 insert().orIgnore() writes returned rows onto the wrong entities when a row is skipped", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [Tag],
+            // drivers that emit "ON CONFLICT ... DO NOTHING" and read generated
+            // values back through RETURNING
+            enabledDrivers: ["postgres", "cockroachdb", "better-sqlite3"],
Evidence
The checklist requires issue fixes to add or update tests under packages/typeorm/test/functional
and identifies issue-only tests without a clear reason as a failure. The PR adds its regression test
only under test/github-issues/12994/, with no corresponding functional-suite test.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/12994/issue-12994.test.ts[12-20]

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 adds all regression coverage under `test/github-issues/12994/`, but issue fixes are required to add or update tests under `test/functional`.
## Fix Focus Areas
- test/github-issues/12994/issue-12994.test.ts[12-20]
## Recommended Fix
Move or duplicate the regression scenarios into the appropriate `test/functional` insert/query-builder test suite, preserving the issue reference in the test comment or description where applicable.

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


3. Inserted entities can lose generated IDs ⊘ Outdated
Description
entityMatchesReturnedRow compares the entity's untransformed unique value with the raw database
value, so a column transformer can make every comparison fail. When an earlier row is ignored, a
later successful insert with a transformed unique value is mapped to -1 and its returned generated
ID is not merged.
Code

src/query-builder/ReturningResultsEntityUpdator.ts[R381-385]

+            if (
+                entityValue !== rowValue &&
+                String(entityValue) !== String(rowValue)
+            )
+                return false
Evidence
Insert values pass through the driver's persistence preparation, which applies column transformers,
while PostgreSQL returns raw fields and the new matcher compares them with untransformed entity
values. An existing transformer demonstrates a concrete plaintext-to-base64 mismatch; an unmatched
row supplies no generated map.

src/query-builder/InsertQueryBuilder.ts[1553-1564]
src/driver/postgres/PostgresDriver.ts[756-763]
test/functional/columns/value-transformer/entity/User.ts[14-19]
src/query-builder/ReturningResultsEntityUpdator.ts[340-359]
src/query-builder/ReturningResultsEntityUpdator.ts[202-218]

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 matcher compares entity-domain values with raw database-domain values, so transformed unique keys cannot identify their returned rows.
## Fix Focus Areas
- src/query-builder/ReturningResultsEntityUpdator.ts[373-387]
- src/query-builder/InsertQueryBuilder.ts[1553-1564]
## Recommended Fix
Compare values in the same representation, using the driver's persistence preparation for entity values and appropriate handling for driver-returned values. Add an ignored-row regression test with a transformed unique key.

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


View action required (3)
4. Conflict inserts overwrite transformed values ⊘ Outdated
Description
InsertQueryBuilder now returns every unique column, and PostgreSQL's createGeneratedMap copies
each returned field into the entity without hydrating transformed values. Even when no row is
skipped, an orIgnore insert of an entity with a transformed unique column replaces its
entity-domain value with the stored representation.
Code

src/query-builder/InsertQueryBuilder.ts[R152-155]

+                    this.expressionMap.extraReturningColumns = [
+                        ...this.expressionMap.extraReturningColumns,
+                        ...this.expressionMap
+                            .mainAlias!.metadata.getUpsertConflictIdentificationColumns()
Evidence
The new columns are appended to RETURNING; PostgreSQL builds its generated map from every returned
field without hydration, and the updator merges that map into the input entity. The repository's
base64 transformer provides an example where stored and entity values differ.

src/query-builder/QueryBuilder.ts[938-959]
src/driver/postgres/PostgresDriver.ts[1456-1471]
src/query-builder/ReturningResultsEntityUpdator.ts[210-225]
test/functional/columns/value-transformer/entity/User.ts[14-19]

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

## Issue description
Conflict-identification columns added to RETURNING are also treated as generated values, overwriting transformed entity properties with raw database values.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[152-163]
- src/query-builder/ReturningResultsEntityUpdator.ts[202-225]
## Recommended Fix
Use identification fields for matching without merging them as generated fields unless they were independently needed for entity updating. Test an unskipped conflict insert with a transformed unique column.

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


5. Explicit projections lose returned values ⊘ Outdated
Description
InsertQueryBuilder places identification columns in extraReturningColumns, but
createReturningExpression omits those extras when .returning() receives a string. If a conflict
shortens a batch using .returning("id") and the input IDs are generated, the matcher sees no
comparable identification value and discards the returned rows.
Code

src/query-builder/InsertQueryBuilder.ts[R152-155]

+                    this.expressionMap.extraReturningColumns = [
+                        ...this.expressionMap.extraReturningColumns,
+                        ...this.expressionMap
+                            .mainAlias!.metadata.getUpsertConflictIdentificationColumns()
Evidence
The returning-expression builder excludes extra columns for string expressions and emits the string
unchanged. The new matcher requires a defined entity value for a field present in the returned row,
then treats unmatched entities as having no returned result.

src/query-builder/QueryBuilder.ts[938-959]
src/query-builder/QueryBuilder.ts[1000-1005]
src/query-builder/ReturningResultsEntityUpdator.ts[318-359]
src/query-builder/ReturningResultsEntityUpdator.ts[373-387]

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

## Issue description
String returning expressions omit the identification columns required by the new short-result mapper.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[144-163]
- src/query-builder/QueryBuilder.ts[938-1005]
- src/query-builder/ReturningResultsEntityUpdator.ts[318-330]
## Recommended Fix
Ensure conflict-row correlation fields are present when a string returning expression is used, or provide a safe mapping path that does not classify unidentifiable successful rows as skipped. Cover a skipped batch with `.returning("id")`.

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


6. Partial keys can assign IDs to skipped rows ⊘ Outdated
Description
getUpsertConflictIdentificationColumns includes unique-index columns without retaining the index
predicate, so the matcher treats a partial key as identifying every row. When a first input is
ignored under a partial index and a later input with the same key falls outside its predicate and
inserts successfully, the later returned row can be consumed for the skipped input.
Code

src/metadata/EntityMetadata.ts[R1180-1182]

+        for (const index of this.indices) {
+            if (index.isUnique)
+                for (const column of index.columns) columns.add(column)
Evidence
Index metadata stores an optional filtering predicate, but the new method retains only its columns.
The ordered mapper consumes the next returned row as soon as those compared columns match, even if
the inputs differ in whether the index applies.

src/metadata/IndexMetadata.ts[35-55]
src/metadata/EntityMetadata.ts[1178-1187]
src/query-builder/ReturningResultsEntityUpdator.ts[340-359]
src/query-builder/ReturningResultsEntityUpdator.ts[373-387]

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 unique index's columns are not globally unique when the index has a predicate, so matching only their values can give a skipped entity another row's generated values.
## Fix Focus Areas
- src/metadata/EntityMetadata.ts[1178-1187]
- src/query-builder/ReturningResultsEntityUpdator.ts[332-387]
## Recommended Fix
Preserve the relevant index predicate and full key semantics during correlation; do not treat partial-index columns alone as globally identifying. Add a batch test with equal key values on opposite sides of a partial-index predicate.

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



Remediation recommended
7. Unmanaged unique indexes leave rows unmapped 🐞 Bug ≡ Correctness
Description
getUpsertConflictIdentificationColumns reads index.columns, but IndexMetadata.build leaves
that array empty for indexes declared with synchronize: false. When such an index causes an
earlier input to be ignored and the primary IDs are generated, the mapper cannot compare the later
returned row with its input entity, so that entity loses its generated values.
Code

packages/typeorm/src/metadata/EntityMetadata.ts[R1174-1177]

+        for (const index of this.indices) {
+            if (index.isUnique)
+                for (const column of index.columns) columns.add(column)
+        }
Evidence
The index constructor records uniqueness and configured column names, but its build method returns
before populating columns when synchronization is disabled. The new helper collects only that
empty array; the query builder therefore cannot return the conflict key, while the mapper requires a
comparable identifier to assign a shortened result.

packages/typeorm/src/metadata/IndexMetadata.ts[89-102]
packages/typeorm/src/metadata/IndexMetadata.ts[150-180]
packages/typeorm/src/metadata/IndexMetadata.ts[240-265]
packages/typeorm/src/metadata/EntityMetadata.ts[1172-1181]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[318-359]

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

## Issue description
Unique indexes declared with `synchronize: false` retain their configured column names but have no resolved `index.columns`. The new identifier collection therefore omits a real conflict key.
## Fix Focus Areas
- packages/typeorm/src/metadata/EntityMetadata.ts[1172-1181]
- packages/typeorm/src/metadata/IndexMetadata.ts[167-223]
## Recommended Fix
Resolve the configured property paths for non-synchronized unique indexes when collecting conflict identifiers, without changing whether TypeORM manages those indexes. Cover a skipped insert against a manually managed unique index with generated primary IDs.

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


8. Ignored rows receive another row's ID 🐞 Bug ≡ Correctness
Description
entityMatchesReturnedRow treats the string "null" and SQL NULL as equal because it falls back
to comparing their string representations. If an existing "null" key causes the first entity to be
ignored and a later entity with a nullable NULL key is inserted, the matcher consumes that later
row for the ignored entity and merges its generated ID into the wrong entity.
Code

packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[R381-385]

+            if (
+                entityValue !== rowValue &&
+                String(entityValue) !== String(rowValue)
+            )
+                return false
Evidence
The new matcher accepts either strict equality or equality after String() conversion, for which
String(null) and String("null") are identical. The new mapping loop consumes the first returned
row on that match, and the insert updator merges the selected row's generated map into the matched
entity.

packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[373-387]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[340-359]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[199-218]

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 conflict-row matcher equates a string key of `"null"` with an actual null key, allowing an ignored entity to consume another entity's returned row.
## Fix Focus Areas
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[379-387]
## Recommended Fix
Use type-aware comparison for identifying values. In particular, reject null-versus-non-null comparisons before any string conversion, and add a regression test with an ignored `"null"` key followed by an inserted nullable `NULL` key.

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


9. Defaulted keys leave inserted rows unmapped ⊘ Outdated
Description
entityMatchesReturnedRow skips identification columns whose input value is undefined and
requires at least one comparison to accept a row. If a batch includes a skipped row and a successful
row whose unique key and primary key are both database-generated, the successful row has no
input-side key to compare and loses its returned generated values.
Code

src/query-builder/ReturningResultsEntityUpdator.ts[R375-377]

+            const entityValue = column.getEntityValue(entity)
+            if (entityValue === undefined) continue
+            if (!(column.databaseName in row)) continue
Evidence
Database-default columns are expected in insertion results, but the mapper advances only after a
positive comparison with an input value. A -1 mapping passes no row to the generated-map builder,
and identifiers are subsequently read from the unpopulated entity.

src/metadata/EntityMetadata.ts[1149-1161]
src/query-builder/ReturningResultsEntityUpdator.ts[340-359]
src/query-builder/ReturningResultsEntityUpdator.ts[202-218]
src/query-builder/ReturningResultsEntityUpdator.ts[297-302]

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

## Issue description
Rows whose identifying values are supplied by database defaults cannot pass the new matcher after a conflict shortens the result.
## Fix Focus Areas
- src/query-builder/ReturningResultsEntityUpdator.ts[332-359]
- src/query-builder/ReturningResultsEntityUpdator.ts[373-387]
## Recommended Fix
Establish a reliable correlation value before insertion for rows without entity-side identifiers, or avoid silently classifying their returned rows as skipped. Test a skipped batch followed by an insert using a database-generated unique default.

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


View review recommended (2)
10. Conflict updates can leave entities stale ⊘ Outdated
Description
entityMatchesReturnedRow rejects a returned row when any input primary or unique value differs,
although orUpdate can leave identifying columns outside its overwrite list at their existing
database values. If another batch row is skipped and a conflict update changes only selected
columns, the updated row can fail matching and its returned values are not merged into the input
entity.
Code

src/query-builder/ReturningResultsEntityUpdator.ts[R379-385]

+            comparedColumns++
+            const rowValue = row[column.databaseName]
+            if (
+                entityValue !== rowValue &&
+                String(entityValue) !== String(rowValue)
+            )
+                return false
Evidence
The SQL builder updates only specified overwrite columns, while the new metadata method supplies all
primary and unique columns to a matcher that rejects any difference. The rejection leaves the
generated map empty for that entity.

src/query-builder/InsertQueryBuilder.ts[558-610]
src/metadata/EntityMetadata.ts[1178-1187]
src/query-builder/ReturningResultsEntityUpdator.ts[340-359]
src/query-builder/ReturningResultsEntityUpdator.ts[202-225]

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

## Issue description
An upsert's returned row may retain existing values for unique columns that were not overwritten, making comparison against every proposed input value fail.
## Fix Focus Areas
- src/query-builder/ReturningResultsEntityUpdator.ts[368-387]
- src/query-builder/InsertQueryBuilder.ts[558-610]
## Recommended Fix
Use the conflict target and columns that remain stable across the update for correlation rather than requiring all primary and unique input fields to equal the updated row. Test a shortened batch with an update that leaves another unique column unchanged.

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


11. Insert results can expose unique secrets ⊘ Outdated
Description
InsertQueryBuilder adds every unique column to extraReturningColumns, which is appended to an
array-form .returning() projection and retained in InsertResult.raw. For a conflict insert whose
caller requests only an ID, returning the raw result to an API consumer now also exposes any unique
secret or token column on the entity, even when no row was skipped.
Code

src/query-builder/InsertQueryBuilder.ts[R152-155]

+                    this.expressionMap.extraReturningColumns = [
+                        ...this.expressionMap.extraReturningColumns,
+                        ...this.expressionMap
+                            .mainAlias!.metadata.getUpsertConflictIdentificationColumns()
Evidence
The returning-expression builder appends extra columns to array-form projections, PostgreSQL exposes
those fields in the raw rows, and InsertResult.from passes that raw value through to callers. The
new condition adds them regardless of whether a conflict actually skips a row.

src/query-builder/QueryBuilder.ts[938-959]
src/driver/postgres/PostgresQueryRunner.ts[297-314]
src/query-builder/result/InsertResult.ts[8-29]
src/query-builder/InsertQueryBuilder.ts[192-225]

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

## Issue description
Columns added solely for internal row correlation appear in the public raw insert result, bypassing a caller's requested returning projection.
## Fix Focus Areas
- src/query-builder/InsertQueryBuilder.ts[152-163]
- src/query-builder/InsertQueryBuilder.ts[192-225]
- src/query-builder/result/InsertResult.ts[8-29]
## Recommended Fix
Retain internal correlation values only while mapping rows, then remove columns not requested by the caller from the exposed raw result. Test a conflict insert with `.returning(["id"])` and a unique sensitive column.

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



Informational
12. The mapper adds excessive comments 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The new mapping methods include long comments and docstrings that restate the implementation flow
and defensive fallback behavior. The added prose spans multiple blocks around row matching and makes
the production code harder to scan without changing its runtime behavior.
Code

packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[R305-311]

+    /**
+     * Maps RETURNING rows back to the entities that produced them when a
+     * conflict clause (orIgnore / orUpdate) may have skipped some rows, which
+     * makes positional mapping wrong. Returns an array where index i holds the
+     * index into insertResult.raw for entity i, or -1 when the entity has no
+     * matching returned row (its row was skipped). Returns undefined when
+     * positional mapping is correct and should be used as before.
Evidence
The diff adds multiple lengthy explanatory comment blocks around the new mapper, including a
detailed method docstring and a multi-line fallback rationale, matching the checklist's prohibition
on extra AI-like comments and style-inconsistent noise.

Rule 4: Remove AI-generated noise
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[305-311]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[359-369]

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 new row-mapping implementation adds lengthy comments and docstrings that repeat the code's control flow and fallback behavior, introducing avoidable maintenance noise.

Fix Focus Areas
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[305-311]
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[359-369]
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[374-385]

Recommended Fix
Replace the long explanatory blocks with concise comments that describe only the non-obvious invariant: returned rows are consumed in entity order and skipped entities remain unmapped. Remove comments that restate straightforward conditions or implementation details.

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


Context sources
Review mode: Auto: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 10/18, lines 376/200; both must reach the floor). Router rationale: Core ORM mapping logic spans multiple edge-case-heavy paths with substantial defect density.
⚠️ Warning | Comment size exceeded, non finding content trimmed Learn more

Grey Divider

Qodo Logo

…by key

ReturningResultsEntityUpdator.insert matched RETURNING rows to entities
by array position. With ON CONFLICT DO NOTHING (orIgnore) or a DO UPDATE
that skips a row, RETURNING comes back shorter than the entity list, so
every row after a skipped one shifted onto the previous entity: a skipped
entity received the next inserted row's id (and other returned columns),
and the inserted entity lost its generated values. With user-set ids two
entities could even end up sharing one id.

Match returned rows to entities by the columns that identify the
conflicting row (primary and unique columns) instead of by position. Those
columns are added to RETURNING for the on-conflict-do-update drivers, and
the rows, which come back in entity order, are consumed in order so each
is assigned only to the entity whose identifying values equal it. Skipped
entities are left untouched. When no row is skipped the previous positional
path is kept unchanged.

Verified on PostgreSQL across skip-first, skip-middle, skip-last,
multi-skip and no-skip cases; regression tests added to the insert
on-conflict functional suite (postgres, cockroachdb, better-sqlite3).

Closes typeorm#12994
@ElwinErnst
ElwinErnst force-pushed the fix/insert-or-ignore-row-mapping branch from a48de09 to 2a09e17 Compare October 25, 2026 16:32
@ElwinErnst

Copy link
Copy Markdown
Author

Thanks for the review. Addressed the test-placement note: the regression coverage now lives in the existing insert-on-conflict functional suite (packages/typeorm/test/functional/query-builder/insert-on-conflict/, with a Tag entity) instead of a per-issue directory, following DEVELOPER.md and the functional-test preference. The three scenarios (skip-first, skip-middle, no-skip) run on postgres, cockroachdb and better-sqlite3, and the github-issues/12994/ directory has been removed.

@pkg-pr-new

pkg-pr-new Bot commented Oct 25, 2026

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

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

commit: 2a09e17

Harden the conflict-row-to-entity matching added for orIgnore/orUpdate:

- Fall back to positional mapping when identity matching cannot account
  for every returned row (previously a batch where no entity carried a
  pre-insert identifying value, or a mismatch broke the walk, would
  discard generated values for genuinely-inserted rows — worse than the
  positional behaviour it replaced).
- Hydrate the raw RETURNING value via the driver before comparing it to
  the entity value, and reuse ColumnMetadata.compareEntityValue, so
  transformer columns, booleans stored as 0/1 and date representations no
  longer produce false negatives that drop or misassign generated ids.

Adds regression coverage with a transformer-backed unique column.
… in orIgnore mapping

entityMatchesReturnedRow fell back to String() equality, so an entity whose
identifying value is the literal string "null" matched a returned row whose
value is a real SQL NULL (String(null) === String("null")). A skipped entity
keyed on "null" could then consume the returned row of an inserted entity
keyed on NULL and receive the wrong generated values.

Reject null-versus-non-null comparisons before the String() fallback. Add a
regression to the insert on-conflict suite covering an ignored "null" key
followed by an inserted NULL key.
@ElwinErnst

Copy link
Copy Markdown
Author

Thanks for the review. Pushed a761dd4c5, which closes out the actionable finding; here is where each stands:

Fixed

  • Ignored rows receive another row's ID (null vs "null") — fixed. entityMatchesReturnedRow now rejects a match when exactly one side is null, before the String() fallback can equate SQL NULL with the literal string "null". Covered by a NullableTag regression case in the on-conflict suite.

Keeping as-is, with rationale

  • Inserted rows assigned to skipped entities (composite key, undefined component) — the matcher already requires every identifying column the entity has a value for to match. The remaining gap is a component that is undefined on both entities (not provided pre-insert). There is no entity-side value to distinguish them, and the generated PK is undefined before the insert, so requiring a complete key would reintroduce the positional-mapping bug from upsert() with MySQL mutates input entity objects in-place with wrong auto-increment IDs after ON DUPLICATE KEY UPDATE #12094. Not resolvable without data that does not exist yet.
  • Unmanaged unique indexes leave rows unmapped (synchronize: false) — when index.columns is empty, the identifying set shrinks and the mapper returns undefined, falling back to the pre-existing positional mapping. It degrades to prior behavior rather than corrupting anything, so this is a pre-existing limitation of IndexMetadata.build, not a regression this PR introduces.
  • Comment volume — these blocks document non-obvious invariants (why undefined is returned instead of the -1 array, the null-guard reasoning, hydrating the raw row value before comparison). They are load-bearing rather than restating the code, so I'd prefer to keep them. Happy to trim if a maintainer disagrees.

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

linked-issue PR references an issue

Development

Successfully merging this pull request may close these issues.

insert().orIgnore() writes the returned rows back onto the wrong entities when a row is skipped

1 participant