Skip to content

fix(query-builder): prevent upsert from mutating input entities - #13029

Open
ElwinErnst wants to merge 5 commits into
typeorm:masterfrom
ElwinErnst:fix/upsert-no-input-mutation
Open

ElwinErnst wants to merge 5 commits into
typeorm:masterfrom
ElwinErnst:fix/upsert-no-input-mutation

Conversation

@ElwinErnst

Copy link
Copy Markdown

Description of change

What: upsert() no longer mutates the input entity objects passed by the caller.

Why: On drivers without RETURNING (e.g. mysql, sqlite), ReturningResultsEntityUpdator.insert() fabricated the generated primary key from the driver insert id and merged it back into every input entity in place. Under ON DUPLICATE KEY UPDATE / ON CONFLICT DO UPDATE, the driver still reports a non-zero insert id even when a row was updated, so updated rows had a wrong primary key written onto them — silently corrupting the caller's in-memory objects with no error or warning. See #12094.

Change: When the operation is an upsert (expressionMap.onUpdate is set), the updator now operates on clones of the entities (OrmUtils.cloneObject, which preserves the entity prototype) instead of the caller's originals. The originals are left untouched. Generated values remain available through insertResult.generatedMaps and insertResult.identifiers.

Behavior note: As a consequence, upsert() no longer writes generated ids back into the passed-in objects (previously it did so — correctly for inserted rows, incorrectly for updated rows). Read generated values from the returned InsertResult instead. This aligns with the expectation in #12094 that input objects should not be mutated.

Current vs new behavior

  • Before: await repo.upsert(entity, ["email"]) could overwrite entity.id with a wrong value when the row was updated.
  • After: entity is left exactly as the caller passed it; ids are exposed via the returned InsertResult.

How verified: Added test/github-issues/12094/ with three cases (no mutation on insert, no wrong-id overwrite on update, generated ids still exposed via InsertResult). Confirmed the new tests fail on master and pass with this change, and that the existing upsert/returning test suites still pass. The defect reproduces beyond MySQL — it was verified against sqljs as well.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links a relevant issue using a closing keyword: Closes #12094
  • There are new or updated tests validating the change
  • Documentation has been updated to reflect this change — N/A (bug fix, no documented behavior change)

Closes #12094

When calling upsert() on drivers without RETURNING (e.g. mysql, sqlite),
TypeORM fabricated the generated primary key from the driver insert id and
merged it back into each input entity in place. On ON DUPLICATE KEY UPDATE /
ON CONFLICT DO UPDATE this wrote a wrong id onto rows that were updated,
silently corrupting the caller's in-memory objects.

Operate on clones of the entities for upserts so the originals are left
untouched. Generated values are still surfaced through
insertResult.generatedMaps and insertResult.identifiers.

Closes typeorm#12094
@github-actions github-actions Bot added linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR labels Nov 1, 2026
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Other open PRs also reference #12094: #12155. Maintainers may want to coordinate.

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

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

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Users get no guidance on changed upsert results ✓ Resolved

Resolving commit: ff62340

Resolution reason
Added documentation stating that upsert leaves input entities unmodified and that generated values
(auto-increment/default PKs) must be read from the returned InsertResult via identifiers,
generatedMaps, or raw. Also added tests covering the new behavior.
Description
ReturningResultsEntityUpdator now clones entities for upserts, so generated ids no longer write
back to caller objects. The new tests codify this changed public usage, but no documentation or
sample explains that callers must read generated values from the returned InsertResult.

2. The issue fix skips the functional test suite 📘 Rule violation ⚙ Maintainability
Description
The new regression coverage for issue 12094 is placed in
packages/typeorm/test/github-issues/12094/issue-12094.test.ts instead of the functional test
suite. This leaves the fix validated only by a per-issue test and does not add an issue reference to
a functional test.
Code

packages/typeorm/test/github-issues/12094/issue-12094.test.ts[R12-16]

