← Back to Pull requests

Add bulk_upsert() and make bulk_create insert-only #86

Closed
unknown closed this pull request without merging on Sep 20, 2026 02:57 UTC
View on GitHub
unknown unknown commented on Jul 23, 2026 16:33 UTC
Author

What

Adds QuerySet.bulk_upsert() — a clearly-named, RETURNING-backed replacement for the old bulk_create(update_conflicts=True, ...) surface — and narrows bulk_create to insert-only.

Stacked on the returning branch.

API

QuerySet.bulk_upsert(
    objs,
    *,
    update_fields: Sequence[Field[Any] | type[Model]],
    unique_fields: Sequence[Field[Any] | type[Model]],
    batch_size=None,
) -> list[T]

update_fields and unique_fields take 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 raises TypeError/FieldError at the call, before any batch is issued.

A foreign key is named by the relation itself: unique_fields=[Model.tenant, Model.slug] against UniqueConstraint(fields=["tenant", "slug"]). Model.tenant is a ForwardForeignKeyDescriptor at runtime and type[Tenant] to the checker — that's what makes where() traversal work, and Model.tenant.id would 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 is Field[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 (use returning() with no arguments for that), whereas a column list can only mean the column.

Both parameters are Sequence, not list. list is invariant, so a hoisted conflict target — fields = [M.tenant, M.slug], which infers list[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. Like bulk_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 UPDATE returns 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 (objs itself is untouched).

Row association by position

bulk_create() maps RETURNING rows onto objects by position, and bulk_upsert() does the same, on the DO UPDATE path 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.py rather 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 as bulk_create does.

Objects that already carry an id

They split the way bulk_create() splits them: one carrying an id inserts 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 id is kept; on the conflict path the stored row's id is hydrated back. A conflicting row already exists and already has an id — the table is the truth, not the object. An id that collides with a different row raises psycopg.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 an id go 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_size caps the statement within a run.

objs itself 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_value once (a TimeZoneField's ZoneInfo becomes its name, a naive datetime becomes aware, a malformed value is rejected before any statement goes out), then conflict_sort_value renders it as a string, canonicalizing every spelling Postgres holds equal but str() does not:

| value | rendered as | because |
|---|---|---|
| a str subclass (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 — a bytea key sorted nondeterministically |
| an aware datetime | converted to UTC | timestamptz stores the instant, not the offset it was written at |
| a float | repr(value + 0.0) | folds -0.0 into 0.0 |
| a Decimal | normalize(), sign-folded | numeric holds Decimal("1.0") and Decimal("1.00") equal |
| a jsonb container | encoded with the field's encoder, then re-parsed and dumped with sort_keys=True | object keys are strings by then, so sorting them can't compare an int to a str |

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 ValueError naming 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_fields must name the primary key, or a condition-free / expression-free UniqueConstraint declared on the model (checked via Options.unique_fields_match_constraint, which matches against total_unique_constraints). A unique Index is not a conflict target — declare a UniqueConstraint. Clear error naming the model and fields otherwise.

  • update_fields must be concrete, non-PK, must not name the same column twice (Postgres assigns each column once per statement), and must not overlap unique_fields. A database-owned column (create_now, generate=True, RandomStringField) can't be named either — EXCLUDED carries a freshly evaluated default, so naming one would reset a creation timestamp on every update. A column that is also update_now is exempt.

  • Every object must have a non-null value for every unique field — NULL never conflicts in Postgres, so the row would always insert and the upsert would silently be an insert.

  • A unique field can't be a database-generated column (create_now, generate=True, RandomStringField), nor an update_now column. 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.

  • Duplicate conflict keys are handled at the statement level rather than up front — see above.
  • update_now columns are refreshed automatically

    A conflicting row is written with the named update_fields plus every update_now column on the model, deduplicated. pre_save stamps the in-memory object on the way in and EXCLUDED carries that same stamp to the row, so the stored row and the object handed back agree on when it was last touched — which is what update_now means. 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_create loses its update_conflicts / update_fields / unique_fields parameters and the top-level OnConflict plumbing behind them; it is now insert-only. OnConflict.IGNORE goes too — nothing ever passed it. The shared _batched_insert helper still threads on_conflict/update_fields/unique_fields through 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"]) becomes bulk_upsert(objs, update_fields=[Model.a], unique_fields=[Model.b]) — note the field references instead of strings, and that the model must declare a matching UniqueConstraint. Passing the old kwargs is now a TypeError (and a type error).

    Internal caller migrated

    plain.cache's set_many() switched from bulk_create(update_conflicts=True, ...) to bulk_upsert(update_fields=[model.value, model.expires_at], unique_fields=[model.key]) — it no longer names updated_at, since bulk_upsert refreshes it. Same single statement, same columns, same timestamp behavior; its suite, including the created_at-preserved invariant, is unchanged. No other update_conflicts usages 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_fields scoping, by-key matching when every row conflicts, returned order, composite unique_fields (via the new UpsertPair fixture, unique on (bucket, slug) and on neither alone), batching, empty input, update_now refreshed 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_now unique value, database-generated update field, duplicate keys, overlapping fields, string field, wrong-model field). A bulk_create test asserts the conflict kwargs now raise TypeError.

    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) and UpsertFloatKey (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.py adds the static half: bulk_upsert returns list[T], takes field references rather than strings, accepts a Model.fk reference, and bulk_create has no conflict kwarg.

    plain-cache's suite still passes after the migration. Full ./scripts/test, ./scripts/type-check ., and ./scripts/fix are green.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: davegaeddert Review duration: 84143m
    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
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    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
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository