Skip to content

perf(core): group reloaded rows by condition values in upsertMany - #8393

Merged
B4nan merged 3 commits into
mikro-orm:masterfrom
irontaek:perf/upsert-many-reload-lookup
Oct 5, 2026
Merged

B4nan merged 3 commits into
mikro-orm:masterfrom
irontaek:perf/upsert-many-reload-lookup

Conversation

@irontaek

@irontaek irontaek commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

This affects upsertMany only when it has to reload rows to fill in primary keys: on platforms without RETURNING (MySQL, MariaDB), or with onConflictAction: 'ignore'. Batches of 100 rows or fewer see no measurable change.

When that reload runs, each entity in loadPK looks up its row with data2.find(...). Each lookup builds the comparable object for every row and runs comparator.matching against it. That is O(batch²) comparator calls per batch (batchSize defaults to 300).

This change builds the comparable rows once. When every condition key is a property the comparator checks with !== (scalar string/number/bigint, no compareValues), it groups the rows by those values. matching then runs only on the rows in the group with the same values.

  • Any row that matching accepts has values identical to the condition, so it always lands in that group. The first matching row is the same one as before.
  • Conditions with other keys, or with non-primitive values, keep the full scan.
  • EntityComparator.isStrictlyCompared(prop) mirrors the type selection in getPropertyComparator, so the strict-equality rule is defined next to the comparator.

Where it matters

Below is em.upsertMany(User, rows, { onConflictFields: ['key'] }) on SQLite with usesReturningStatement() mocked to false, the same way upsert-many-managed-rows.sqlite.test.ts simulates MySQL. Median of 9 runs; before and after were run alternately, three times each. My machine was noisy, so the absolute numbers moved a lot between rounds:

rows before (3 rounds) after (3 rounds)
100 28.1 / 7.1 / 11.4 ms 11.8 / 6.8 / 9.1 ms
300 94.0 / 18.6 / 39.3 ms 26.7 / 16.2 / 19.7 ms
1000 236.4 / 61.9 / 124.6 ms 88.5 / 42.2 / 54.9 ms
3000 735.8 / 174.4 / 324.6 ms 122.9 / 126.0 / 134.6 ms

Before the change, I also timed just this lookup loop inside upsertMany. It was 1–2 ms of 14–16 ms at 100 rows, 25–34 ms of 71–101 ms at 300, and 0.33–0.47 s of 0.9–1.0 s at 3000.

Tests

  • The upsert test files that run on SQLite pass: 179 tests, the same as master.
  • To check the new branch is really covered, I made the grouped lookup always miss. That breaks 3 existing tests: GH5668, partial-returned-rows ("matches mixed inserted, updated and suppressed rows to their entities") and upsert-many-managed-rows ("RETURNING supported: false > hydrates generated primary keys and defaults only into SQL inputs").
  • I also ran every test file that touches SQLite. The failures match master exactly: they are the suites that need MySQL, Postgres and other databases I don't have running locally.
  • tsc --noEmit -p packages/core, oxfmt and oxlint are clean.

The second lookup a few lines below (loadPK.size !== data2.length, matching on uniqueFields) has the same shape. I left it alone because it only runs when the reload returns a different number of rows.

https://claude.ai/code/session_01W9Mk18mBNfkPfgg3hYweKq

When upsertMany reloads rows to fill in primary keys (no RETURNING support,
onConflictAction: 'ignore'), every entity scanned all reloaded rows of the
batch with the entity comparator, which is O(batch size squared). When all
condition keys are compared with strict equality, group the rows by those
values once and run the comparator only on the rows in the matching group.
Other conditions keep the full scan.
@codecov

codecov Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.66%. Comparing base (39599a7) to head (f4872a3).

Additional details and impacted files
@@           Coverage Diff            @@
##           master    #8393    +/-   ##
========================================
  Coverage   99.66%   99.66%            
========================================
  Files         293      293            
  Lines       32000    32028    +28     
  Branches     9011     8625   -386     
