Repository navigation
TML-3436: Scopes: db.orm.scope for any model with given fields, Post.scope for one model, and a checked order field - #30564
Merged
Merged
Conversation
…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]>
…nd-fragments-design
…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]>
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]>
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]>
…nd-fragments-design
…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]>
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]>
Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
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]>
wmadden
approved these changes
Oct 6, 2026
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]>
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]>
4 tasks done
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.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, anoffsetor acursorthat 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
selectandincludeon every endpoint that returns a summary, a sort field taken from a request. In a query API made of method calls, these are functions.wherealready takes a function of the model accessor (the object awherecallback receives, with one member per field), andapply(#30560) runs a function on a collection. What was missing:Scopes also expose a problem in the writes.
updateAll,updateAndCount,deleteAllanddeleteAndCountignored alimit, anoffset, acursor,distinctanddistinctOn:Post.where(...).limit(10).deleteAll()deleted every matching row, not ten. A scope can add thatlimit(10)where the call site does not show it.updatewith a relation callback also ignored the order, so it could change a row other than the onefirst()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)scopeis a method of the ORM client. Each field is declared with a field builder from@prisma/orm-postgres/contract-builder, such asfield.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-postgreswrites{ codecId, nullable }instead, withmany: { elementNullable: false }ormany: { 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 asfield.namedType(...), throwsORM.ARGUMENT_INVALIDwhen the scope is defined.The body receives a
ScopeCollection. Its model accessor has only the declared fields, each typed as aCodecField(aCodecListFieldfor a list, whose elements includenullonly when the declaration says they may be null). The body may callwhere,orderBy,limitandoffset, but notselectorinclude. The type of that collection records whether the body has applied awhereand anorderBy(ScopeFacts). Because the record is part of the type, a body cannot claim a filter it may not have applied, for example after reassigning alet, 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 onejsonbvalue, is a list. The receiver can be a root collection, a custom class, a chained collection, one narrowed byselect, an include refinement, orthisin 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.applyreturns the receiver's own type plus the filter and order the body applied:Filtered<C>after awhere, soupdateanddeleteAllare allowed, andOrdered<C>after anorderBy, socursoris 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
deletedAtandtitle, applied toComment, which has onlydeletedAt:When the receiver's type does not name one model, as for
Collection<Contract, string>orscope.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:
field.uuidString(), achar(36)column, matches a field of anychar(n).scope, the namespace keeps the name and the ORM client has noscopemethod.At run time the scope checks the receiver's model each time it is applied, before the body runs. It throws
ORM.FIELD_UNKNOWN, withwhy,fixandmeta, 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 throwsORM.ARGUMENT_INVALIDotherwise. A JavaScript caller that passes a field map, a declaration or a body of the wrong kind getsORM.ARGUMENT_INVALIDwhen the scope is defined.CodecFieldCodecField<Contract, CodecId, Nullable>is the model accessor's type for a field named by its codec instead of its model, andCodecListField<Contract, CodecId, Nullable, ElementNullable>the type for a list field. Awherecallback 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.tscompares the method parameters of every scalar field in the test contract with itsCodecField. The only differences it allows are the value methods of such narrowing fields.A scope for one model:
db.orm.public.Post.scope(body)scopeis a method of every collection. The body is typed once, against the plain collection of the receiver's model in the receiver's namespace, sopostsneeds no annotation. The method reads the contract, model and namespace through athisparameter. Its type therefore does not mention the class's type arguments, andCollection<Contract, 'Post'>stays assignable toCollection<Contract, string>. A scope made fromdb.orm.auth.Useris refused bydb.orm.public.User: at compile time, and withORM.ARGUMENT_INVALIDat 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, orthisin a custom class. It refuses one narrowed byselect, because the result would claim fields the query does not return. It also refuses one narrowed byvariant.The result is always typed as the body's result on the plain collection. A custom class's methods and an earlier
whereororderBystill run, but they are not in the result's type, soupdateandcursorare 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)allowedis 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 theordertrait (OrderableFieldNames).directionis the request's string, andundefinedmeansasc.Before any query is built,
orderByFieldthrowsORM.ARGUMENT_INVALIDfor:ordertrait;allowed;ascordesc.The request string reaches SQL only as the quoted identifier of a column the model owns.
Writes refuse what they would ignore
updateAll,updateAndCount,deleteAllanddeleteAndCountchange every row that matches the filter. The statement they run cannot apply alimit, anoffset, acursor,distinctordistinctOn, so they now throwORM.ARGUMENT_INVALIDon 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.updateanddeletechange one row, the onefirst()returns, so the order, the offset, the cursor,distinctanddistinctOnchoose it. That is not new; their documentation now says so. Afterlimit(0)they now change nothing and returnnull, and a limit that a read refuses, such aslimit(-1), is refused with the sameORM.ARGUMENT_INVALID; before, they changed one row in both cases, becausefirst()replaces the limit with 1.updatewith a relation callback finds its row by the filter alone, so it now throwsORM.ARGUMENT_INVALIDon a collection with an order, a limit, an offset, a cursor,distinctordistinctOn. The checks live insrc/write-guards.ts.One fix comes with this.
delete()with aninclude, on a collection with an offset, read the row back with the offset applied. It found nothing and returnednull, although it had deleted the row. It now reads the row without the offset and returns it.The
fieldof the Postgrescontract-builderentry@prisma/orm-postgres/contract-buildernow exportsfieldwith the Postgres presets. An application can writefield.text(),field.temporal.timestamptz()orfield.uuidString()outside adefineContractcallback. It is the callback'sfieldwithout 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-clientpackage reads a builder throughScalarFieldDeclarationBuilder, a type in@internal/framework-components/codec. The contract DSL'sScalarFieldBuilderimplements it, sosql-orm-clientdoes not depend on the DSL.Smaller changes
wherehad a fourth overload that duplicated the first. When no overload matches and there are more than three, TypeScript reports only the last one. So aCodecFieldcallback 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.tscompiles such a call with the TypeScript compiler API and checks the message.collection-dispatch.ts, the scope's field check andorderByFieldnow share one column lookup and one codec-trait lookup, insrc/column-codec.ts.@prisma/orm-postgres/orm-clientaddsorderByField,OrderableFieldNames,CodecField,CodecListField,FieldScope,DeclaredFieldandScopeFacts; the last three appear in the declaration TypeScript writes for an exported scope for any model.@internal/framework-components/codecaddsCodecDescriptorRef,ScalarFieldDeclarationandScalarFieldDeclarationBuilder.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:db.orm.scopeandPost.scopetogetherdb.orm.scopePost.scopeorderByFieldThe
Post.scopeandorderByFieldrows were measured on an earlier main.On a generated contract of 200 models, half of them with
deletedAt, with one scope that filters ondeletedAtand ten uses on ten different models:db.orm.scopedefinitionEach 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:DeclaredFieldand the builder form of a declaration;ScopeCollection, whose type records the body'sScopeFacts;MissingScopeFieldsandScopeFieldsCheck, which produce the compile error;FieldScopeandWithFacts; the run-time checks indefineFieldScope; andorderByField.src/collection.ts:scope, and theapplyoverload for a scope for any model; the write refusals insrc/write-guards.ts, and the read-back and thelimit(0)case inupdate()anddelete(). AlsoModelScopeReceiverinsrc/collection-types.ts, the type a scope for one model accepts.scopeonOrmClientMembersinsrc/orm.ts.CodecFieldandCodecListFieldinsrc/types.ts, andtest/codec-field-parity.types.test-d.ts.test/field-scope.types.test-d.tsandtest/model-scope.types.test-d.tscover every site a scope is applied at, and every refusal.test/scope-run-time-checks.test.tscovers the run-time checks and the write refusals.ScalarFieldDeclarationBuilderinpackages/1-framework/1-core/framework-components/src/shared/column-spec.ts, andpackages/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.tsandget-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.scopemethod. A custom collection class that declares its ownscopewith another signature no longer compiles; rename it. An aggregate operation namedscopeis refused withORM.AGGREGATE_OPERATION_RESERVEDwhenorm()builds the ORM client.fieldof@prisma/orm-postgres/contract-builderchecks.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'svector, are not checked.updateAll,updateAndCount,deleteAllanddeleteAndCountthrowORM.ARGUMENT_INVALIDon a collection with alimit, anoffset, acursor,distinctordistinctOn.updatewith a relation callback throws on a collection with an order, a limit, an offset, a cursor,distinctordistinctOn. Without a relation callback,updateanddeleteafterlimit(0)change nothing and returnnull, and they refuse a limit that a read refuses, such aslimit(-1).Not in this pull request
select()on a model in a non-default namespace offers only theidfield. Found while testing scopes ondb.orm.auth.User; predates this change: TML-3454.upsertandcreateignore the filter, limit and offset of the collection they are called on, so a tenant scope in front ofupsertdoes not restrict the row it updates. This predates this change and needs a decision: TML-3490.like, which Postgres cannot apply to an array. This predates this change and belongs to TML-2913, which makes such calls compile errors.scopeno longer hides thescopemethod. No contract has such a namespace today.Alternatives considered
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 insideapplyis already sound.where(undefined)andorderBy(undefined)as no-ops. It adds an overload to everywhereandorderBy, costs about 7.5% more type checking in the client package when unused, and covers only those two methods.{ deletedAt: Post.fields.deletedAt }. It ties a reusable scope to one model, and renaming that field breaks every scope that names it.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.Collection<Contract, 'Post'>is no longer assignable toCollection<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.TypeStateproperty. Every real collection has that property, so a body could return any collection, such asdb.orm.public.Post.where(...), and the type would accept it. With a separate property, the type refuses that.limitandoffsetout of the body of a scope. A limit written in the chain beforedeleteAllis ignored in the same way, so the refusal belongs on the write.Housekeeping
upgrade-instructions/pending/query-fragment-helpers/, listed under Breaking changes.skills/prisma-8/references/queries-postgres.mdgains a "Workflow — Scopes" section and a checklist line.skills/prisma-8/SKILL.mdlists the helpers among the query triggers.skills/prisma-8/references/contract.mdsays that thefieldthe Postgrescontract-builderentry exports has the presets.pnpm typecheckfor the whole repository: 171 of 171 tasks.sql-orm-clienttypecheck, lint and its 1,288 tests, at 05689c6.packages/3-extensions/postgres): 333 tests.contract-ts: 569 tests.pnpm fixtures:check,lint:deps,lint:throws,lint:casts,lint:agent,lint:skills,lint:framework-vocabulary,check:upgrade-coverage.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.git commit -s) per the DCO.TML-NNNN: <sentence-case title>form.Agent: shonagon-99