Skip to content

TML-3415: The ORM client locks the rows a collection reads with forUpdate, forNoKeyUpdate, forShare and forKeyShare - #30555

Merged
wmadden merged 56 commits into
mainfrom
tml-3415-row-locking-orm-client
Oct 7, 2026
Merged

wmadden merged 56 commits into
mainfrom
tml-3415-row-locking-orm-client

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

An ORM collection can now lock the rows it reads, until the transaction ends:

await db.transaction(async (tx) => {
  const product = await tx.orm.public.Product.where({ id: productId }).forUpdate().first();
  if (product !== null && product.stock > 0) {
    await tx.orm.public.Product.where({ id: productId }).update({ stock: product.stock - 1 });
  }
});
SELECT ... FROM "public"."product" WHERE "product"."id" = $1 LIMIT 1 FOR UPDATE OF "product"

Without the lock, two requests for the last unit can both read stock = 1 and both write stock = 0. With it, the second request's read waits until the first transaction commits, then sees stock = 0.

This PR builds on #30549, which is merged. #30549 gave the typed SQL builder the same four methods, and added the lock to the shared select tree, the seven capabilities and the Postgres rendering. The design is recorded in ADR 261, in #30542.

Closes #30531.

The decision

The same four methods as the typed SQL builder. A collection gains forUpdate(), forNoKeyUpdate(), forShare() and forKeyShare(). Each takes an optional nowait or skipLocked, which exclude each other.

The ORM locks only the model's own rows. There is no of option. Every clause renders OF the model's table, under the name the ORM's lowering writes in FROM. (The lowering is the step that turns a collection into a select tree.) This matters because the lowering adds joins the caller never wrote. A polymorphic model, for example, outer-joins its variant tables. Without OF, Postgres would try to lock those tables too, and it refuses to lock the nullable side of an outer join. The tests check this on a polymorphic model with and without variant().

The methods need sql.lockOf as well as their strength's capability. Because the ORM always renders OF, a target that cannot render OF cannot run its locks either. Without its capabilities, a method's parameter list is never, so even forUpdate() with no arguments is a type error. At run time the method checks again and throws ORM.CAPABILITY_MISSING. This is the pattern distinctOn uses.

A lock is refused together with anything that would drop it or that Postgres refuses. Each refusal is ORM.LOCK_INCOMPATIBLE, and its meta.conflict says why:

What the caller wrote meta.conflict When it is refused
a locked collection read with include() include when the read is compiled
a locked collection read with distinct() or distinctOn() distinct, distinctOn when the read is compiled
a lock inside an include() refinement includeRefinement at the call, and again when the parent read is compiled
groupBy() or aggregate() on a locked collection groupBy, aggregate at the call
any mutation method on a locked collection mutation before the first statement

The include() row and the refinement row are different mistakes. An include() refinement is a callback that receives the related collection and narrows it. It can return that collection, a scalar such as a count, or a combine of several of those. A lock method called on the related collection inside the callback is refused at once, because the lock is on a related collection, not on the collection being read. A callback can also return a collection that was locked outside it. The ORM catches that when it compiles the parent read, by checking every included collection, scalar and combine branch for a lock.

A mutation is refused because it already locks the rows it changes, and silently dropping the lock written before it would hide a mistake.

A lock outside a transaction is not refused. Postgres then releases it when the statement ends, which is legal, and nowait there asks whether a row is free right now.

The locking rules now live in one module. packages/2-sql/4-lanes/relational-core/src/ast/locking.ts holds three things:

  • which capabilities each strength and option needs;
  • the nowait/skipLocked option type and its run-time check;
  • the LockConflict union of meta.conflict values.

The typed SQL builder, the ORM client and the Postgres renderer all read it, so they cannot disagree. That is why this PR touches the builder and the renderer as well as the ORM. Their behaviour and error messages do not change.

How to review this PR

28 files change. The substance:

Where What
packages/2-sql/4-lanes/relational-core/src/ast/locking.ts the locking rules shared by the three consumers
packages/3-extensions/sql-orm-client/src/collection.ts the four methods, and the refusal calls in groupBy(), aggregate() and the mutation methods
packages/3-extensions/sql-orm-client/src/collection-contract.ts assertLockCapability, the run-time capability check
packages/3-extensions/sql-orm-client/src/types.ts CollectionState.locking, set to undefined by emptyState()
packages/3-extensions/sql-orm-client/src/lock-guards.ts assertLockCompatible, which refuses the shapes in the table and finds a lock inside an included collection, scalar or combine branch
packages/3-extensions/sql-orm-client/src/query-plan-select.ts runs assertLockCompatible when a read is compiled, and puts the lock on the outermost select
packages/2-sql/4-lanes/sql-builder/src/..., packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts switched to the shared module