========================================
+ Hits        31894    31922    +28     
  Misses        102      102            
  Partials        4        4            

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread packages/core/src/EntityManager.ts Outdated
};
const findRowIndex = (cond: Dictionary) => {
const keys = Utils.keys(cond) as EntityKey<Entity>[];
const key = keys.every(k => meta.properties[k] && this.#comparator.isStrictlyCompared(meta.properties[k]))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The comparator skips props that aren't in meta.comparableProps (version, discriminator, persist: false, generated columns). The old scan ignored such a condition key, this one groups on it. I couldn't come up with a case where the result differs, but please check meta.comparableProps here too, so the grouping can never be stricter than matching.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 2224195. Grouping now only uses keys whose prop is in meta.comparableProps and is compared with !==, otherwise it falls back to the full matching scan, so it can't be stricter than the comparator. The upsert suites still pass, and breaking the grouped lookup still fails the same 3 tests, so the common path (unique scalar onConflictFields) still takes the grouping.

return Utils.callCompiledFunction(comparator, a as T, b as T, options);
}

/** Returns true if the comparator checks this property with `!==`, so matching values are identical primitives. */

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This ends up in the public API of an exported class, please mark it @internal (same as getEntityComparator).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Marked @internal in 2224195.

Comment thread packages/core/src/EntityManager.ts Outdated
const tmp: Dictionary = {};
add.forEach(k => {
const prop = meta.properties[k];
const comparableRows = data2.map(row => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This converts every reloaded row even when loadPK is empty (e.g. upserts with explicit PKs, where the reload only fetches defaults). The old code did nothing in that case. Can you build it lazily, or wrap the block in if (loadPK.size > 0)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Wrapped the whole block in if (loadPK.size > 0) in 2224195, so nothing is converted when the reload only fetches defaults.

- only group on props in meta.comparableProps, so grouping is never
  stricter than matching()
- mark isStrictlyCompared as @internal
- skip building comparable rows when loadPK is empty
@B4nan

B4nan commented Oct 5, 2026

Copy link
Copy Markdown
Member

Thanks for the quick fixes. One more thing before merging: codecov reports 3 uncovered lines in the patch, and we keep the coverage complete. I think those are the non-grouped paths (the full scan fallback and the rows without a group key). Please add a test under tests/features/upsert/ that covers them, e.g. upsertMany on a driver without returning statement support, with a unique key that includes a Date, boolean or nullable column.

Add a test for a date unique key, which takes the full scan fallback.
Simplify the grouping so every row gets a key (null and undefined share
one, which can only widen a group), leaving no branch that a unique key
can never reach.
@irontaek

irontaek commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Added tests/features/upsert/upsert-many-reload-matching.sqlite.test.ts in f4872a3. It runs upsertMany with a date unique key and no RETURNING support, so it covers the full-scan fallback.

The other two lines were the row-without-a-group-key branch and pushing a second row into an existing group. I couldn't reach either with an upsert that works today: rows are unique on the condition keys, and a null in the key already fails before this code runs (see below). So I simplified the grouping instead. Every row now gets a key, and null/undefined share one, which can only widen a group, never narrow it. With v8 coverage on the upsert suites, no statement in the block is uncovered locally.

While writing the test I ran into two cases that also fail on master, independent of this PR:

  • On a nullable unique column, an input with null there gets the condition {} and throws Cannot find matching entity for condition {}.
  • When inputs in one batch pick different unique keys (e.g. one by code, another by [day, active]), add collects all of those keys. The comparable row then carries keys the condition doesn't have, and matching rejects it.

I can open issues for those if that's useful.

@B4nan B4nan left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

thanks

@B4nan
B4nan merged commit 33236ce into mikro-orm:master Oct 5, 2026
26 checks passed
@B4nan

B4nan commented Oct 5, 2026

Copy link
Copy Markdown
Member

While writing the test I ran into two cases that also fail on master, independent of this PR:

See #8396 and #8397

B4nan added a commit that referenced this pull request Oct 6, 2026
…ted rows (#8397)

`em.upsertMany()` threw `Cannot find matching entity for condition {}`
when a row had `null` in its unique key and the batch had to be reloaded
to get the primary keys: always on MySQL/MariaDB (no `RETURNING`), and
on the other SQL drivers with `onConflictAction: 'ignore'` or
`onConflictWhere`. When every row had a `null` key, it could instead
return entities hydrated from an unrelated row. Reported in the review
of #8393.

A `null` unique value never conflicts, so the row is always inserted,
but there is nothing to find it by afterwards. When the returned rows
cannot be mapped by position, such rows now go through `em.upsert()`,
which reads the primary key from the insert result. That costs one
insert and one select per `null`-key row on those paths. Entities with
an autoincrement PK and no unique key keep the single batch statement,
and so does MongoDB, which already inserts such rows as part of the
batch. The rows that stay in the batch are reloaded by the primary key
the insert reported, not by the unique fields of the first row.

`em.upsert()` had the same problem with explicit `onConflictFields` when
the row had to be reloaded: the reload ran with an empty condition and
hydrated the entity from an arbitrary row. It now falls back to the
primary key.

Two more shapes ended up on an unrelated row in both methods: a
composite PK that is only partially in the data, and a PK generated by a
database default (not autoincrement) that is missing in the data. A PK
missing in the data is now part of the returned columns, so with
`RETURNING` or `OUTPUT` the entity gets the row that was written.

TPT children were affected as well. The child table targeted the parent
row found by the (null) unique key, which was an unrelated row. The SQL
driver now takes the PK of such a row from the parent insert and reports
it, and `em.upsertMany()` sends those rows through `em.upsert()` one by
one, since a child table cannot return its rows. A direct driver call
with more than one such row in a batch is refused.

One behaviour change: when there is nothing to find the row by (no PK,
no non-null unique value, no `RETURNING`), the SQL drivers now throw
instead of hydrating the entity from an unrelated row. The statement has
already run by then, so the row is written unless the call is inside a
transaction.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants