← Back to Pull requests

Add typed select() for column selection #89

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

What

Adds QuerySet.select(items, flat=False, result_type=None) — typed column selection that returns honest rows (tuples, flat scalars, or dataclass instances) via a new RowQuerySet[R], never partial model instances.

User.query.where(...).select(User.id, User.email)       # RowQuerySet[tuple[int, str]]
User.query.select(User.email, flat=True)                # RowQuerySet[str]
User.query.select(User.id, User.email, result_type=UserStats)  # RowQuerySet[UserStats]

Stacked on typed-where (#84), which provides the typed field-access surface.

Vocabulary decision

select() and where() are the primary query API from here on. The string-based forms — values(), values_list(), only(), defer(), annotate(), filter() — remain in place and are untouched by this PR. They get swept in a follow-up slice; that sweep is deferred deliberately, not forgotten, and nothing here deprecates or removes them.

The sweep is set up to be a migration rather than a rewrite: select() is built on top of the existing _values_list plumbing (same _values → set_values path, same converters, same iterables), so the two produce identical SQL and identical row values. The one thing that can't invert is direction — values_list() accepts bare strings, which select() deliberately rejects — so consumers move to select() and then values_list() goes away, not the other way round.

Design

  • Selectable[T] base — Field[T] and F/BaseExpression subclass a shared generic marker so select() can bind each column's value type. It's a bare class Selectable[T]: pass; a checker solves T from Field[str] <: Selectable[T] by specializing the base class, so the marker needs no members.

  • Rows, not instances — everything that reads rows is inherited from QuerySet. RowQuerySet adds only the refusals and, under TYPE_CHECKING, the R the base can't carry.

  • Fields resolve by name; expressions get internal auto-aliases via the existing values_list plumbing. result_type maps columns onto dataclass fields positionally (arity + field-name checks at select() time).

  • Row mode is row mode, whoever entered it — update() now carries the same _fields is not None guard delete() already had, so values(), values_list() and select() all refuse writes. Previously values("name").update(...) silently ran.

  • select() goes last in a chain. Anything that would change the SELECT list afterwards is refused: values(), values_list(), only(), defer() and select_related() already raised, and annotate() now joins them (annotate first, then select()). Re-selecting is last-wins for the column list — expression columns included, which take the internal annotate path rather than the guarded public one. Joins introduced by an earlier expression persist, so select(Upper("tags__name")).select(Widget.name) still returns one row per joined row and count()/exists() count those. That is annotate(...) + values_list(...) behaving as it always has; trimming joins no queryset needs any more is out of scope here, and noted in the README.

  • A column belongs to the model whose field built it. Order.query.select(User.email) raises TypeError naming both models — the select() half of the guard #133 gave where(), reusing the Field.source_model it added. The check runs ahead of the traversal refusal, so a traversed column rooted on another model is reported as the cross-model mistake it is. Expressions are unaffected — F("email") takes a string resolved against whatever query it lands in, like filter()'s kwargs.

  • prefetch_related() is refused in both orders. A prefetch attaches related objects to a model instance's attributes, and a row has nowhere to put them. Select the columns you need from the related model instead.

  • result_type columns map onto the constructor, read off inspect.signature() rather than dataclasses.fields() — the two disagree in both directions, since an InitVar is a constructor parameter that never appears in fields() and an init=False field appears there but can't be passed. Each value is passed by the kind its parameter takes: positional-only and positional-or-keyword by position, keyword-only by name.

  • Chaining methods are annotated Self, not QuerySet[T] — otherwise RowQuerySet[R], which specializes its base as QuerySet[Any], drops R through reverse(), none(), order_by() and friends. That fix lives in the base QuerySet and also stops a custom queryset subclass being erased mid-chain.
  • Typing

    The overload ladder is keyed on Selectable[T] itself. Pure-field selects get precise per-column types; a select that mixes in an expression types that expression's column as Any while the fields around it stay precise — e.g. select(D.priority, Upper("name")) → RowQuerySet[tuple[int, Any]].

    A column annotated Field[Any] is rejected by select(): Any satisfies the model-valued __get__ overload, so class access resolves as type[Any] rather than a field and no overload matches. That is the same reason the field-annotation guidance says never to annotate a field Field[Any] — use the concrete type, or Field[object] when the column really does hold arbitrary JSON, which select() types as object. No code change; noted here and in the README because the diagnostic (a fourteen-overload no-matching-overload dump) doesn't explain itself.

    The ladder runs to ten columns; an eleventh still works but degrades to tuple[Any, ...]. All ten rungs are hand-written with no codegen, so tests/typing/select_ladder.py asserts every one of them against a model with ten distinctly typed columns — a transposed typevar in a middle rung can't ship silently. (Verified the hard way: transposing two typevars in the six- and eight-column rungs each fires a type-assertion-failure now, and passed clean before the file existed.)

    Not in this slice

    Relations are not selectable. select(Post.author), select(Post.author.city) and select(Post.author.id) all raise TypeError. The reason is nullability, not effort: a column reached through a relation arrives over a join, so a nullable relation yields None where the traversed field's type says int/str. That includes the foreign key's own column. values_list("author__id", flat=True) is the spelling until select() can express it, and the error message names it.

    A custom QuerySet subclass is not preserved — select() hands back a plain RowQuerySet, so chain your own methods before select(), not after. Documented in the README.

    Known gaps (follow-up, not introduced here)

  • Traversed columns type-check but fail at runtime. Post.author.id is Field[int] to a checker whether it was traversed or not, so the runtime refusal is the only guard. Closing it statically needs Selectable to carry model identity.

  • result_type mode allocates one tuple per row that it immediately unpacks and discards (tuple_expected=True in the shared values_list path).
  • Tests / checks

    ./scripts/fix, ./scripts/type-check . and the full ./scripts/test are green — 27 packages, 0 failures, 1371 passed / 5 skipped in plain-postgres (88 in test_select.py).

    Rebased on master after #133 merged; the merge also gave master's four lock methods (for_update() and friends, from #87) the same Self treatment as the rest of the chaining surface, so rows.for_update() keeps its row type.

    (One plain-dev test, test_nested_app_directories_do_not_collide_across_worktrees, fails in my environment because it shells out to git commit and the signing agent is locked. It reproduces on pristine master with no changes, so it is environmental and unrelated.)

    Every column kind was exercised against a live database: encrypted (decrypts), JSON, Decimal/UUID/date/time/duration/bool/choices, timezone-aware datetimes (all converters correct — the values_list path is reused wholesale), plus distinct(), order_by on an unselected column, annotate before select, filter/where after, slicing, get() with 0/2 rows, first() on empty, exists(), count(), iterator(), pickling, and select() twice.

    Review follow-ups

    Both Codex findings are fixed and their threads resolved:

  • P1 — annotate() after select() appended a column under the declared row type: silently for tuples (RowQuerySet[tuple[str]] yielding ("alpha", 1)), as a confusing constructor error for result_type=, and silently dropped for flat=. Refused now, naming the supported order. 0bb3f36523

  • P2 — result_type arity was read off dataclasses.fields(), which omits InitVar constructor parameters and includes init=False fields. Now read off inspect.signature(). 86feed2111
  • Round two:

  • A result_type constructor mixing positional-only and keyword-only parameters (__init__(self, name, /, , priority)) validated and then failed, because every value was passed by keyword. The row now splits by parameter kind at a single point computed once per query. a4474208c1

  • Inherited methods annotated -> QuerySet[T] dropped the row type on RowQuerySet[R] (and erased custom queryset subclasses generally). Swept to Self in the base. 5ce62e9400
  • Round three:

  • select() twice with an expression (select(D.name).select(F("priority"))) raised Cannot call annotate() after select(), because _values_list aliases expression columns by calling the public annotate(), which RowQuerySet refuses. The mechanism moved to _annotate(); the caller-facing guard is unchanged. fc6c97d5f6

  • prefetch_related("tags").select(..., result_type=NameRow) raised AttributeError: Cannot find 'tags' on NameRow object at iteration — and in tuple/flat mode didn't raise at all, so the prefetch query ran and its results went nowhere. Refused in both orders now, like select_related(). 7e4b60e0c0
  • Round four (live-DB review):

  • P1 — select() twice crashed when both selections held an expression (select(Upper("name")).select(Upper("status")) → ValueError: The annotation 'upper1' conflicts with a field on the model). The internal alias counter restarted on every select() and only avoided the columns being selected right then, so it regenerated the previous alias; the message named neither the cause nor a real field. 290fb8ae69

  • P2, same root, no error at all — an internal alias could land on a name the caller had already used: annotate(upper1=Lower("name")).order_by("upper1").select(D.name, Upper("status")) came back ordered by UPPER(status). The generator now clears existing annotations and previously selected columns too. 290fb8ae69

  • P5 — model_qs | row_qs and model_qs & row_qs raised RecursionError, because _merge_sanity_check only inspected the left operand. Symmetric now. Pre-existing via values()/values_list(); select() is just the first typed door to it. a5e7350eb8

  • P3/P4 — get_or_none() returned Any | None instead of R | None; create() and bulk_create() were the two writes not refused on a RowQuerySet. 260a88aea8
  • __or__ used to be the one method that couldn't be Self — a sliced left operand is re-expressed as an id subquery against Meta.base_queryset, which is a plain QuerySet by design (it must never be a user-defined queryset, which might filter rows out). #85 settled it with an overload pair and a cast on that branch, so after merging master the row type survives | like everywhere else, and the corpus claim that recorded the degradation now records that it holds.

    Review round five

    Five non-blocking items from a live-DB review, all in 6383297030:

  • A field read off a mixin class raised a bare AssertionError; it's a TypeError naming the mistake now. (A checker rejects the access too, so this is the backstop for an untyped call site.)

  • A sliced RowQuerySet in | hit select()'s own values() refusal through the id-subquery fallback; the internal paths use _values().

  • _merge_sanity_check compared columns but not row shape, so a result_type= queryset merged with a tuple one and quietly returned the left operand's shape. It compares _iterable_class and _select_result_type too, with its own message.

  • The expression alias generator now steps over the model's own column names, so a model with a column called upper1 or f1 can't be shadowed. AliasCollisionExample exists to prove it.

  • The README's lead select() example didn't type-check (email: str rather than Field[str], plus an unnecessary query: line). Rewritten, and the same example is in the typing corpus so it can't rot.
  • Then merged master for #85's returning() (006b751070), and again for #86's bulk_upsert() and #88's upsert() (63c0df464d). That last merge is where the write stack ends, so this branch is now the only one outstanding.

    The upsert merge needed two corrections a structural diff against master caught: RowQuerySet.update_or_create() was overriding a method #88 deleted, so it refused an API that no longer exists; and upsert()/bulk_upsert() were new writes RowQuerySet didn't refuse, so both ran on a row-mode queryset and handed back model instances. Both are settled, with tests.

    Merge-verification follow-ups

  • bulk_update() already failed on a row-mode queryset, but from the update() inside its own transaction.atomic(savepoint=False), which left the enclosing transaction unusable — the next query raised TransactionManagementError. It refuses up front now, with nothing sent. 3e28b260da

  • returning() was accepted and inert on a RowQuerySet, and statically worse than inert: the checker went on believing update() hands back instances. Both orders refused. 3e28b260da

  • The ladder is now asserted rung by rung. 46d158af04
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: davegaeddert Review duration: 84017m
    All Vouch review confidence checks passed
    Residual risk 0.23 = Change Risk (0.57) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.57 · 650 lines diff across 8 files
    0.57
    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
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #89"
    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: 57% (MEDIUM) · Higher = larger blast radius
    57%
    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: 22.5% · Safe to merge
    22.5%
    Repository