Add returning() to queryset update() and delete() #85
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 #85"
general
weight: 0.35
davegaeddert
What
Adds a queryset-chain API for Postgres
RETURNINGon set-based writes:returning()is a queryset clone method set before the write, so the SQL is fully known before execution.Behavior changes
Three things that a caller who never touches
returning()can still hit. Release-note wording:update()ordelete()outside a transaction now raisesTransactionManagementError. It previously ran unlocked — neither statement takes a locking clause, sofor_update(...)on a set-based write was silently dropped. The write is now emitted as a locking sub-select, which needs an opentransaction.atomic()exactly like a locked read does. Wrap the write inatomic().update()ordelete()now emitsWHERE id IN (SELECT ... FOR UPDATE ...)instead of a flat statement. Still one statement; the rowcount and returned rows are unchanged. Code asserting on generated SQL for locked writes will need updating..values().update()now raisesTypeError. It previously ignored the.values()silently.delete()already raised; the two agree now. (.distinct().update()still succeeds silently —delete()guards it,update()doesn't. Unchanged here, worth its own decision.)Semantics
returning()->RETURNINGall concrete columns -> list of model instances (converters applied). Forupdate()these reflect post-update values and stay live. Fordelete()they are read-only snapshots — every value is there to read, the id included, but the row is gone, socreate()/update()/delete()on them raise. (The opposite ofModel.delete(), which clears the id and leaves the instance re-creatable: that is a row you still hold, while a snapshot records one that was removed.)returning(fields: Field[Any]) ->RETURNINGthose columns -> list of dicts keyed by field name. Fields are typed references (Event.id, not"id"); a string raisesTypeError, a field from another model raisesFieldError, and a relation attribute raisesFieldError— forward FK, many-to-many and reverse accessor alike, since at class level each is its descriptor, which is what letswhere()traverse it; columns come back through no-argreturning(). Validated at thereturning()call, not when the write runs.returning()is inert for reads. It describes what the next write hands back, so iterating,count(),first()andvalues()on the same queryset behave exactly as without it — which is what lets you inspect a chain before writing it.returning()->update()/delete()return anintexactly as before.returning()only applies toupdate()anddelete(). Any other write on the same queryset —create(),bulk_create(),bulk_update(),get_or_create(),update_or_create()— raisesTypeErrorrather than silently dropping it.returning()keeps the queryset's own class, so a customQuerySetand its methods survive it in either order.|and&carry the returning state from either side, since the combined query emits oneRETURNINGclause. Two different selections raiseTypeErrorrather than letting the left one silently win; selections are compared by the columns they name, so a queryset still combines with its owndeepcopy().RETURNINGonly reports the statement's own target-table rows; cascade-deleted children never appear.update()runs no Python-side field hooks, so anupdate_now=Truetimestamp comes back unchanged unless theupdate()set it.WHERE id IN (subquery).RETURNINGsurvives that rewrite and it stays a single statement, on bothupdate()anddelete().Row locks
A lock belongs on the read side of the write — that pairing is the job-claim pattern:
One statement. A second worker running the same write skips the rows the first one holds instead of blocking on them, so each row is claimed once.
Note the scope: this claims every row the filter matches, so it suits draining a batch, not handing one unit of work to one worker. A bounded claim needs a sliced write and
update()/delete()reject a sliced queryset — a per-worker claim still wants the locked read (for_update(skip_locked=True)+first()) and a separate write.bulk_update()drops the lock rather than routing every batch through a sub-select: its batches target rows by id, which the caller already holds, so the lock has nothing left to guard.A locked write locks only the target table's rows. When the filter spans a relation the sub-select joins the other tables to look values up, and a bare
FOR UPDATEwould lock a row in each — so a write filtering on a parent would wait on (or, withskip_locked=True, silently skip) rows it never touches. The clause is emitted asFOR UPDATE OF <target>. To lock related rows as well, take them with a separate locked read.That is also why
of=can only name"self"on a write: the sub-select reads one column — this table's id — andOFis resolved against the selected columns, so a related name has nothing to point at;update()/delete()raiseTypeErrorat the call rather than let it surface as aFieldErrorfrom the compiler. Droppingof=gets you the same lock. Reads are unchanged.Typing
returning()is declared to returnReturningQuerySet[T, R], whoseupdate()/delete()are typed-> R. Two overloads pinR: no-arg ->list[T], field refs ->list[dict[str, Any]]. The plainQuerySetkeepsupdate/delete->int.ReturningQuerySetis a static-only type — nothing is ever an instance of it. Runtime behavior is driven by the queryset's own state (_returning_fields/_returning_instances), soreturning()hands backself._chain()and a custom subclass survives. It is bound at runtime to a type alias soget_type_hints()and doc generators can still evaluate the annotations that name it.Every method that hands back the queryset it was called on says
-> Self, so the shape survives the chain:|,&,none(),defer(),only(),reverse(), and the rest.|and&also take overloads so the shape is right whenreturning()is on the right-hand operand.values()/values_list()stayQuerySet[Any]— they change the element type, soSelfwould be a different lie.The trade: a custom method reads cleanly before
returning()and needsisinstance()narrowing after it. "Self, but withupdate/deleterebound toR" isn't expressible in Python's type system. Both orders work at runtime, and the shapes plus this narrowing rule are asserted inplain-postgres/tests/typing/returning_writes.py.Implementation
UpdateQuery/DeleteQueryasreturning_fields, emitted viadialect.returning_columns()and converted by the sharedcompiler.convert_returning_rows()— the same helpers the insert path uses.SQLWriteCompilerbase that runs the statement once and asserts the result type isCURSORorNO_RESULTS.QuerySet.update()/delete(), next to the state it reads. "Didreturning()run?" isis Noneat every layer, andreturning()is the only place a selection is built — neither of its branches can make an empty one, which is what the write path depends on.SQLUpdateCompiler.pre_sql_setup()no longer early-returns on a single active table, andSQLDeleteCompiler.as_sql()no longer takes the single-alias shortcut, when the query carries alock_mode.ModelStategrows adeletedflag, set on the instances the delete path hydrates;create(),update()anddelete()all check it first, so the three give one explanation rather than two.convert_returning_rows(and no longer copies each row into a list when no converters apply).Notes for reviewers
ReturningQuerySetis not a runtime export — it is a type-only name with a runtime alias. #89'sRowQuerySethas the same__class__-swap shape and should follow this pattern (not changed here); #89's-> Selfsweep overnone()/__and__is spelled the same way here so the merge collapses. Other internal moves:SQLWriteCompileris the base for write compilers,QuerySet._raw_delete()takes no arguments, and_hydrate_returning(rows, , deleted=False)sits onQuerySet.SQLInsertCompiler.execute_sql(returning_fields=...)) and on the query for UPDATE/DELETE. Moving insert's ontoInsertQuerywould make all three symmetric and drop onety: ignore, but it changes a signature #88 builds on — better decided together with that PR.plain-jobs' job claim is reachable in principle now that the lock composes, but it also wants a bounded write and both writes still refuse a sliced queryset.Tests
plain-postgres/tests/public/test_returning.py— return shapes, converters, validation errors, empty results, FK cascade, the join rewrite on both writes, the writes that must rejectreturning(), custom-queryset survival in both chain orders, combining via|/&/none()including the mismatch error, deleted-row snapshots refusing all three writes, reads being unaffected, and both locked writes refusing to run outside a transaction.plain-postgres/tests/public/test_row_locking.pyalso covers the write side: the lock lands in the sub-select and names only the written table,bulk_update()drops it,of=("self",)works on a joined write, and a relatedof=target is refused on the write while still working on the read. A second two-session test holds a joined-to parent row from another connection and asserts the locked write still claims its own row.Locking is tested twice over: SQL-shape assertions that the clause sits inside the sub-select (
test_row_locking.pyfor plain writes,test_returning.pyfor returning ones), and a real two-session race — the captured statement replayed on two raw psycopg connections with the first holding its transaction open, asserting the claimed row sets are disjoint. Without the fix the second session dies onlock_timeout.plain-postgres/tests/internal/test_returning_internals.pypins the invariants the layers depend on: annotations resolve at runtime, and the write compiler rejects row-shaping result types.Static claims live in
plain-postgres/tests/typing/returning_writes.py../scripts/fix,./scripts/type-check .,./scripts/test plain-postgres(1121 passed, 5 skipped), and the full./scripts/testall pass.