Smaller changes:

  • orm-errors.ts registers LOCK_INCOMPATIBLE, and relational-core's exports/ast.ts exports the new module.
  • The docs: docs/reference/error-reference.md, docs/reference/query-patterns.md and skills/prisma-8/references/queries-postgres.md now show the ORM methods beside the builder's, and say that a lock lasts until the transaction ends.
  • projects/select-row-locking/ gains this slice's plan, and its design.md now points to ADR 261.

The new tests are lock-capability.test.ts, lock-capability.test-d.ts and select-locking-plan.test.ts in the ORM, locking.test.ts and locking.types.test-d.ts in relational-core, a bindSelectAst case in where-binding.test.ts, and test/integration/test/sql-orm-client/lock.test.ts.

What changes for people outside this repo

The pending upgrade notes in upgrade-instructions/pending/orm-row-locking/ say the same.

What the tests prove

The unit and type tests cover:

  • that each method and option exists only with its capabilities;
  • the rendered SQL for every method, option and polymorphic shape;
  • every refusal in the table above.

The integration tests run each form inside a transaction against PGlite. They assert the exact SQL the runtime sent and the whole row returned. They read xmax to show the transaction holds the lock where a plain read does not. They include FOR UPDATE OF "tasks" next to two LEFT JOINs on the polymorphism fixture, which Postgres accepts.

PGlite serves one connection, so no test here shows a second transaction waiting, skipping a row or failing under nowait.

Alternatives considered

ADR 261 argues each of these in full:

  • An of option on the ORM, or no OF at all. Either way, the caller would need to know which tables the lowering joins.
  • Rendering without OF on a target that lacks sql.lockOf. That would lock every joined table, which is what OF prevents.
  • Supporting a lock together with include(). The lock would have to sit on an inner select of the include lowering, with the OF name chosen there. The read-then-write and work-queue patterns do not need it.
  • Refusing a lock outside a transaction. It is legal Postgres and has a real use.

Agent: machiavelli-37

Summary by CodeRabbit

  • New Features
    • Added row-locking methods to ORM collections, with nowait and skipLocked options where supported. Locks target the collection’s model table.
    • Added PostgreSQL support for rendering available lock modes and options.
  • Bug Fixes
    • Incompatible combinations—such as locks with includes, grouping, aggregates, distinct operations, or mutation terminals—are rejected with a clear error.
    • Unsupported locking capabilities and conflicting wait options are reported as errors.
  • Documentation
    • Added guidance and examples for row locking, transaction behavior, work queues, and lock compatibility.

…the SQL builder and the ORM

Proposes forUpdate(), forNoKeyUpdate(), forShare() and forKeyShare() on the typed SQL builder and the ORM client, seven capability flags, a target-neutral LockingClause node on SelectAst, and Postgres and SQLite renderer behaviour. Tracks #30531.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…er code to SQL

Restructured for a reader without context: a grounding example first, the decision second, a diagram of how a call becomes SQL, then each layer from the outside in. Refusals are gathered into one table, jargon is explained on first use, and alternatives come last.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ice 1 spec and plan

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ith distinct, distinctOn, groupBy or having

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ge already uses

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…UNTIME.LOCK_INCOMPATIBLE, documented in the error reference

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…rs locking clauses after OFFSET, and SQLite refuses them

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ocking clause with RUNTIME.AST_UNSUPPORTED like its other unrenderable features

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…orShare and forKeyShare under their capability flags

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…query and which code it uses

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…tion tests and are documented in the query patterns reference

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ually renders, and the joined-alias lock test is named for what it checks

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…names the wait policy, and requires renderer capabilities

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]>
… builder refuses a lock with distinct, distinctOn, groupBy, having or an aggregate under ORM.LOCK_INCOMPATIBLE

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ry caller must pass, and its refusal names the locking-clause feature

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…licy, as Postgres does

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…agg or window function, and the SQL builder's lock refusal asks it

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… lock is held, and the docs, type tests and extension upgrade note cover every locking refusal and API change

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…Share under their capability flags, and each records a lock on the model's table in the collection state

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…IT and OFFSET, and refuses a lock with include, groupBy, aggregate, distinct, distinctOn or a mutation under ORM.LOCK_INCOMPATIBLE

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…and pin the whole SQL for a polymorphic model with no variant, an MTI variant and an STI variant

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…e docs, the prisma-8 skill and the upgrade notes cover them

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ing capability keys

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… when rebuilding a select, since SelectAst.toOptions() is private

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…trength's capability, in the types and at run time, because the ORM always renders OF the model's table

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…cause they always render OF

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 5 commits October 6, 2026 08:12
…nto s2-orm-client

# Conflicts:
#	packages/2-sql/4-lanes/relational-core/src/exports/ast.ts
…uilder

