Add typed select() for column selection #89
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
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
Ai Authored
ai_authored
0.050
Real PR Conversation Timeline
1 comments
"Review active on #89"
general
weight: 0.35
davegaeddert
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 newRowQuerySet[R], never partial model instances.Stacked on
typed-where(#84), which provides the typed field-access surface.Vocabulary decision
select()andwhere()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_listplumbing (same_values→set_valuespath, 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, whichselect()deliberately rejects — so consumers move toselect()and thenvalues_list()goes away, not the other way round.Design
Selectable[T]base —Field[T]andF/BaseExpressionsubclass a shared generic marker soselect()can bind each column's value type. It's a bareclass Selectable[T]: pass; a checker solvesTfromField[str] <: Selectable[T]by specializing the base class, so the marker needs no members.QuerySet.RowQuerySetadds only the refusals and, underTYPE_CHECKING, theRthe base can't carry.values_listplumbing.result_typemaps columns onto dataclass fields positionally (arity + field-name checks atselect()time).update()now carries the same_fields is not Noneguarddelete()already had, sovalues(),values_list()andselect()all refuse writes. Previouslyvalues("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()andselect_related()already raised, andannotate()now joins them (annotate first, thenselect()). 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, soselect(Upper("tags__name")).select(Widget.name)still returns one row per joined row andcount()/exists()count those. That isannotate(...)+values_list(...)behaving as it always has; trimming joins no queryset needs any more is out of scope here, and noted in the README.Order.query.select(User.email)raisesTypeErrornaming both models — theselect()half of the guard #133 gavewhere(), reusing theField.source_modelit 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, likefilter()'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_typecolumns map onto the constructor, read offinspect.signature()rather thandataclasses.fields()— the two disagree in both directions, since anInitVaris a constructor parameter that never appears infields()and aninit=Falsefield 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.Self, notQuerySet[T]— otherwiseRowQuerySet[R], which specializes its base asQuerySet[Any], dropsRthroughreverse(),none(),order_by()and friends. That fix lives in the baseQuerySetand 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 asAnywhile the fields around it stay precise — e.g.select(D.priority, Upper("name"))→RowQuerySet[tuple[int, Any]].A column annotated
Field[Any]is rejected byselect():Anysatisfies the model-valued__get__overload, so class access resolves astype[Any]rather than a field and no overload matches. That is the same reason the field-annotation guidance says never to annotate a fieldField[Any]— use the concrete type, orField[object]when the column really does hold arbitrary JSON, whichselect()types asobject. No code change; noted here and in the README because the diagnostic (a fourteen-overloadno-matching-overloaddump) 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, sotests/typing/select_ladder.pyasserts 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 atype-assertion-failurenow, and passed clean before the file existed.)Not in this slice
Relations are not selectable.
select(Post.author),select(Post.author.city)andselect(Post.author.id)all raiseTypeError. The reason is nullability, not effort: a column reached through a relation arrives over a join, so a nullable relation yieldsNonewhere the traversed field's type saysint/str. That includes the foreign key's own column.values_list("author__id", flat=True)is the spelling untilselect()can express it, and the error message names it.A custom
QuerySetsubclass is not preserved —select()hands back a plainRowQuerySet, so chain your own methods beforeselect(), not after. Documented in the README.Known gaps (follow-up, not introduced here)
Post.author.idisField[int]to a checker whether it was traversed or not, so the runtime refusal is the only guard. Closing it statically needsSelectableto carry model identity.result_typemode allocates one tuple per row that it immediately unpacks and discards (tuple_expected=Truein the sharedvalues_listpath).Tests / checks
./scripts/fix,./scripts/type-check .and the full./scripts/testare green — 27 packages, 0 failures, 1371 passed / 5 skipped in plain-postgres (88 intest_select.py).Rebased on master after #133 merged; the merge also gave master's four lock methods (
for_update()and friends, from #87) the sameSelftreatment as the rest of the chaining surface, sorows.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 togit commitand the signing agent is locked. It reproduces on pristinemasterwith 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_byon an unselected column,annotatebeforeselect,filter/whereafter, slicing,get()with 0/2 rows,first()on empty,exists(),count(),iterator(), pickling, andselect()twice.Review follow-ups
Both Codex findings are fixed and their threads resolved:
annotate()afterselect()appended a column under the declared row type: silently for tuples (RowQuerySet[tuple[str]]yielding("alpha", 1)), as a confusing constructor error forresult_type=, and silently dropped forflat=. Refused now, naming the supported order.0bb3f36523result_typearity was read offdataclasses.fields(), which omitsInitVarconstructor parameters and includesinit=Falsefields. Now read offinspect.signature().86feed2111Round two:
result_typeconstructor 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-> QuerySet[T]dropped the row type onRowQuerySet[R](and erased custom queryset subclasses generally). Swept toSelfin the base.5ce62e9400Round three:
select()twice with an expression (select(D.name).select(F("priority"))) raisedCannot call annotate() after select(), because_values_listaliases expression columns by calling the publicannotate(), whichRowQuerySetrefuses. The mechanism moved to_annotate(); the caller-facing guard is unchanged.fc6c97d5f6prefetch_related("tags").select(..., result_type=NameRow)raisedAttributeError: Cannot find 'tags' on NameRow objectat 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, likeselect_related().7e4b60e0c0Round four (live-DB review):
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 everyselect()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.290fb8ae69annotate(upper1=Lower("name")).order_by("upper1").select(D.name, Upper("status"))came back ordered byUPPER(status). The generator now clears existing annotations and previously selected columns too.290fb8ae69model_qs | row_qsandmodel_qs & row_qsraisedRecursionError, because_merge_sanity_checkonly inspected the left operand. Symmetric now. Pre-existing viavalues()/values_list();select()is just the first typed door to it.a5e7350eb8get_or_none()returnedAny | Noneinstead ofR | None;create()andbulk_create()were the two writes not refused on aRowQuerySet.260a88aea8__or__used to be the one method that couldn't beSelf— a sliced left operand is re-expressed as an id subquery againstMeta.base_queryset, which is a plainQuerySetby 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:AssertionError; it's aTypeErrornaming the mistake now. (A checker rejects the access too, so this is the backstop for an untyped call site.)RowQuerySetin|hitselect()'s ownvalues()refusal through the id-subquery fallback; the internal paths use_values()._merge_sanity_checkcompared columns but not row shape, so aresult_type=queryset merged with a tuple one and quietly returned the left operand's shape. It compares_iterable_classand_select_result_typetoo, with its own message.upper1orf1can't be shadowed.AliasCollisionExampleexists to prove it.select()example didn't type-check (email: strrather thanField[str], plus an unnecessaryquery: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'sbulk_upsert()and #88'supsert()(63c0df464d). That last merge is where the write stack ends, so this branch is now the only one outstanding.The
upsertmerge 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; andupsert()/bulk_upsert()were new writesRowQuerySetdidn'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 theupdate()inside its owntransaction.atomic(savepoint=False), which left the enclosing transaction unusable — the next query raisedTransactionManagementError. It refuses up front now, with nothing sent.3e28b260dareturning()was accepted and inert on aRowQuerySet, and statically worse than inert: the checker went on believingupdate()hands back instances. Both orders refused.3e28b260da46d158af04