Add bulk_upsert() and make bulk_create insert-only #86
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #86"
general
weight: 0.35
davegaeddert
What
Adds
QuerySet.bulk_upsert()— a clearly-named, RETURNING-backed replacement for the oldbulk_create(update_conflicts=True, ...)surface — and narrowsbulk_createto insert-only.Stacked on the
returningbranch.API
update_fieldsandunique_fieldstake typed field references (e.g.update_fields=[CachedItem.value],unique_fields=[CachedItem.key]), validated by a shared_validate_field_refs()— a string or a field from the wrong model raisesTypeError/FieldErrorat the call, before any batch is issued.A foreign key is named by the relation itself:
unique_fields=[Model.tenant, Model.slug]againstUniqueConstraint(fields=["tenant", "slug"]).Model.tenantis aForwardForeignKeyDescriptorat runtime andtype[Tenant]to the checker — that's what makeswhere()traversal work, andModel.tenant.idwould traverse to the related model's column rather than the foreign key — so these lists unwrap the descriptor to the column it stands for, and their element type isField[Any] | type[Model].This is the one write API that takes
Model.fk.returning()still refuses it: there the reference is ambiguous with asking for the whole related object (usereturning()with no arguments for that), whereas a column list can only mean the column.Both parameters are
Sequence, notlist.listis invariant, so a hoisted conflict target —fields = [M.tenant, M.slug], which inferslist[type[Tenant] | Field[str]]— would fail to type-check even though the identical literal written inline passes. A tuple works too.Issues one
INSERT ... ON CONFLICT (unique_fields) DO UPDATE SET col = EXCLUDED.col ... RETURNING ...per batch, wrapped in a single atomic transaction. Likebulk_create, the write is against the table — a filter on the queryset it's called from doesn't narrow or exclude anything. Every object comes back — both freshly inserted and conflict-updated rows — with its DB-returned fields (primary key, DB defaults) populated.DO UPDATEreturns all targeted rows, so updates are hydrated too, not just inserts.You get back the caller's objects, in the caller's order, in a new list (
objsitself is untouched).Row association by position
bulk_create()maps RETURNING rows onto objects by position, andbulk_upsert()does the same, on theDO UPDATEpath as much as the insert path. Postgres processes VALUES rows sequentially and emits one RETURNING row per row, so the rows come back in the order the objects were sent.Nothing in the SQL standard promises that, so it's pinned by
plain-postgres/tests/internal/test_returning_order.pyrather than assumed: 400 rows, every other key seeded so the batch is a shuffled mix of inserts and conflicting updates, asserted to return in the order sent. Both call sites carry a comment pointing at it — they stand or fall together.The hydration happens inside the transaction, with
assert len(returned_rows) == len(objs), exactly asbulk_createdoes.Objects that already carry an
idThey split the way
bulk_create()splits them: one carrying anidinserts with it, one without lets Postgres generate the identity value, each in a statement with its own column list.On the insert path a caller-set
idis kept; on the conflict path the stored row'sidis hydrated back. A conflicting row already exists and already has anid— the table is the truth, not the object. Anidthat collides with a different row raisespsycopg.errors.UniqueViolation, like any set-based write.Deadlock-avoidance ordering
Every object is sorted by its conflict key before anything is sent, so concurrent
bulk_upserts touching overlapping keys lock rows in the same order and can't deadlock. The sort spans the whole call, not each statement: objects carrying anidgo out in a statement of their own (see below), and sorting those separately would let two callers holding the same keys lock them as(a,b),(c,d)and(c,d),(a,b). A new statement starts only where the row shape changes as the sorted list is walked, so interleaved ids cost statements, never order.batch_sizecaps the statement within a run.objsitself is never reordered —sorted()runs over positions, is stable, and never compares the objects.The sort key only has to be two things: the same for a given logical key every time, and incapable of raising when compared. Each component goes through
get_prep_valueonce (aTimeZoneField'sZoneInfobecomes its name, a naive datetime becomes aware, a malformed value is rejected before any statement goes out), thenconflict_sort_valuerenders it as a string, canonicalizing every spelling Postgres holds equal butstr()does not:| value | rendered as | because |
|---|---|---|
| a
strsubclass (StrEnum,SafeString) |str.__str__(value)| it compares equal to the plain string the column stores, but renders itself differently || a
memoryview/bytearray|bytes|str(memoryview)is its address in memory — abyteakey sorted nondeterministically || an aware
datetime| converted to UTC |timestamptzstores the instant, not the offset it was written at || a
float|repr(value + 0.0)| folds-0.0into0.0|| a
Decimal|normalize(), sign-folded |numericholdsDecimal("1.0")andDecimal("1.00")equal || a
jsonbcontainer | encoded with the field's encoder, then re-parsed and dumped withsort_keys=True| object keys are strings by then, so sorting them can't compare anintto astr|The result is a plain string — one total order over everything, which can't raise.
Duplicate conflict keys
Two objects with the same key in one statement are a Postgres cardinality violation — it won't touch a row twice per statement — re-raised as a
ValueErrornaming the model and the key.Split across batches they're simply legal: the first inserts, the second updates, both objects are hydrated from their own returned row (the same row), and the later write wins.
Validation (at call time, before any query, even for an empty
objs)unique_fieldsmust name the primary key, or a condition-free / expression-freeUniqueConstraintdeclared on the model (checked viaOptions.unique_fields_match_constraint, which matches againsttotal_unique_constraints). A uniqueIndexis not a conflict target — declare aUniqueConstraint. Clear error naming the model and fields otherwise.update_fieldsmust be concrete, non-PK, must not name the same column twice (Postgres assigns each column once per statement), and must not overlapunique_fields. A database-owned column (create_now,generate=True,RandomStringField) can't be named either —EXCLUDEDcarries a freshly evaluated default, so naming one would reset a creation timestamp on every update. A column that is alsoupdate_nowis exempt.NULLnever conflicts in Postgres, so the row would always insert and the upsert would silently be an insert.create_now,generate=True,RandomStringField), nor anupdate_nowcolumn. In each case the caller doesn't control the value, so it could never conflict — the upsert would silently be an insert every time. These three guards are about the write, not about associating rows, so they survive position matching.update_nowcolumns are refreshed automaticallyA conflicting row is written with the named
update_fieldsplus everyupdate_nowcolumn on the model, deduplicated.pre_savestamps the in-memory object on the way in andEXCLUDEDcarries that same stamp to the row, so the stored row and the object handed back agree on when it was last touched — which is whatupdate_nowmeans. Callers never name them.(The deeper answer is a DB-side trigger for
updated_at; that's a separate future. This is the correct behavior until then.)bulk_create narrowing
bulk_createloses itsupdate_conflicts/update_fields/unique_fieldsparameters and the top-levelOnConflictplumbing behind them; it is now insert-only.OnConflict.IGNOREgoes too — nothing ever passed it. The shared_batched_inserthelper still threadson_conflict/update_fields/unique_fieldsthrough to_insert()per batch —bulk_upsert()is the only caller that now passes them. No deprecation shim — the upgrade agent fixes user code.Upgrade step:
bulk_create(objs, update_conflicts=True, update_fields=["a"], unique_fields=["b"])becomesbulk_upsert(objs, update_fields=[Model.a], unique_fields=[Model.b])— note the field references instead of strings, and that the model must declare a matchingUniqueConstraint. Passing the old kwargs is now aTypeError(and a type error).Internal caller migrated
plain.cache'sset_many()switched frombulk_create(update_conflicts=True, ...)tobulk_upsert(update_fields=[model.value, model.expires_at], unique_fields=[model.key])— it no longer namesupdated_at, sincebulk_upsertrefreshes it. Same single statement, same columns, same timestamp behavior; its suite, including thecreated_at-preserved invariant, is unchanged. No otherupdate_conflictsusages exist in the repo.Tests
Public tests in
plain-postgres/tests/public/test_bulk_upsert.py: insert-only, mixed insert/update batch (PKs + updated values),update_fieldsscoping, by-key matching when every row conflicts, returned order, compositeunique_fields(via the newUpsertPairfixture, unique on(bucket, slug)and on neither alone), batching, empty input,update_nowrefreshed without being named (the row's stamp advances and equals the hydrated object's), and each validation error (unmatched constraint, null unique value, database-generated unique value,update_nowunique value, database-generated update field, duplicate keys, overlapping fields, string field, wrong-model field). Abulk_createtest asserts the conflict kwargs now raiseTypeError.Fixtures added for the harder key shapes:
UpsertScoped(a foreign key inside a composite unique constraint),UpsertValueKey(a composite(payload jsonb, blob bytea, zone varchar)conflict key) andUpsertFloatKey(a float key, the column type that can hold NaN). Tests cover the FK in both column lists, a conflicting jsonb key written with its dict keys in the other order and a non-string object key, a jsonb key holding an object / a number / a string / an array in one call, a NaN key round-tripping, and two NaN keys detected as duplicates.plain-postgres/tests/typing/bulk_writes.pyadds the static half:bulk_upsertreturnslist[T], takes field references rather than strings, accepts aModel.fkreference, andbulk_createhas no conflict kwarg.plain-cache's suite still passes after the migration. Full
./scripts/test,./scripts/type-check ., and./scripts/fixare green.