# Conflicts:
#	packages/3-targets/6-adapters/postgres-codec-testkit/src/index.ts
#	packages/3-targets/6-adapters/postgres/src/core/adapter.ts
#	packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
#	packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
#	packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts
#	packages/3-targets/6-adapters/postgres/test/adapter-errors.test.ts
#	packages/3-targets/6-adapters/postgres/test/array-lift-single-evaluation.integration.test.ts
#	packages/3-targets/6-adapters/postgres/test/full-text-lowering.test.ts
#	packages/3-targets/6-adapters/postgres/test/raw-expr-lowering.test.ts
#	packages/3-targets/6-adapters/postgres/test/raw-query-lowering.test.ts
#	packages/3-targets/6-adapters/postgres/test/sql-renderer-namespace-qualification.test.ts
#	packages/3-targets/6-adapters/postgres/test/sql-renderer.cast-policy.test.ts
…uilder

# Conflicts:
#	examples/multi-extension-monorepo/packages/audit/migrations/snapshots/d60ebdd877de6283fafbbe0dc9a4fa13c1197009a53ba95ed37ba04fa3640cb1/contract.json
#	examples/multi-extension-monorepo/packages/feature-flags/migrations/snapshots/9ea058903cdc9636107c83c1a6bbb6c3f28d92d4515cff00c31c2b4e37bb5bd4/contract.json
#	examples/prisma-8-demo/migrations/snapshots/2a89d70379cd3a3a349abc0cd39278d70531afd884e29c5b095bed02f0af0955/contract.json
#	examples/prisma-8-demo/migrations/snapshots/ad6c8696da69df5c3a46cb752b6e0d53fd10f195b394341513d5f6e9c65e43ac/contract.json
#	examples/prisma-8-demo/migrations/snapshots/b601a01134fe52b77d235b926df687360b3fbc46867ddf9cffdb0b909f812ebc/contract.json
#	examples/prisma-8-demo/migrations/snapshots/f865f3034901be5195a6e7c30b3832daa8bea2684457d29d9c7e9cff2e230aba/contract.json
#	examples/prisma-8-postgis-demo/migrations/snapshots/254e34b6bf4a1f74980cfdfb8c038a58e2c06fdc73c1b19bd6f4019373e3ca58/contract.json
#	packages/3-extensions/pgvector/migrations/snapshots/4a96b488a4ce92b434e5f7d6607b6435c0955f0d36b0018077045787764240e6/contract.json
#	packages/3-extensions/postgis/migrations/snapshots/2db551a8a5619d0d97710f29130eaea0eccbdd5238f015ee9d18408d438e0f8a/contract.json
…did not report

The data-type upgrade script rewrites an rc.14 contract to what the
current emitter writes, but it does not add capabilities. This slice
makes the Postgres emitter write seven row-locking capability keys,
so the upgraded contract now differs from the emitted fixtures by
exactly those lines. Users get them by re-emitting, as the
select-row-locking upgrade note says. The test compares against the
emitted fixtures with those seven lines removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Base automatically changed from tml-3402-row-locking-sql-builder to main October 6, 2026 13:24
# Conflicts:
#	packages/3-extensions/sql-orm-client/src/collection.ts
…ame content as slice 1's final commit, merged here already
@wmadden
wmadden added this pull request to the merge queue Oct 7, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Oct 7, 2026
@wmadden
wmadden enabled auto-merge October 7, 2026 07:00
… variant() now takes

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
@wmadden
wmadden removed this pull request from the merge queue due to a manual request Oct 7, 2026
@wmadden
wmadden added this pull request to the merge queue Oct 7, 2026
Merged via the queue into main with commit ecb206f Oct 7, 2026
24 checks passed
@wmadden
wmadden deleted the tml-3415-row-locking-orm-client branch October 7, 2026 16:16
Thegreatsura pushed a commit to Thegreatsura/prisma that referenced this pull request Oct 8, 2026
This deletes `projects/select-row-locking/`, the working folder of the
row locking project. Everything in it now lives somewhere permanent, so
nothing is lost.

Row locks on a select shipped in two pull requests:

```ts
await tx.orm.public.Product.where({ id }).forUpdate().first();
// SELECT ... FOR UPDATE OF "product"
```

- prisma#30549 gave the typed SQL builder `forUpdate()`, `forNoKeyUpdate()`,
`forShare()` and `forKeyShare()`.
- prisma#30555 gave the ORM client the same methods, and closed prisma#30531.

Where the folder's content went:

- The design is ADR 261, merged in prisma#30542.
- `packages/2-sql/4-lanes/sql-builder/STATUS.md` lists row locking as
supported.
- `docs/reference/capabilities.md` documents the seven capabilities.
- The follow-up work is filed in Linear as TML-3492, TML-3493, TML-3494
and TML-3495.

No other file in the repo refers to the folder.

Agent: crusoe-92

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

2 participants