Repository navigation
perf(core): group reloaded rows by condition values in upsertMany - #8393
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
| }; | ||
| 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])) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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. */ |
There was a problem hiding this comment.
This ends up in the public API of an exported class, please mark it @internal (same as getEntityComparator).
| const tmp: Dictionary = {}; | ||
| add.forEach(k => { | ||
| const prop = meta.properties[k]; | ||
| const comparableRows = data2.map(row => { |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
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
|
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 |
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.
|
Added 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 While writing the test I ran into two cases that also fail on
I can open issues for those if that's useful. |
…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.
This affects
upsertManyonly when it has to reload rows to fill in primary keys: on platforms withoutRETURNING(MySQL, MariaDB), or withonConflictAction: 'ignore'. Batches of 100 rows or fewer see no measurable change.When that reload runs, each entity in
loadPKlooks up its row withdata2.find(...). Each lookup builds the comparable object for every row and runscomparator.matchingagainst it. That is O(batch²) comparator calls per batch (batchSizedefaults to 300).This change builds the comparable rows once. When every condition key is a property the comparator checks with
!==(scalarstring/number/bigint, nocompareValues), it groups the rows by those values.matchingthen runs only on the rows in the group with the same values.matchingaccepts has values identical to the condition, so it always lands in that group. The first matching row is the same one as before.EntityComparator.isStrictlyCompared(prop)mirrors the type selection ingetPropertyComparator, so the strict-equality rule is defined next to the comparator.Where it matters
Below is
em.upsertMany(User, rows, { onConflictFields: ['key'] })on SQLite withusesReturningStatement()mocked tofalse, the same wayupsert-many-managed-rows.sqlite.test.tssimulates 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: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
master.GH5668,partial-returned-rows("matches mixed inserted, updated and suppressed rows to their entities") andupsert-many-managed-rows("RETURNING supported: false > hydrates generated primary keys and defaults only into SQL inputs").masterexactly: they are the suites that need MySQL, Postgres and other databases I don't have running locally.tsc --noEmit -p packages/core,oxfmtandoxlintare clean.The second lookup a few lines below (
loadPK.size !== data2.length, matching onuniqueFields) 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