← Back to Pull requests

Add returning() to queryset update() and delete() #85

Closed
unknown closed this pull request without merging on Sep 20, 2026 02:31 UTC
View on GitHub
unknown unknown commented on Jul 23, 2026 15:49 UTC
Author

What

Adds a queryset-chain API for Postgres RETURNING on set-based writes:

# No args -> RETURNING every concrete column -> list of hydrated model instances
running = Job.query.filter(status="pending").returning().update(status="running")

# Field refs -> RETURNING those columns -> list of dicts
deleted = Event.query.filter(created_at__lt=cutoff).returning(Event.id, Event.payload).delete()

# Unchanged: int rowcount when returning() is not used
n = Job.query.filter(...).update(status="x")

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:

  • A locked update() or delete() outside a transaction now raises TransactionManagementError. It previously ran unlocked — neither statement takes a locking clause, so for_update(...) on a set-based write was silently dropped. The write is now emitted as a locking sub-select, which needs an open transaction.atomic() exactly like a locked read does. Wrap the write in atomic().

  • A locked update() or delete() now emits WHERE 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 raises TypeError. 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

  • No-arg returning() -> RETURNING all concrete columns -> list of model instances (converters applied). For update() these reflect post-update values and stay live. For delete() they are read-only snapshots — every value is there to read, the id included, but the row is gone, so create()/update()/delete() on them raise. (The opposite of Model.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]) -> RETURNING those columns -> list of dicts keyed by field name. Fields are typed references (Event.id, not "id"); a string raises TypeError, a field from another model raises FieldError, and a relation attribute raises FieldError — forward FK, many-to-many and reverse accessor alike, since at class level each is its descriptor, which is what lets where() traverse it; columns come back through no-arg returning(). Validated at the returning() call, not when the write runs.

  • returning() is inert for reads. It describes what the next write hands back, so iterating, count(), first() and values() on the same queryset behave exactly as without it — which is what lets you inspect a chain before writing it.

  • Without returning() -> update()/delete() return an int exactly as before.

  • returning() only applies to update() and delete(). Any other write on the same queryset — create(), bulk_create(), bulk_update(), get_or_create(), update_or_create() — raises TypeError rather than silently dropping it.

  • returning() keeps the queryset's own class, so a custom QuerySet and its methods survive it in either order.

  • Combining querysets:* | and & carry the returning state from either side, since the combined query emits one RETURNING clause. Two different selections raise TypeError rather than letting the left one silently win; selections are compared by the columns they name, so a queryset still combines with its own deepcopy().

  • RETURNING only reports the statement's own target-table rows; cascade-deleted children never appear.

  • The returned values are whatever the statement wrote. A set-based update() runs no Python-side field hooks, so an update_now=True timestamp comes back unchanged unless the update() set it.

  • Filtering across a relation rewrites the write to WHERE id IN (subquery). RETURNING survives that rewrite and it stays a single statement, on both update() and delete().
  • Row locks

    A lock belongs on the read side of the write — that pairing is the job-claim pattern:

    with transaction.atomic():
        claimed = (
            Job.query.filter(status="pending")
            .for_update(skip_locked=True)
            .returning()
            .update(status="running")
        )
    

    UPDATE "jobs" SET "status" = 'running'
    WHERE "id" IN (
        SELECT U0."id" FROM "jobs" U0 WHERE U0."status" = 'pending' FOR UPDATE OF U0 SKIP LOCKED
    )
    RETURNING ...
    

    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 UPDATE would lock a row in each — so a write filtering on a parent would wait on (or, with skip_locked=True, silently skip) rows it never touches. The clause is emitted as FOR 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 — and OF is resolved against the selected columns, so a related name has nothing to point at; update()/delete() raise TypeError at the call rather than let it surface as a FieldError from the compiler. Dropping of= gets you the same lock. Reads are unchanged.

    Typing

    returning() is declared to return ReturningQuerySet[T, R], whose update()/delete() are typed -> R. Two overloads pin R: no-arg -> list[T], field refs -> list[dict[str, Any]]. The plain QuerySet keeps update/delete -> int.

    ReturningQuerySet is 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), so returning() hands back self._chain() and a custom subclass survives. It is bound at runtime to a type alias so get_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 when returning() is on the right-hand operand. values()/values_list() stay QuerySet[Any] — they change the element type, so Self would be a different lie.

    The trade: a custom method reads cleanly before returning() and needs isinstance() narrowing after it. "Self, but with update/delete rebound to R" isn't expressible in Python's type system. Both orders work at runtime, and the shapes plus this narrowing rule are asserted in plain-postgres/tests/typing/returning_writes.py.

    Implementation

  • RETURNING selection is stored on UpdateQuery/DeleteQuery as returning_fields, emitted via dialect.returning_columns() and converted by the shared compiler.convert_returning_rows() — the same helpers the insert path uses.

  • Both write compilers inherit a SQLWriteCompiler base that runs the statement once and asserts the result type is CURSOR or NO_RESULTS.

  • The returning-aware branch sits directly in QuerySet.update() / delete(), next to the state it reads. "Did returning() run?" is is None at every layer, and returning() 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.

  • Locked writes: SQLUpdateCompiler.pre_sql_setup() no longer early-returns on a single active table, and SQLDeleteCompiler.as_sql() no longer takes the single-alias shortcut, when the query carries a lock_mode.

  • ModelState grows a deleted flag, set on the instances the delete path hydrates; create(), update() and delete() all check it first, so the three give one explanation rather than two.

  • No behavior changes to insert / bulk_create / upsert / bulk_update, though the insert path now shares convert_returning_rows (and no longer copies each row into a list when no converters apply).
  • Notes for reviewers

  • Stacked PRs (#86, #88, #89): ReturningQuerySet is not a runtime export — it is a type-only name with a runtime alias. #89's RowQuerySet has the same __class__-swap shape and should follow this pattern (not changed here); #89's -> Self sweep over none()/__and__ is spelled the same way here so the merge collapses. Other internal moves: SQLWriteCompiler is the base for write compilers, QuerySet._raw_delete() takes no arguments, and _hydrate_returning(rows, , deleted=False) sits on QuerySet.

  • Insert asymmetry, deliberately left: RETURNING fields live on the compiler for INSERT (SQLInsertCompiler.execute_sql(returning_fields=...)) and on the query for UPDATE/DELETE. Moving insert's onto InsertQuery would make all three symmetric and drop one ty: ignore, but it changes a signature #88 builds on — better decided together with that PR.

  • No in-tree consumers yet. 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 reject returning(), 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.py also 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 related of= 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.py for plain writes, test_returning.py for 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 on lock_timeout.

    plain-postgres/tests/internal/test_returning_internals.py pins 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/test all pass.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: davegaeddert Review duration: 84161m
    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 #85"
    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