Skip to content

fix(query-builder): prevent orIgnore returning mismatch on skipped entities - #13051

Open
Asadshah7950 wants to merge 5 commits into
typeorm:masterfrom
Asadshah7950:fix/or-ignore-returning-entity-mismatch
Open

Asadshah7950 wants to merge 5 commits into
typeorm:masterfrom
Asadshah7950:fix/or-ignore-returning-entity-mismatch

Conversation

@Asadshah7950

@Asadshah7950 Asadshah7950 commented Nov 9, 2026 •

Copy link
Copy Markdown

Description of change

Fixes an issue where \insert().orIgnore()\ (or \ON CONFLICT DO NOTHING) shifts database-returned rows onto the wrong entity instances when one or more rows are skipped due to a unique constraint conflict (Closes #12994, Fixes #5226).

Root Cause

When executing multi-row inserts with .orIgnore()\ on database drivers supporting \RETURNING\ clauses (such as PostgreSQL, CockroachDB, MSSQL), the database skips conflicted rows and returns only the rows that were actually inserted (fewer rows than the original \entities\ array).

Previously, \ReturningResultsEntityUpdator.insert()\ assumed a 1:1 positional index mapping:
\\ s
const result = Array.isArray(insertResult.raw)
? insertResult.raw[entityIndex]
: insertResult.raw
\
When an entity at index \

…tities (typeorm#12994)

When performing bulk inserts with .insert().orIgnore() on drivers supporting RETURNING statements, databases skip writing rows that violate unique constraints and return only the rows that were actually inserted. Previously, ReturningResultsEntityUpdator mapped insertResult.raw[entityIndex] strictly by positional array index, which shifted returned identifiers and autogenerated columns onto skipped entities and left subsequent inserted entities undefined.

This commit resolves the issue by:
1. Ensuring InsertQueryBuilder includes inserted columns in extraReturningColumns when onIgnore is enabled on drivers supporting RETURNING, so returned rows contain identifying column values.
2. Correlating returned raw rows to entities in ReturningResultsEntityUpdator by primary key or inserted column values when onIgnore is enabled or fewer rows are returned than entities.
3. Leaving skipped entities untouched and assigning undefined to their corresponding positions in insertResult.identifiers and insertResult.generatedMaps.
@github-actions github-actions Bot added needs-triage PR needs issue link triage linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR and removed needs-triage PR needs issue link triage labels Nov 9, 2026
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Ignored inserts can fail on transformed values 🐞 Bug ≡ Correctness ⭐ New
Description
doesColumnValueMatch() calls transformFrom on hydratedRawValue, even though
prepareHydratedValue() has already applied that transformer. When correlation tests a returned row
against a nonmatching entity, a transformer that expects a database string can receive its own array
output and throw, aborting the insert result processing.
Code

packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[R531-534]

+            const hydratedFromRaw = ApplyValueTransformers.transformFrom(
+                column.transformer,
+                hydratedRawValue,
+            )
Evidence
The matcher hydrates the raw value before its fallback branch, while PostgreSQL hydration already
applies transformFrom. The repository's string-to-array transformer calls .split() in from, so
invoking it again with the resulting array throws when the earlier comparisons find a mismatch.

packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[489-543]
packages/typeorm/src/driver/postgres/PostgresDriver.ts[989-995]
packages/typeorm/test/functional/columns/value-transformer/entity/Post.ts[5-12]

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

## Issue description
Correlation can invoke a value transformer's `from` method twice for a nonmatching returned row, causing non-idempotent transformers to throw.

## Fix Focus Areas
- packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[489-544]

## Recommended Fix
Use the already-hydrated value for comparisons instead of applying `transformFrom` to it again. Add a regression case with a non-idempotent transformer and a skipped row preceding a differently valued inserted row.

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


2. Skipped null-valued rows receive wrong IDs ✓ Resolved
Description
doesEntityMatchRaw() ignores explicitly null entity values, so another row can match solely on the
fields they share. If a partial unique index skips a null-valued row while a row with the same other
values and a non-null value is inserted, the skipped entity consumes the inserted row's generated ID
and the inserted entity remains unmatched.

3. Aliased returns put IDs on skipped rows ✓ Resolved
Description
createReturningExpression() treats a column mentioned in a custom returning string as an unaliased
result field, so returning("name AS alias") does not append the name field needed for
correlation. When a bulk ignored insert skips the first entity, the returned row has alias rather
than name; the matcher can accept that row for the skipped entity and merge the inserted entity's
generated ID into it.

View action required (4)
4. SQL-based keys misassign generated values ✓ Resolved
Description
doesEntityMatchRaw() skips a function-valued primary key without clearing allPrimaryKeysDefined,
then accepts the returned row before comparing other columns. If a bulk ignored insert uses SQL
expressions for primary keys and an earlier entity is skipped on another unique constraint, that
entity can consume a later entity's returned row and generated values.

5. Skipped rows can receive another row's ID ✓ Resolved
Description
getEntityMatchingSignature() joins stringified column values without escaping their boundaries,
and the fast path accepts a matching signature without checking the underlying values. If a
conflicted entity and an inserted entity have distinct values that produce the same signature, the
inserted row's generated values are merged into the skipped entity.

6. Explicit returning loses inserted IDs ✓ Resolved
Description
InsertQueryBuilder adds identifying columns to extraReturningColumns, but
createReturningExpression() omits those columns from SQL when .returning() receives a string.
With .orIgnore().returning("id") and generated primary keys, the matcher sees only returned IDs,
cannot match them to input entities, and leaves even successfully inserted entities without
generated maps or identifiers.

7. Default-only inserts lose generated IDs ✓ Resolved
Description
doesEntityMatchRaw() requires at least one defined, non-generated input value to match a returned
row. When an ignored insert supplies only defaults, PostgreSQL can insert and return the row, but
the matcher rejects it and records an undefined identifier and generated map.


Remediation recommended

8. Trailing comments hide returned columns 🐞 Bug ≡ Correctness ⭐ New
Description
createReturningExpression() appends identifying columns directly to a custom returning string,
including after a trailing SQL -- comment. With .orIgnore().returning('id -- note'), PostgreSQL
treats the appended columns as comment text, so the matcher lacks the returned values it needs when
rows are skipped.
Code

packages/typeorm/src/query-builder/QueryBuilder.ts[1064]

+                            returning += ", " + extraStr
Evidence
The new string-returning branch concatenates extra expressions after the entire supplied fragment.
Its SQL scanner recognizes -- as extending to the newline or end of the fragment, while the
matcher relies on those extra columns being present in returned rows.

packages/typeorm/src/query-builder/QueryBuilder.ts[1025-1065]
packages/typeorm/src/query-builder/QueryBuilder.ts[1120-1125]
packages/typeorm/src/query-builder/InsertQueryBuilder.ts[124-151]
packages/typeorm/src/query-builder/ReturningResultsEntityUpdator.ts[185-208]

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

## Issue description
Appending correlation columns after a trailing SQL line comment makes those columns part of the comment rather than the RETURNING list.

## Fix Focus Areas
- packages/typeorm/src/query-builder/QueryBuilder.ts[1025-1069]
- packages/typeorm/src/query-builder/QueryBuilder.ts[1195-1205]

## Recommended Fix
Place added expressions before a trailing line comment, preserving valid SQL and the user's comment. Cover custom PostgreSQL RETURNING and SQL Server OUTPUT fragments ending in `--` comments.

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


9. Test cleanup bypasses driver types with a double cast ⊘ Outdated
Description
The MSSQL test's finally block removes buildTableVariableDeclaration by casting
dataSource.driver through unknown to Record, which hides the driver's real type. The same test
already restores this property through driverCleanupCallbacks in
setupEmulatedReturningQueryRunner, so the cast-and-delete is a second, inconsistent cleanup path.
A later maintainer adding a stub will see two cleanup mechanisms and may trust the cast instead of
the typed API.

10. InsertResult type change is undocumented for users ✓ Resolved
Description
InsertResult.identifiers and InsertResult.generatedMaps now hold undefined for entities
skipped by orIgnore(), a visible change to the public result shape. The diff only updates the type
declarations and adds no docs or changelog note, so users who read .id from each identifiers
entry will not learn they must guard against undefined for ignored rows.

View review recommended (11)
11. Date strings lose inserted IDs ✓ Resolved
Description
doesEntityMatchRaw() compares an entity's timestamp string against the PostgreSQL driver's
hydrated Date without normalizing the input first. When a successful ignored bulk insert returns
fewer rows than supplied entities and a timestamp string identifies an inserted row, correlation
rejects that row and records an undefined generated map and identifier.

12. Output comments break ignored inserts ✓ Resolved
Description
createReturningExpression() searches the raw custom output string for INTO without excluding SQL
comments or string literals, and splices identifying columns at the first occurrence. A SQL Server
output clause such as INSERTED.id /* INTO note */ INTO @OutputTable receives its additional
expression inside the comment rather than before the real target, leaving fewer output expressions
than declared table columns.

13. Output target lists reject ignored inserts ✓ Resolved
Description
createReturningExpression() adds expressions before a SQL Server INTO clause but preserves any
explicit target-column list after it. For a custom clause such as `INSERTED.id INTO @OutputTable
(id)`, an ignored insert adds an output expression for an identifying column without adding its
target column, so SQL Server rejects the mismatched lists.

14. Setup failures pass tests silently ⊘ Outdated
Description
The unit tests cast the query builder to any to reach private state and re-implement the
production extraReturningColumns loop in the test body. Several it blocks also begin with `if
(!fakeDataSource) return`, so a failed setup reports success without asserting anything.

15. Issue regression test skips the functional test suite ✓ Resolved
Description
The fix's only regression tests are a new github-issues/12994 directory, and no test is added
under packages/typeorm/test/functional. The PR gives no reason for choosing the per-issue
location, so the fix does not follow the project's preference for functional tests. The issue number
is referenced in the test title, but that does not change the directory placement. Future
contributors will look for this behaviour's coverage in the functional suite and will not find it
there.

16. Result mapping casts bypass the types it writes to ✓ Resolved
Description
The new insert() loop pushes entityId and generatedMaps[entityIndex] onto InsertResult
arrays using as any casts. These casts hide a type mismatch rather than resolving it, and the
casts apply to every row written by a bulk insert, including rows left undefined for skipped
entities. Later maintainers reading the result types will not see that these arrays can hold
undefined, so the casts also make future type errors in this path harder to find.

17. Bracketed column names break ignored inserts ✓ Resolved
Description
createReturningExpression() puts column.databaseName directly into a regular expression rather
than treating it as a literal column name. With .orIgnore().returning(...), a valid quoted
database column name containing an unmatched [ makes query construction throw before the insert
executes.

18. Oracle inserts fail with custom returning ✓ Resolved
Description
createReturningExpression() appends identifying columns to the end of a custom returning string,
including after an Oracle INTO clause. When an Oracle insert uses .orIgnore() and a custom
fragment such as id INTO :out, the generated RETURNING id INTO :out, "name" places a returned
column among the output binds.

19. Computed values hide inserted rows ✓ Resolved
Description
doesEntityMatchRaw() compares original entity values with hydrated database results, although
insert expressions and persistence transformers can change those values before storage. For example,
an input SQL function producing a slug or a transformer normalizing it makes a successful
.orIgnore() insert fail correlation, so its returned generated values are discarded.

20. Partial keys hide inserted rows ✓ Resolved
Description
doesEntityMatchRaw() selects primary-key matching when any primary-key component is set, but marks
the match false when another component is unset. An entity with a supplied primary-key component and
a generated component is therefore rejected before its inserted columns can be compared, even when
the database returned its row.

21. Large ignored inserts scan quadratically ✓ Resolved
Description
ReturningResultsEntityUpdator.insert() scans the returned-row array from the start for each input
entity and checks columns for every unused candidate. A large .orIgnore() bulk insert on a
returning-capable driver can therefore perform a quadratic number of comparisons on its query-result
path.

Grey Divider

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

Grey Divider

Context sources
Review mode: Auto: ⚖️ Balanced: Downgraded extended -> standard: change is below the extended eligibility bar (hunks 12/18, lines 1800/200; both must reach the floor). Router rationale: Large, bug-dense cross-driver logic change with many independent defect opportunities.

Grey Divider

⚠️ Warning | Comment size exceeded, non finding content trimmed Learn more

Grey Divider

Qodo Logo

@Asadshah7950

Copy link
Copy Markdown
Author

Addressed Qodo Review Edge Cases (commit 8692f73)

Thank you @qodo-cover-pr-agent for the thorough automated review. All 5 edge cases identified in the review have been addressed:

  1. String-form .returning(id):

    • In QueryBuilder.ts, when
      eturning is specified as a string clause, createReturningExpression() now checks extraReturningColumns during .orIgnore() inserts.
    • Any non-wildcard missing identifying columns are automatically appended (including INSERTED. prefixing for MSSQL) to ensure the database returns the columns required for entity correlation.
  2. Default-only entities (�alues([{}])):

    • isMatchingRequired is strictly activated only when insertResult.raw.length < entities.length (when rows are actually skipped by conflict).
    • In doesEntityMatchRaw(), if an entity has no user-supplied non-generated values (e.g. table with all database defaults or generated columns), it now matches an available returned row if no column mismatch was detected (
      eturn !hasMismatch) instead of failing on matchedColumnsCount > 0.
  3. Computed values & persistence transformers:

    • Column values with ransformer defined are compared both in domain format and database-transformed format via ApplyValueTransformers.transformTo() and ApplyValueTransformers.transformFrom().
    • Computed SQL functions (() => ...) are skipped during entity-to-raw column comparisons rather than failing equality against generated values.
  4. Partial composite primary keys:

    • In doesEntityMatchRaw(), if an entity specifies a partial composite primary key (e.g. a provided tenant/partition ID with a database-generated sequential ID), defined components are verified and do not abort early when undefined generated components are encountered; verification cleanly continues to non-generated columns.
  5. (N \times M)$ matching complexity on bulk inserts:

    • Added getEntityMatchingSignature() and an index map signatureToRawIndices: Map<string, number[]> over candidate identifying columns in ReturningResultsEntityUpdator.
    • Resolves matches in (1)$ time per entity, reducing bulk insert matching from quadratic (N \times M)$ to linear (N)$.

Unit tests covering all 5 scenarios have been added to est/github-issues/12994/issue-12994.test.ts. All 31 existing query builder insert tests and 10 issue tests pass cleanly.

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

Copy link
Copy Markdown

Addressed Qodo Review Edge Cases (commit 8692f73)

Thank you @qodo-cover-pr-agent for the thorough automated review. All 5 edge cases identified in the review have been addressed:

  1. String-form .returning(id):

    • In QueryBuilder.ts, when
      eturning is specified as a string clause, createReturningExpression() now checks extraReturningColumns during .orIgnore() inserts.
    • Any non-wildcard missing identifying columns are automatically appended (including INSERTED. prefixing for MSSQL) to ensure the database returns the columns required for entity correlation.
  2. Default-only entities (
    alues([{}]))
    :

    • isMatchingRequired is strictly activated only when insertResult.raw.length < entities.length (when rows are actually skipped by conflict).
    • In doesEntityMatchRaw(), if an entity has no user-supplied non-generated values (e.g. table with all database defaults or generated columns), it now matches an available returned row if no column mismatch was detected (
      eturn !hasMismatch) instead of failing on matchedColumnsCount > 0.
  3. Computed values & persistence transformers:

    • Column values with ransformer defined are compared both in domain format and database-transformed format via ApplyValueTransformers.transformTo() and ApplyValueTransformers.transformFrom().
    • Computed SQL functions (() => ...) are skipped during entity-to-raw column comparisons rather than failing equality against generated values.
  4. Partial composite primary keys:

    • In doesEntityMatchRaw(), if an entity specifies a partial composite primary key (e.g. a provided tenant/partition ID with a database-generated sequential ID), defined components are verified and do not abort early when undefined generated components are encountered; verification cleanly continues to non-generated columns.
  5. (N \times M)$ matching complexity on bulk inserts:

    • Added getEntityMatchingSignature() and an index map signatureToRawIndices: Map<string, number[]> over candidate identifying columns in ReturningResultsEntityUpdator.
    • Resolves matches in (1)$ time per entity, reducing bulk insert matching from quadratic (N \times M)$ to linear (N)$.

Unit tests covering all 5 scenarios have been added to est/github-issues/12994/issue-12994.test.ts. All 31 existing query builder insert tests and 10 issue tests pass cleanly.

Thanks for the update. The published report already marks all five findings as resolved in commit 8692f73:

  • Finding 1, explicit returning loses inserted IDs: resolved. createReturningExpression() now appends the correlation columns to string-form .returning() clauses during .orIgnore() inserts.
  • Finding 2, default-only inserts lose generated IDs: resolved. Default-only entities can match returned rows.
  • Finding 3, computed values hide inserted rows: resolved. Transformers are applied before comparison, and SQL-expression values are skipped.
  • Finding 4, partial keys hide inserted rows: resolved. Unset primary-key components no longer reject a match outright.
  • Finding 5, large ignored inserts scan quadratically: resolved. A signature index replaces the full scan, with sequential matching kept as a fallback.

I haven't checked the new tests or the code itself. If you want Qodo to re-review the PR against the latest commit, ask me to run a review.

@Asadshah7950

Copy link
Copy Markdown
Author

Addressed Qodo Review Finding (commit dba7220)

Thank you @qodo-free-for-open-source-projects for the sharp review catch. The candidate verification and signature delimiter boundary issue has been resolved:

  1. Unambiguous Length-Prefixed Signatures:

    • Updated getEntityMatchingSignature() to format each component using length-prefixed encoding: ${colName.length}:${colName}=${valStr.length}:${valStr}.
    • Eliminates boundary conflation when column values contain delimiters such as ; or = (e.g. {a: "x;b=2", b: "3"} vs {a: "x", b: "2;b=3"}).
  2. Per-Candidate Value Verification:

    • In the fast-path candidate lookup, each retrieved raw candidate is now explicitly validated against the entity using this.doesEntityMatchRaw(entity, candidateRaw) before marking it used and assigning the match.
    • Non-matching candidates remain available in the candidate list for subsequent true-matching entities, guaranteeing that a skipped entity never consumes another entity's returned identifier.
  3. Regression Tests:

    • Added unit test should verify candidate rows against actual entity values and never match skipped rows with delimiter-confusable signatures in test/github-issues/12994/issue-12994.test.ts.
    • All 12 issue tests and 31 query builder insert tests pass cleanly.

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

Copy link
Copy Markdown

Addressed Qodo Review Finding (commit dba7220)

Thank you @qodo-free-for-open-source-projects for the sharp review catch. The candidate verification and signature delimiter boundary issue has been resolved:

  1. Unambiguous Length-Prefixed Signatures:

    • Updated getEntityMatchingSignature() to format each component using length-prefixed encoding: ${colName.length}:${colName}=${valStr.length}:${valStr}.
    • Eliminates boundary conflation when column values contain delimiters such as ; or = (e.g. {a: "x;b=2", b: "3"} vs {a: "x", b: "2;b=3"}).
  2. Per-Candidate Value Verification:

    • In the fast-path candidate lookup, each retrieved raw candidate is now explicitly validated against the entity using this.doesEntityMatchRaw(entity, candidateRaw) before marking it used and assigning the match.
    • Non-matching candidates remain available in the candidate list for subsequent true-matching entities, guaranteeing that a skipped entity never consumes another entity's returned identifier.
  3. Regression Tests:

    • Added unit test should verify candidate rows against actual entity values and never match skipped rows with delimiter-confusable signatures in test/github-issues/12994/issue-12994.test.ts.
    • All 12 issue tests and 31 query builder insert tests pass cleanly.

Thanks for the update. The fix you describe targets finding 1 (skipped rows receiving another row's ID), but the published report still lists it as open. That report covers commit 8692f73, and I can't see a review of dba7220 yet, so the report hasn't caught up.

  • Finding 1: Your per-candidate doesEntityMatchRaw check should stop a skipped entity from consuming another row's ID. Length-prefixing the signature also removes the delimiter collision from the evidence. A re-review would confirm this.
  • Finding 4: The new regression test is still under test/github-issues/12994/. The report flags that the project prefers test/functional/, so this rule violation remains unless you move the test.
  • Findings 5 and 6: Your change doesn't address the as any casts or the regex built from column names. These are still open.

If you want the report refreshed against dba7220, ask me to run a review again.

@Asadshah7950

Copy link
Copy Markdown
Author

Addressed All Updated Qodo Review Findings & Compliance Rules (commit 09fd2fbb7)

Thank you @qodo-free-for-open-source-projects for the detailed review. All 4 reported bugs and 3 compliance/type-safety items have been resolved:

  1. Aliased RETURNING Columns & Missing Raw Field Correlation:

    • Updated QueryBuilder.createReturningExpression() with quote/expression-aware helpers (splitReturningExpressions, unquoteIdentifier, hasUnaliasedReturningColumn) so aliased items like name AS alias are not mistaken for unaliased column returns, ensuring the raw identifying column is appended when needed for correlation.
    • Updated ReturningResultsEntityUpdator.doesEntityMatchRaw() to track hasComparableColumnValue independently of whether the column key exists in rawItem, preventing entities with non-default values from falsely matching when expected returning columns are missing from raw output.
  2. SQL-Expression Primary Keys (typeof val === 'function'):

    • In doesEntityMatchRaw(), primary keys whose entity value is a SQL expression function now set allPrimaryKeysDefined = false, falling through cleanly to non-PK column correlation instead of short-circuiting to true.
  3. Regex-Free Tokenizer for Custom RETURNING Columns:

    • Replaced dynamic new RegExp(...) construction with explicit quote/bracket/alias tokenization in splitReturningExpressions(), unquoteIdentifier(), and hasUnaliasedReturningColumn(), safely supporting column names containing regex metacharacters (e.g. code[).
  4. Oracle RETURNING ... INTO & MSSQL OUTPUT ... INTO Handling:

    • Skips modifying custom Oracle RETURNING ... INTO strings and empty RETURNING expressions.
    • For MSSQL custom OUTPUT ... INTO strings, inserts extra INSERTED.<column> identifying columns before the INTO clause rather than trailing after it.
  5. Type Safety & Compliance Rule Alignment:

    • Removed as any casts when pushing undefined slots by typing InsertResult.identifiers and InsertResult.generatedMaps as (ObjectLiteral | undefined)[], and replaced any with unknown in getEntityMatchingSignature.
    • Relocated regression tests from test/github-issues/12994/ into test/functional/query-builder/insert-on-ignore-returning/ referencing #12994 / #5226, driving execution through public QueryBuilder.insert().orIgnore().returning().execute() APIs without as any casts or if (!dataSource) return guards.
  6. Verification:

    • npx tsc --noEmit: passed with 0 errors.
    • pnpm test:fast --grep "query builder > insert": 43 passing (including all 12 tests under on ignore returning correlation).

@qodo-free-for-open-source-projects Please run an updated review against commit 09fd2fbb7.

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

Copy link
Copy Markdown

Addressed All Updated Qodo Review Findings & Compliance Rules (commit 09fd2fbb7)

Thank you @qodo-free-for-open-source-projects for the detailed review. All 4 reported bugs and 3 compliance/type-safety items have been resolved:

  1. Aliased RETURNING Columns & Missing Raw Field Correlation:

    • Updated QueryBuilder.createReturningExpression() with quote/expression-aware helpers (splitReturningExpressions, unquoteIdentifier, hasUnaliasedReturningColumn) so aliased items like name AS alias are not mistaken for unaliased column returns, ensuring the raw identifying column is appended when needed for correlation.
    • Updated ReturningResultsEntityUpdator.doesEntityMatchRaw() to track hasComparableColumnValue independently of whether the column key exists in rawItem, preventing entities with non-default values from falsely matching when expected returning columns are missing from raw output.
  2. SQL-Expression Primary Keys (typeof val === 'function'):

    • In doesEntityMatchRaw(), primary keys whose entity value is a SQL expression function now set allPrimaryKeysDefined = false, falling through cleanly to non-PK column correlation instead of short-circuiting to true.
  3. Regex-Free Tokenizer for Custom RETURNING Columns:

    • Replaced dynamic new RegExp(...) construction with explicit quote/bracket/alias tokenization in splitReturningExpressions(), unquoteIdentifier(), and hasUnaliasedReturningColumn(), safely supporting column names containing regex metacharacters (e.g. code[).
  4. Oracle RETURNING ... INTO & MSSQL OUTPUT ... INTO Handling:

    • Skips modifying custom Oracle RETURNING ... INTO strings and empty RETURNING expressions.
    • For MSSQL custom OUTPUT ... INTO strings, inserts extra INSERTED.<column> identifying columns before the INTO clause rather than trailing after it.
  5. Type Safety & Compliance Rule Alignment:

    • Removed as any casts when pushing undefined slots by typing InsertResult.identifiers and InsertResult.generatedMaps as (ObjectLiteral | undefined)[], and replaced any with unknown in getEntityMatchingSignature.
    • Relocated regression tests from test/github-issues/12994/ into test/functional/query-builder/insert-on-ignore-returning/ referencing #12994 / #5226, driving execution through public QueryBuilder.insert().orIgnore().returning().execute() APIs without as any casts or if (!dataSource) return guards.
  6. Verification:

    • npx tsc --noEmit: passed with 0 errors.
    • pnpm test:fast --grep "query builder > insert": 43 passing (including all 12 tests under on ignore returning correlation).

@qodo-free-for-open-source-projects Please run an updated review against commit 09fd2fbb7.

I can't start a new review from this chat, because the review-rerun tool isn't available on this deployment. The current report has no open findings: finding 1 through finding 5 and finding 7 through finding 13 are marked resolved, and finding 6 is marked outdated.

Here's what I can do:

  • Explain how any specific resolved finding was addressed, for example finding 3 (skipped rows receiving another row's ID).
  • Check a particular part of the diff, such as the RETURNING parsing in QueryBuilder.createReturningExpression() or the matcher in ReturningResultsEntityUpdator.
  • Walk through the new regression tests in test/functional/query-builder/insert-on-ignore-returning/.

To get a fresh review of commit 09fd2fbb7, use the Qodo review trigger you normally use for this repository, or ask a maintainer with access to run it.

@Asadshah7950

Copy link
Copy Markdown
Author

Addressed Remaining Qodo Findings & Compliance Rules (commit 79084b1ab)

All 4 remaining edge-case bugs and 2 compliance items from the updated 09fd2fbb7 review have been fixed:

  1. Explicit null Values Treated as Comparable (#1):

    • ReturningResultsEntityUpdator.normalizeColumnSignaturePart() and doesEntityMatchRaw() now distinguish explicit null from unset (undefined), encode explicit null unambiguously (n:null) so it never collides with literal "null", and verify returned values against explicit null so a skipped null row cannot consume an inserted non-null row's ID.
  2. Timestamp Strings Normalized Consistently with Driver Date Hydration (#9):

    • Normalized entity values through driver.preparePersistentValue() and raw values through driver.prepareHydratedValue() / driver.preparePersistentValue() in both normalizeColumnSignaturePart() (encoding Date via .toISOString()) and doesColumnValueMatch(), matching string timestamp inputs against hydrated Date outputs.
  3. SQL-Comment/Literal-Safe OUTPUT INTO Detection & Target Column Expansion (#10, #11):

    • Extracted QueryBuilder.advancePastSqlDelimiter(), findTopLevelIntoKeyword(), expandMssqlCustomOutputClause(), and appendMssqlTargetColumns() so comments (e.g. /* INTO note */), string literals ('text INTO x'), and whitespace before trailing comments are skipped cleanly.
    • When an MSSQL custom OUTPUT ... INTO <target> (...) specifies an explicit target-column list, matching extra identifying columns are now appended inside the target column list alongside INSERTED.<col> before INTO.
  4. Test Cleanup & InsertResult Documentation (#7, #8):

    • Removed the redundant double-cast delete from the MSSQL test finally block in insert-on-ignore-returning.test.ts (handled cleanly via driverCleanupCallbacks in afterEach).
    • Updated JSDoc comments on InsertResult.identifiers and InsertResult.generatedMaps and added a user-facing note in docs/docs/query-builder/2-insert-query-builder.md documenting undefined slots for rows skipped by orIgnore().
  5. Verification:

    • npx tsc --noEmit: 0 errors.
    • pnpm test:fast --grep "query builder > insert": 47 passing (including 16 passing tests under on ignore returning correlation).

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 possible-duplicate PR may duplicate an existing open PR

1 participant