+describe("github issues > #12094 upsert must not mutate input entities", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
Evidence
All newly added regression coverage is under the per-issue test directory, and the diff adds no
corresponding test under packages/typeorm/test/functional.

Rule 3: Prefer functional tests over per-issue tests
packages/typeorm/test/github-issues/12094/issue-12094.test.ts[1-12]
packages/typeorm/test/github-issues/12094/issue-12094.test.ts[25-84]

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 issue regression tests were added only under `packages/typeorm/test/github-issues`, contrary to the project requirement that issue fixes stay in the functional test suite.
## Fix Focus Areas
- packages/typeorm/test/github-issues/12094/issue-12094.test.ts[1-86]
- packages/typeorm/test/functional/*[1-1]
## Recommended Fix
Move or recreate the three regression cases under an appropriate directory in `packages/typeorm/test/functional`, and include a comment referencing issue 12094 where applicable. Remove the per-issue-only coverage if the functional tests fully replace it.

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



Remediation recommended

3. Test data bypasses type checking ✓ Resolved

Resolving commit: ff62340

Resolution reason
The any-typed input at the flagged location was replaced: the test now declares `const input:
QueryDeepPartialEntity<Order> = { reference: "ref-1", meta: {} }` (typed via the entity's type,
using QueryDeepPartialEntity rather than plain Order/inferred type). This removes the any bypass
while keeping the embedded meta value.
Description
The embedded-value test declares its input as any, bypassing compile-time validation instead of
using the entity's type. This masks incorrect property shapes in the new regression case and makes
failures depend only on runtime behavior.

4. Upserts fail for read-only embedded values ✓ Resolved

Resolving commit: ff62340

Resolution reason
The assignment target[embedded.propertyName] = embeddedClone was replaced with
Object.defineProperty, which defines an own writable/enumerable/configurable data property on the
clone, so a getter-only embedded no longer throws. A regression test (ReadonlyMetaOrder entity with
getter-only embedded, upserted and asserted to return an id) was added. This matches the suggested
fix (define an own data property on the clone, add a getter-only regression test).
Description
cloneEmbeddeds() assigns a replacement object to the mapped embedded property, even when that
property is a getter without a setter. For an entity with a getter-backed embedded value, the upsert
query has already executed when this assignment throws, so the call rejects before returning its
result.

5. Upserts still mutate embedded input values ✓ Resolved
Description
ReturningResultsEntityUpdator.insert() uses OrmUtils.cloneObject() for upserts, but that shallow
copy shares embedded objects with the caller's entity. When a generated or returned embedded column
is merged into the clone, the column setter writes through the shared object and changes the
caller's input.

View review recommended (1)
6. Upsert callbacks lose generated entity IDs ✓ Resolved
Description
ReturningResultsEntityUpdator.insert() now merges generated values into clones, but
InsertQueryBuilder.execute() still broadcasts after-insert events using the original value sets.
When an upsert input has no generated ID, after-insert listeners and subscriber event.entity no
longer receive that ID, even though the returned InsertResult contains it.

Grey Divider

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

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

Qodo Logo

Address review feedback on the upsert input-mutation fix:

- after-insert listeners/subscribers were given the original (now
  un-mutated) value sets, so upsert callbacks no longer saw the generated
  id. The updator now returns the entities carrying the generated values
  (the clones for an upsert, the originals otherwise) and execute()
  broadcasts those, so listeners still receive the id while the caller's
  objects stay untouched.
- OrmUtils.cloneObject is shallow, so embedded objects were still shared
  by reference and merged into in place. Clone the embedded tree as well
  (never following relations, so no cyclic traversal).

Adds tests covering the after-insert listener and embedded cases.
@ElwinErnst

Copy link
Copy Markdown
Author

Addressed the review in 812c4980:

  • Upsert callbacks losing generated ids (correctness): the after-insert broadcast was using the original value sets, which are no longer mutated for upserts. ReturningResultsEntityUpdator.insert() now returns the entities carrying the generated values (the clones for an upsert, the originals otherwise) and execute() broadcasts those. Listeners and subscribers still receive the generated id while the caller's objects stay untouched. Added a test with an @AfterInsert listener.
  • Embedded values still mutated (correctness): OrmUtils.cloneObject is shallow, so embedded objects were shared by reference and merged into in place. The clone now also clones the embedded tree (following only embeddeds, never relations, so no cyclic traversal). Added a test with an embedded column default.

On the two rule-violation notes: the behavior change (generated ids are read from the returned InsertResult rather than written back onto the input) is called out in the PR description and commit message; happy to add a docs note if maintainers prefer. I kept the test under test/github-issues/12094/ to match the established convention for issue-specific regression tests.

…of any

The typeorm#12094 embedded-mutation regression declared its upsert input as `any`,
bypassing compile-time checks. Use QueryDeepPartialEntity<Order>, the type
upsert actually accepts, so an invalid input shape fails the build.
Document that generated values are no longer written back onto the input
objects and must be read from the returned InsertResult.
… when cloning for upsert

cloneEmbeddeds replaced each embedded via target[propertyName] = clone. The
upsert clone keeps the entity prototype, so for an embedded exposed through a
getter-only accessor the assignment threw (TypeError: Cannot set property which
has only a getter) after the insert had already executed.

Define an own data property on the clone instead, which shadows the inherited
accessor and keeps the same result for writable embeddeds. Add a regression
with a getter-only mapped embedded.
@ElwinErnst

Copy link
Copy Markdown
Author

Thanks for the review. Pushed ff62340e4 which addresses the actionable findings:

  • Bug (read-only embedded values) — fixed. cloneEmbeddeds no longer assigns through the mapped property (which throws for a getter-only embedded after the insert has already run); it defines an own data property via Object.defineProperty instead. Covered by a ReadonlyMetaOrder regression case.
  • Rule 2 (docs) — added a note in 6-repository-api.md that upsert does not mutate input entities and that generated values must be read from the returned InsertResult.
  • Rule 4 (any in test) — the embedded-value input is now typed as QueryDeepPartialEntity<Order>; no any remains.

On Rule 3 (functional vs per-issue test): keeping this one under test/github-issues/12094/ on purpose. That is where this repo places issue regressions already (thousands of them), so moving it to test/functional/ would cut against the established convention rather than follow it. Happy to relocate if a maintainer prefers otherwise.

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

Compliance violation linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR

Development

Successfully merging this pull request may close these issues.

upsert() with MySQL mutates input entity objects in-place with wrong auto-increment IDs after ON DUPLICATE KEY UPDATE

1 participant