Skip to content

TML-3436: Scopes: db.orm.scope for any model with given fields, Post.scope for one model, and a checked order field - #30564

Merged
wmadden merged 115 commits into
mainfrom
tml-3436-fragment-helpers
Oct 7, 2026
Merged

wmadden merged 115 commits into
mainfrom
tml-3436-fragment-helpers

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

At a glance

A scope is a function from a collection to a collection; apply (#30560) runs one. This pull request adds the three scopes applications share most: a scope for any model with given fields, a scope for one model, and an order field taken from a request.

import { field } from '@prisma/orm-postgres/contract-builder';
import { orderByField, type CollectionRowOf } from '@prisma/orm-postgres/orm-client';

// A scope for any model with a nullable deletedAt timestamp
const notDeleted = db.orm.scope(
  { deletedAt: field.temporal.timestamptz().optional() },
  (rows) => rows.where((r) => r.deletedAt.isNull()),
);
db.orm.public.Post.apply(notDeleted).deleteAll();   // Post has deletedAt; the scope filtered, so deleteAll is allowed
db.orm.public.Comment.apply(notDeleted);
db.orm.public.Tag.apply(notDeleted);                // error: Tag has no deletedAt

// A scope for Post collections, defined once: select two fields and include the user
const summary = db.orm.public.Post.scope((posts) => posts.select('id', 'title').include('user'));
type PostSummary = CollectionRowOf<ReturnType<typeof summary>>;
db.orm.public.Post.where({ userId }).apply(summary);
db.orm.public.User.include('posts', (posts) => posts.apply(summary));
db.orm.public.Post.select('id').apply(summary);     // error: the rows no longer have every Post field

// An order field from a request, checked at run time
db.orm.public.Post.orderBy(orderByField(db.orm.public.Post, input.sort, input.direction, ['title', 'createdAt']));

The decision: a shared piece of a query is a function, typed so that it fits exactly the collections it is sound for. A scope declares the fields it needs with the same field builders used to write the schema. The query API gains no methods for control flow. Because a scope can add a limit, an offset or a cursor that the call site does not show, a write that would ignore one now throws instead.

Why

Applications share pieces of queries: a soft-delete filter on every model that has the field, a tenant filter on every query, the same select and include on every endpoint that returns a summary, a sort field taken from a request. In a query API made of method calls, these are functions. where already takes a function of the model accessor (the object a where callback receives, with one member per field), and apply (#30560) runs a function on a collection. What was missing:

  • a way to write a filter for every model that has a field, without naming a model;
  • a way to define a selection once per model and name the row it produces;
  • a safe way to turn a request string into an order.

Scopes also expose a problem in the writes. updateAll, updateAndCount, deleteAll and deleteAndCount ignored a limit, an offset, a cursor, distinct and distinctOn: Post.where(...).limit(10).deleteAll() deleted every matching row, not ten. A scope can add that limit(10) where the call site does not show it. update with a relation callback also ignored the order, so it could change a row other than the one first() returns.

What this adds

This implements ADR 259, "Query fragments are functions", which is set to Accepted here.

A scope for any model with given fields: db.orm.scope(fields, body)

scope is a method of the ORM client. Each field is declared with a field builder from @prisma/orm-postgres/contract-builder, such as field.temporal.timestamptz().optional(). A list field adds .many(), or .many({ elementsNullable: true }) when its elements may be null, as in the contract DSL. A package that does not import @prisma/orm-postgres writes { codecId, nullable } instead, with many: { elementNullable: false } or many: { elementNullable: true } for a list. The codec must be one of the contract's codecs, so a misspelled codec id is a compile error at the declaration. A builder that names no column type, such as field.namedType(...), throws ORM.ARGUMENT_INVALID when the scope is defined.

The body receives a ScopeCollection. Its model accessor has only the declared fields, each typed as a CodecField (a CodecListField for a list, whose elements include null only when the declaration says they may be null). The body may call where, orderBy, limit and offset, but not select or include. The type of that collection records whether the body has applied a where and an orderBy (ScopeFacts). Because the record is part of the type, a body cannot claim a filter it may not have applied, for example after reassigning a let, and cannot return a collection other than the one it received.

The scope accepts a collection of any model whose own fields include the declared ones. A field matches by its name in the model, its codec and its nullability. It must be a list exactly where the declaration declares one, with the same element nullability. Whether a field is a list is read from the model's field, so a list of value objects such as Address[], stored as one jsonb value, is a list. The receiver can be a root collection, a custom class, a chained collection, one narrowed by select, an include refinement, or this in a class. The scope reads the receiver's contract, model and namespace from the receiver's type, and checks the declared fields against that one model. apply returns the receiver's own type plus the filter and order the body applied: Filtered<C> after a where, so update and deleteAll are allowed, and Ordered<C> after an orderBy, so cursor is allowed. The result keeps the receiver's own type name, so TypeScript can write a declaration file for an exported chain.

A refused model gets a compile error that names the field. For a scope that declares deletedAt and title, applied to Comment, which has only deletedAt:

Property ''the model has no field that matches the declaration in the scope'' is missing in type 'CollectionBase<Contract, "Comment", ...>' but required in type '{ readonly 'the model has no field that matches the declaration in the scope': "title"; }'.

When the receiver's type does not name one model, as for Collection<Contract, string> or scope.call(undefined, collection), the missing property in the error is 'the scope could not read the model of the collection from its type' instead. A union of collections is accepted when every model in it has the fields. A union of two scopes is accepted when both establish the same filter and order.

Some limits of the match:

  • Only the codec, the nullability, the list kind and the element nullability are compared, not the column type's parameters. field.uuidString(), a char(36) column, matches a field of any char(n).
  • A relation, or a field that only one variant of a polymorphic model has, does not match.
  • A collection whose type carries no namespace, such as a custom class, is checked at compile time against every model of that name in the contract. Its real namespace is checked at run time.
  • If the contract has a namespace named scope, the namespace keeps the name and the ORM client has no scope method.

At run time the scope checks the receiver's model each time it is applied, before the body runs. It throws ORM.FIELD_UNKNOWN, with why, fix and meta, when a field does not match. After the body runs, it checks that the body returned a collection of the receiver's model, namespace and class, and throws ORM.ARGUMENT_INVALID otherwise. A JavaScript caller that passes a field map, a declaration or a body of the wrong kind gets ORM.ARGUMENT_INVALID when the scope is defined.

CodecField

CodecField<Contract, CodecId, Nullable> is the model accessor's type for a field named by its codec instead of its model, and CodecListField<Contract, CodecId, Nullable, ElementNullable> the type for a list field. A where callback whose parameter is { deletedAt: CodecField<...> } fits every model with such a field. It has the same methods as the field on a model, including operations a package contributes. It checks values against the codec's output type, so it accepts values that a field which narrows its codec would refuse, such as 'superuser' for an enum stored as text. test/codec-field-parity.types.test-d.ts compares the method parameters of every scalar field in the test contract with its CodecField. The only differences it allows are the value methods of such narrowing fields.

A scope for one model: db.orm.public.Post.scope(body)

scope is a method of every collection. The body is typed once, against the plain collection of the receiver's model in the receiver's namespace, so posts needs no annotation. The method reads the contract, model and namespace through a this parameter. Its type therefore does not mention the class's type arguments, and Collection<Contract, 'Post'> stays assignable to Collection<Contract, string>. A scope made from db.orm.auth.User is refused by db.orm.public.User: at compile time, and with ORM.ARGUMENT_INVALID at run time.

The scope accepts a collection of that model whose rows still have every field: a root or filtered collection, a collection after include, an include refinement, or this in a custom class. It refuses one narrowed by select, because the result would claim fields the query does not return. It also refuses one narrowed by variant.

The result is always typed as the body's result on the plain collection. A custom class's methods and an earlier where or orderBy still run, but they are not in the result's type, so update and cursor are refused after it. A scope for one model is for changing the row. A filter on one model belongs in a class method or in a scope for any model.

An order field from a request: orderByField(collection, name, direction, allowed)

allowed is required and names at least one field. Without it, request text could order the rows by a secret field and learn its values from the order of the results. Its type accepts only fields whose codec has the order trait (OrderableFieldNames). direction is the request's string, and undefined means asc.

Before any query is built, orderByField throws ORM.ARGUMENT_INVALID for:

  • a name or direction that is not a string;
  • a name that is not a field of the model, is a relation, or has a codec without the order trait;
  • a name outside allowed;
  • a direction other than asc or desc.

The request string reaches SQL only as the quoted identifier of a column the model owns.

Writes refuse what they would ignore

updateAll, updateAndCount, deleteAll and deleteAndCount change every row that matches the filter. The statement they run cannot apply a limit, an offset, a cursor, distinct or distinctOn, so they now throw ORM.ARGUMENT_INVALID on a collection that has any of them, whether a scope added it or the chain did. The error names what the collection has, for example "the collection has a limit, an offset and a cursor". An order does not change which rows they change, so they still accept one.

update and delete change one row, the one first() returns, so the order, the offset, the cursor, distinct and distinctOn choose it. That is not new; their documentation now says so. After limit(0) they now change nothing and return null, and a limit that a read refuses, such as limit(-1), is refused with the same ORM.ARGUMENT_INVALID; before, they changed one row in both cases, because first() replaces the limit with 1. update with a relation callback finds its row by the filter alone, so it now throws ORM.ARGUMENT_INVALID on a collection with an order, a limit, an offset, a cursor, distinct or distinctOn. The checks live in src/write-guards.ts.

One fix comes with this. delete() with an include, on a collection with an offset, read the row back with the offset applied. It found nothing and returned null, although it had deleted the row. It now reads the row without the offset and returns it.

The field of the Postgres contract-builder entry

@prisma/orm-postgres/contract-builder now exports field with the Postgres presets. An application can write field.text(), field.temporal.timestamptz() or field.uuidString() outside a defineContract callback. It is the callback's field without the helpers an extension adds. Its .default(...) now checks the value against the Postgres target's column types, as the callback's does.

The sql-orm-client package reads a builder through ScalarFieldDeclarationBuilder, a type in @internal/framework-components/codec. The contract DSL's ScalarFieldBuilder implements it, so sql-orm-client does not depend on the DSL.

Smaller changes

  • where had a fourth overload that duplicated the first. When no overload matches and there are more than three, TypeScript reports only the last one. So a CodecField callback refused for a model without the field printed an error about shorthand filter objects. With the duplicate removed, the error names the missing field. test/codec-field-diagnostics.test.ts compiles such a call with the TypeScript compiler API and checks the message.
  • The model accessor, the shorthand filters, the decoding of included columns in collection-dispatch.ts, the scope's field check and orderByField now share one column lookup and one codec-trait lookup, in src/column-codec.ts.
  • New public names. @prisma/orm-postgres/orm-client adds orderByField, OrderableFieldNames, CodecField, CodecListField, FieldScope, DeclaredField and ScopeFacts; the last three appear in the declaration TypeScript writes for an exported scope for any model. @internal/framework-components/codec adds CodecDescriptorRef, ScalarFieldDeclaration and ScalarFieldDeclarationBuilder.

Cost

Measured as type instantiations reported by TypeScript 5.9.3 (pnpm typecheck --extendedDiagnostics), each count taken twice with the same result. ADR 259 describes the method.

On examples/prisma-8-demo, which checks at 735,059 instantiations on main without these helpers:

Feature Present but unused Definition Ten uses, over the same code written inline
db.orm.scope and Post.scope together +342 (+0.05%)
db.orm.scope 8,305 for the first in a program, 145 for each later one +3,147: 4,089 for the ten uses, against 942 inline
Post.scope 21 −7,109: the body is typed once instead of at each site
orderByField none — about 550 once, then under 20

The Post.scope and orderByField rows were measured on an earlier main.

On a generated contract of 200 models, half of them with deletedAt, with one scope that filters on deletedAt and ten uses on ten different models:

Instantiations
One db.orm.scope definition 19,732
Its first use 1,136
Each later use about 890
Ten uses, with the definition 28,887
The same ten filters written inline 17,775
Ten uses over inline, with the definition +11,112

Each use checks the declared fields against the receiver's model only. What in the contract's type drives the cost of the definition was not measured.

What reviewers should look at

All paths in the first five items are under packages/3-extensions/sql-orm-client/.

  • src/scopes.ts: DeclaredField and the builder form of a declaration; ScopeCollection, whose type records the body's ScopeFacts; MissingScopeFields and ScopeFieldsCheck, which produce the compile error; FieldScope and WithFacts; the run-time checks in defineFieldScope; and orderByField.
  • src/collection.ts: scope, and the apply overload for a scope for any model; the write refusals in src/write-guards.ts, and the read-back and the limit(0) case in update() and delete(). Also ModelScopeReceiver in src/collection-types.ts, the type a scope for one model accepts.
  • scope on OrmClientMembers in src/orm.ts.
  • CodecField and CodecListField in src/types.ts, and test/codec-field-parity.types.test-d.ts.
  • The tests. test/field-scope.types.test-d.ts and test/model-scope.types.test-d.ts cover every site a scope is applied at, and every refusal. test/scope-run-time-checks.test.ts covers the run-time checks and the write refusals.
  • ScalarFieldDeclarationBuilder in packages/1-framework/1-core/framework-components/src/shared/column-spec.ts, and packages/3-extensions/postgres/src/contract/field.ts.
  • test/integration/test/namespaced-accessors-scopes.integration.test.ts: both kinds of scope on a contract that has the same model name in two namespaces, against a database.
  • examples/prisma-8-demo/src/orm-client/scopes.ts, get-recent-posts.ts and get-recent-users.ts, which use all three helpers.

Breaking changes

The upgrade entries are in upgrade-instructions/pending/query-fragment-helpers/, for applications and for extension authors.

  • Every collection of the SQL ORM client has a scope method. A custom collection class that declares its own scope with another signature no longer compiles; rename it. An aggregate operation named scope is refused with ORM.AGGREGATE_OPERATION_RESERVED when orm() builds the ORM client.
  • The field of @prisma/orm-postgres/contract-builder checks .default(...) values against the Postgres target's column types. A default of the wrong type, which compiled before and failed when the contract was built, is now a compile error. Column types an extension adds, such as pgvector's vector, are not checked.
  • Writes refuse what they would ignore. updateAll, updateAndCount, deleteAll and deleteAndCount throw ORM.ARGUMENT_INVALID on a collection with a limit, an offset, a cursor, distinct or distinctOn. update with a relation callback throws on a collection with an order, a limit, an offset, a cursor, distinct or distinctOn. Without a relation callback, update and delete after limit(0) change nothing and return null, and they refuse a limit that a read refuses, such as limit(-1).

Not in this pull request

  • Including the same relation twice projects it twice in the SQL. This predates this change: TML-3438.
  • select() on a model in a non-default namespace offers only the id field. Found while testing scopes on db.orm.auth.User; predates this change: TML-3454.
  • A default scope per model, such as soft delete applied to every query of a model. That is a later decision.
  • upsert and create ignore the filter, limit and offset of the collection they are called on, so a tenant scope in front of upsert does not restrict the row it updates. This predates this change and needs a decision: TML-3490.
  • A list field offers the single-value comparison methods, such as like, which Postgres cannot apply to an array. This predates this change and belongs to TML-2913, which makes such calls compile errors.
  • Putting the namespaces or the ORM client's methods under a member of their own, so that a namespace named scope no longer hides the scope method. No contract has such a namespace today.
  • A scope for one model whose body keeps the row could return the receiver's own type with the filter and order the body applied, as a scope for any model does. ADR 259 keeps the simpler rule for now.

Alternatives considered

  • A when(value, fn) combinator for conditional fragments. It moves control flow into the query API, and every construct would need its own combinator. Under ADR 265 a filtered collection is a subtype of an unfiltered one, so a plain conditional inside apply is already sound.
  • where(undefined) and orderBy(undefined) as no-ops. It adds an overload to every where and orderBy, costs about 7.5% more type checking in the client package when unused, and covers only those two methods.
  • Query fragments as objects. The chain is the query language here. An object fragment needs a second way to express every method, kept in step with the first.
  • Declaring a scope's fields by pointing at a model's field, { deletedAt: Post.fields.deletedAt }. It ties a reusable scope to one model, and renaming that field breaks every scope that names it.
  • A scope for one model written with type arguments, scope<Contract, 'Post'>()(body). The empty call exists only because TypeScript cannot take two explicit type arguments and infer the body's type in the same call.
  • A scope for one model typed with the class's type arguments. The model then appears in the parameter of the returned scope, so Collection<Contract, 'Post'> is no longer assignable to Collection<Contract, string>, which generic helpers rely on. Typing the body against the receiver's namespace this way costs 6,611 instantiations (+0.9%) in the demo when unused.
  • Carrying the body's facts in ADR 265's TypeState property. Every real collection has that property, so a body could return any collection, such as db.orm.public.Post.where(...), and the type would accept it. With a separate property, the type refuses that.
  • Leaving limit and offset out of the body of a scope. A limit written in the chain before deleteAll is ignored in the same way, so the refusal belongs on the write.

Housekeeping

  • Linked issue: TML-3436. Builds on TML-3403: A collection keeps its class through the chain, and a conditional query cannot unlock deleteAll #30560 (TML-3403), merged.
  • Upgrade instructions: upgrade-instructions/pending/query-fragment-helpers/, listed under Breaking changes.
  • Docs: the client README gains a "Scopes" section, and the demo README lists the new queries.
  • Skill update: skills/prisma-8/references/queries-postgres.md gains a "Workflow — Scopes" section and a checklist line. skills/prisma-8/SKILL.md lists the helpers among the query triggers. skills/prisma-8/references/contract.md says that the field the Postgres contract-builder entry exports has the presets.
  • Testing performed, at cf14083 unless noted:
    • pnpm typecheck for the whole repository: 171 of 171 tasks.
    • sql-orm-client typecheck, lint and its 1,288 tests, at 05689c6.
    • The Postgres facade package (packages/3-extensions/postgres): 333 tests. contract-ts: 569 tests.
    • Demo typecheck and 91 demo tests, including the declaration-emit test.
    • pnpm fixtures:check, lint:deps, lint:throws, lint:casts, lint:agent, lint:skills, lint:framework-vocabulary, check:upgrade-coverage.
    • Integration files, run one at a time: planner-golden/planner-ddl-golden, namespaced-accessors-scopes, sql-orm-client/update, sql-orm-client/delete, sql-orm-client/nested-mutations, sql-orm-client/pagination, psl-print/every-postgres-contract-roundtrip.
  • All commits are signed off (git commit -s) per the DCO.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated.
  • The PR title is in TML-NNNN: <sentence-case title> form.

Agent: shonagon-99

…and query fragments are functions

ADR 258: the type state and row are declared properties of the collection, unknown flags default to boolean, where and orderBy return this intersected with the flag they set, include returns this with the row widened, select returns a plain Collection. A custom class keeps its methods through the chain, and a conditional between a filtered and an unfiltered collection reduces to the unfiltered one, so update, delete and cursor stay refused.

ADR 259: a query fragment is a function. where and orderBy take row fragments; a pipe method applies collection fragments; any function body inside pipe is sound by ADR 258. FieldExpression, rowFragment with RowOf, and sortField cover the shared-filter, shared-select and request-sort idioms.

The three spike write-ups behind the decisions are included.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…preceding-state narration

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…er from a this parameter; rows are read through this

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ered, Ordered, Including; pipe moves here from ADR 259

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Chaining methods take a this parameter and return the receiver plus the
fact they establish (Filtered, Ordered, Including), so custom collection
methods chain before and after where, orderBy, limit and include. The
type state and row live in declared properties keyed by StateType and
RowType; unestablished flags are boolean, so a filtered collection is a
subtype of an unfiltered one and conditionals reduce soundly (TML-3397).
Adds pipe(step).

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
getUserPosts chains forUser and newestFirst. A type test checks class
methods after include, a conditional filter, and that exported chains
and steps produce declarations through the published facade.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Including takes the fields it adds; CollectionStateOf is an indexed
access; the public names include AggregateIncludeReducers and
IncludeScalar; cost figures are the measured ones. The client README
describes custom collections, the facts, pipe and the type state.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…esign' into tml-3403-collection-keeps-its-class
The public surface no longer names the class: chains print as
Filtered<Collection<...>> or Filtered<PostCollection>, and the class is
CollectionBase inside the package. HasRow and HasState replace
IncludeReceiver, StateCarrier, RowSelection and the inline shapes, and
the public types move to collection-types.ts. Rows flatten with
Simplify, including combine branches. The six writes guard with
this: Filtered<this>; cursor and distinctOn keep the argument guard.
Adds tests for cursor, distinctOn, variant, the select fallback and an
annotated union, and makes the runtime chaining tests able to fail.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…y break

ADR 258: a scope paragraph (the MongoDB client is unchanged), exact
declarations, both guard forms with the methods that use each and why,
the real reason variant drops the class, the select fallback dropping
included relations, "base Collection type" for the class base, and the
class through variant and the MongoDB client under later decisions.
Every example compiles against the demo contract.

Upgrade instructions add writes on a conditional collection, pipe as a
member, overrides of chaining methods, and an optional entry for the
demo edit; their snippets compile and the ReturnType, include and
MongoDB statements are exact.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The description still holds, and leaving it unchanged lets the app
upgrade instructions reproduce every non-test change in examples/.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… classes only

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The test runs real declaration emit (not --noEmit) on a fixture that
exports collection classes with unannotated methods covering every
chaining and row-returning method, pipe, variant, a generic subclass, a
subclass with private fields, an exported chain and a function returning
Filtered<Collection<...>>, all through @prisma/orm-postgres/orm-client.
It fails at this commit with TS2527 for every row-returning method.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
CollectionRowOf and CollectionStateOf are mapped types of their own, so
a subclass method that returns rows or a prepared collection emits as
CollectionRowOf<this> instead of naming the RowType symbol, which a
consumer of the facade cannot reach (TS2527). Implementation signatures
of the row-returning methods return unknown so the overloads stay
compatible without casts.

The eight guarded methods all take a this parameter constrained to the
fact: Self extends HasWhere for the six writes, Self extends HasOrderBy
for cursor and distinctOn. The ported aggregation tests that use cursor
without an order, as the upstream queries do, now cast the receiver.

Variant tests run on the emitted polymorphism contract, and the chaining
tests write Filtered and Ordered.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…form

ADR 258: why the read helpers are mapped types of their own (declaration
emit through the facade), one guard form and its error, what error
messages print, and the union write error with its remedy. ADR 250 gives
the current type of _row.

Upgrade instructions: the conditional-write detection is narrowed and
tells the agent to act only where the compiler reports the error; a new
entry covers cursor and distinctOn checking the receiver.

The prisma-8 skill: a write needs a filter on every code path,
distinctOn needs an order, and a section on custom collection classes,
pipe, Step, Filtered and Ordered, linked from runtime.md.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…sumer of emitted declarations

A class method that calls include and then a terminal must return the
included relation, for every row-returning method. The declaration-emit
test now also typechecks a consumer of the emitted .d.ts that asserts
exact collection and row types, and the fixture library covers include
refinements, include reducers, combine, first(filter), groupBy and
aggregate. Both fail at this commit.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Inside a class method, this.include(...) has the type this & HasRow<...>,
and a method whose return type names the polymorphic this reads the
class row from it, losing the included relation. all, first, create,
createAll, upsert and the writes now take a this parameter and return
CollectionRowOf<this & Self>, so the receiver row includes what the
chain added. The read methods keep a final overload that returns
CollectionRowOf<this>, which ReturnType and infer patterns read.

The prepared getter cannot take a this parameter and still reads the
class row inside a class body.

AggregateSelector is exported, so a class method that returns an
aggregate or groupBy result emits declarations.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Declaration output keeps the alias name for it, so the mapped form was
not needed; the declaration-emit test covers prepared, the one member
whose type reads it.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The emitted polymorphism contract is copied into test/fixtures by the
package emit script, like the other generated fixtures, and emit:check
covers it. The variant chaining and model type tests import it from
there instead of from the integration test package.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
ADR 258: the row-returning methods read CollectionRowOf<this & Self>
and keep a final overload for ReturnType; the prepared getter reads the
class row inside a class body; a class method called on another call
inside a class body loses that call facts; declarations name the
family package, which predates this decision; re-measured costs.

The upgrade entry for overrides covers the row-returning methods, and
the skill notes how to chain class methods inside a class body.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
all, first, create, createAll and upsert take Self extends this and
return CollectionRowOf<Self>. Reading this & Self made TypeScript hit
its instantiation depth limit on an integration test with native enum
arrays, and the final create overload with a union input changed what
Parameters<C["create"]> gives. The final overloads now repeat the
signatures the methods had before, so ReturnType, Parameters and infer
patterns read the same types as before. The writes keep
CollectionRowOf<this & Self> with Self extends HasWhere.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
update, updateAll, delete and deleteAll returned CollectionRowOf<Self & HasRow>. ReturnType replaces Self with its constraint, HasWhere, which has no row, so NonNullable<Awaited<ReturnType<PostCollection['update']>>> was {} instead of the Post row. They now return CollectionRowOf<Self & HasRow<CollectionRowOf<this>>>. A call keeps the receiver's row, ReturnType reads the row of the type the method is read from, including relations that include added, and an Omit receiver still checks without TS2589.

CollectionRowOf<Self & HasRow<Row>>, with the class's row type argument, was rejected: declaration output writes a custom class's row out in full, which fails the demo's declaration-emit test on rows with Temporal fields, and its ReturnType after include loses the relation.

Adds type tests for ReturnType of every write, for writes after include and after select, and for writes on a polymorphic base. ADR 258 states the form and the counts measured with it. The prisma-8 skill now says that a class method whose body chains two class methods loses the first call's facts for every caller.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ful refusals

update and delete change the row first() returns, so they honour the order and the offset again; only update with a relation callback, which finds its row by the filter alone, throws ORM.ARGUMENT_INVALID on an order, a limit or an offset. updateAll, updateAndCount, deleteAll and deleteAndCount keep refusing a limit or an offset. delete with an include no longer reads its row back with the offset. ADR 259, the README, the prisma-8 skill and the upgrade entry say which writes refuse and why.

A scope declaration of one value no longer matches a list field, at compile time or at run time. A list is declared with .many() on the builder or many: true in the object, and matches only a list field; the body types it as a list of the codec's values. The soft-delete fixture gains Tag.labels String[].

When the receiver's model cannot be read from its type, as for scope.call(undefined, collection) or a Collection<Contract, string>, the compile error says so instead of naming a field the model has. The compile-time refusal for a field now reads 'the model has no field that matches the declaration in the scope'.

A JavaScript receiver whose ctx has no context or contract is refused with ORM.ARGUMENT_INVALID instead of a TypeError. The soundness test for explicit facts uses an unannotated body again. ADR 259 describes custom classes without a namespace as they behave, and says codec where the check is on the codec.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The demo's baseline is now 702,050; the helpers present but unused still add 308. The db.orm.scope row is measured with a demo file that defines a scope on createdAt and applies it at the ten sites: the first definition costs 7,869, each later one 143, and ten uses 4,253 against 1,090 inline. The 200-model table is measured with the same script as before.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
ADR 258 keeps this branch's version: main holds the design PR's text, which this branch corrected after review.
The polymorphism test reads its contract from test/fixtures/poly-contract.ts, so main's many: false on every column and scalar field goes there.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Base automatically changed from tml-3403-collection-keeps-its-class to main October 6, 2026 09:07
contract-dsl.ts keeps main's ApplyMany and ManyOptions, which slice 1 brought in from main, and this branch's implements ScalarFieldDeclarationBuilder.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Files whose main version is slice 1's final version keep this branch's version. contract-dsl.ts imports both DataTypeLookup and ScalarFieldDeclarationBuilder. The namespaced-accessors fixture keeps the two Note models and passes main's codec and data type lookups.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Main's createComposedAuthoringHelpers now requires codecLookup and dataTypeLookup. The facade's field builds them as defineContract does for a contract without extensions.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Main records a list as many: false | { elementNullable } on contract fields and storage columns. A scope's declaration now does the same: .many() declares a list whose elements are never null, .many({ elementsNullable: true }) one whose elements may be null, and the package form takes many: { elementNullable } in place of many: true. A declaration matches a field only when both hold one value or both are lists with the same element nullability, at compile time and at run time. Inside the body a list field is a CodecListField whose element type includes null when the declaration says so.

The soft-delete fixture gains Tag.notes String?[] and is re-emitted with the list shape main writes; the planner golden manifest records slice 2's contracts.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The demo files of main at 7bc1b4d check at 735,059 instantiations against main's packages and 735,401 against slice 2's: +342 (+0.05%) for both scope methods present but unused. On the same demo files, the first db.orm.scope definition costs 8,305, each later one 145, and ten uses 4,089 against 942 inline. The 200-model probe, re-emitted with main's emitter, gives 19,732 for the definition and +11,112 for ten uses over inline. The rows for a conditional inside apply, Post.scope and orderByField were not measured again.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…any is checked

The run-time check read whether a field is a list from its storage column, so a list of value objects, a list in the model stored as one jsonb value, matched no declaration. It now reads the model's field, as the compile-time check does. A field builder whose build() returns a many other than false, undefined or { elementNullable } now throws ORM.ARGUMENT_INVALID, as the object form does.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…mit(0) changes nothing

updateAll, updateAndCount, deleteAll and deleteAndCount now throw ORM.ARGUMENT_INVALID on a cursor, distinct or distinctOn, as on a limit or an offset, and the error names what the collection has. update with a relation callback refuses them too. update and delete without one find their row through first(), which applies all of them; after limit(0) they now change nothing and return null instead of changing the row first() would return.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…g exactly

CodecListField is exported from the orm-client entry, listed in ADR 259's public names, and used by a list row fragment and a list scope in the demo's declaration fixture. ADR 259, the client README, the prisma-8 skill, the scope doc comment and the upgrade entry state the write refusals (limit, offset, cursor, distinct, distinctOn, and limit(0) on update and delete), that both checks read a list from the model's field, what is compared when a field matches, and the error TypeScript gives for a union of scopes whose facts differ.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Main's contract columns now store their data type id. Slice 2's fixtures (soft-delete, scope-namespace, namespaced-accessors) are re-emitted and the planner golden manifest is regenerated; only their entries differ from main's.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Their row lookup goes through first(), which replaces the limit with 1, so limit(-1) used to change a row while all() threw. They now check the limit with the rule reads use, checkLimitOffset, which relational-core exports.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
ADR 259 keeps this branch's text, cites the collection ADR as ADR 265 as main now numbers it, and names #30428 for the scope builder instead of ADR 260, which main now gives to another decision.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden added this pull request to the merge queue Oct 6, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 6, 2026
…capabilities

Main's #30549 adds forUpdate, forNoKeyUpdate, forShare, forKeyShare, lockNowait, lockOf and lockSkipLocked to every Postgres contract and re-emitted the fixtures on main; the soft-delete and scope-namespace fixtures this branch adds were not there yet.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
collection.ts keeps this branch's scope method and main's variant(), which selects by discriminator value (#30577). The scope tests call variant('bug'), so the type tests' expected errors still come from the scope refusal.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden added this pull request to the merge queue Oct 7, 2026
Merged via the queue into main with commit 4accaf0 Oct 7, 2026
24 checks passed
@wmadden
wmadden deleted the tml-3436-fragment-helpers branch October 7, 2026 06:45
Thegreatsura pushed a commit to Thegreatsura/prisma that referenced this pull request Oct 8, 2026
…sma#30635)

## At a glance

The SQL ORM client's collection method `apply` is renamed to `with`.
Nothing else about it changes.

```diff
  const summary = db.orm.public.Post.scope((posts) => posts.select('id', 'title').include('user'));

- const cards = await db.orm.public.Post.where({ userId }).apply(summary).limit(10).all();
+ const cards = await db.orm.public.Post.where({ userId }).with(summary).limit(10).all();

- db.orm.public.User.include('posts', (posts) => posts.apply(summary));
+ db.orm.public.User.include('posts', (posts) => posts.with(summary));
```

`summary` is a scope: a function that takes a collection and returns a
collection. `apply(fn)` called it with the collection and returned the
result; `with(fn)` does the same. The method shipped under the old name
in 8.0.0-rc.15 last week, so this is a breaking change with an upgrade
entry.

## Why rename

A scope can do two kinds of thing to a collection. It can filter it, and
it can change what comes back: which fields, which relations, in what
order, how many rows. For filtering, the client already has a better
home than `apply`: `where` takes a function of the row, so a reusable
filter is written `where(notDeleted)` and needs no second method. That
leaves `apply` for the second kind, and there `with` is plain English: a
post *with* its summary, *with* the newest first.

```ts
db.orm.public.Post.where(notDeleted).with(summary).with(newestFirst);
```

`with` is a reserved word in JavaScript but a valid method name.
`collection.with(fn)` works everywhere; only `const { with } =
collection` is impossible, and nothing in the client needs it.

The word "scope" is not part of this change. Whether a scope should be
called something else is a separate discussion.

## What changes

- **The method.** `with` replaces `apply` on `CollectionBase` in
`@internal/sql-orm-client`, with the same two overloads and the same
run-time behaviour. Every call in the client, the demo, the declaration
fixtures and the tests follows: 141 call sites.
- **The reserved name.** Every collection now has a `with` member, so an
aggregate operation named `with` is refused with
`ORM.AGGREGATE_OPERATION_RESERVED`, and one named `apply` is allowed
again. A new test covers the refusal.
- **Error texts.** The two messages that named the method now say
`with`: "Pass the scope to with on a collection:
collection.with(scope)." and "A scope passed to with can add one without
showing it at the call site."
- **Docs.** ADR 259, ADR 265, the ADR index, the client README, the
`prisma-8` skill and the doc comments use `with`. Each place that
introduces the method now also says that a reusable filter is
`where(rowFragment)`, so readers do not reach for `with` where `where`
already serves.

Left alone on purpose: `Function.prototype.apply` and `Reflect.apply`
calls, the language server test helper's own `apply` method, and the
published rc.15 upgrade guides, which describe that release.

## Upgrading

The entry is `upgrade-instructions/pending/collection-with/`, for
applications and for extensions:

- Rename `collection.apply(fn)` to `collection.with(fn)`. The detection
matches `.apply(` only when its first argument is a name or an arrow
function, because `fn.apply(this, args)` shares the name; the entry
tells the consumer's agent to rename only where the receiver is a
collection.
- A custom collection class that declares its own `with` must rename it.
One that declared `apply` because that name was reserved may keep it.

## Alternatives considered

- **`use`**, the runner-up. It matches middleware's `app.use(fn)` and
reads neutrally in every case, but worse than `with` for selections and
includes, which are most of what the method is for once filters go
through `where`.
- **`modify`** (Knex, Objection.js), **`$call`** (Kysely) and **`thru`**
(Lodash), the words other libraries use for this slot. Accurate, and
less readable at a call site.
- **`pipe`, `chain`, `tap`, `merge`, `combine`, `and`**. Rejected in the
original design or already taken: `combine` is a collection method and
`and` is the expression combinator inside `where`.
- **Keeping `apply` as a deprecated alias.** The product is in release
candidates, and the upgrade entry is what consumers' agents act on; an
alias would only delay the rename.

## Housekeeping

- **Linked issue:** TML-3508. Builds on prisma#30560 (TML-3403) and prisma#30564
(TML-3436), merged.
- **Skill update:** `skills/prisma-8/SKILL.md` and
`references/queries-postgres.md` use `with` and state the
`where(rowFragment)` rule.
- **Testing performed**, at f9749bf: `pnpm typecheck` for the whole
repository (171 tasks); client typecheck, lint and 1,303 tests; Postgres
facade, 333 tests; demo typecheck and 91 tests including
`declaration-emit`; `lint:deps`, `lint:throws`, `lint:casts`,
`lint:agent`, `lint:skills`, `lint:framework-vocabulary`;
`check:upgrade-coverage`; `pnpm fixtures:check`; the integration file
`namespaced-accessors-scopes` alone. The app upgrade entry was validated
by applying it to the demo at the base and comparing with this branch.
- [x] All commits are signed off (`git commit -s`) per the
[DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco).
- [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is
scoped to one logical concern.
- [x] Tests are updated.
- [x] The PR title is in `TML-NNNN: <sentence-case title>` form.

Agent: shonagon-99

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants