@prisma/orm-postgres 8.0.0-rc.24-dev.27 → 8.0.0-rc.24-dev.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +8 -3
  2. package/dist/components-CWcPJJxx-0zxP3brl.mjs +19 -0
  3. package/dist/components-CWcPJJxx-0zxP3brl.mjs.map +1 -0
  4. package/dist/config.mjs +21 -14
  5. package/dist/config.mjs.map +1 -1
  6. package/dist/{contract-from-json-BVDNIlFO-Ds6x_F9v.mjs → contract-from-json-BQdx9dk3-CHLY5fww.mjs} +3 -3
  7. package/dist/{contract-from-json-BVDNIlFO-Ds6x_F9v.mjs.map → contract-from-json-BQdx9dk3-CHLY5fww.mjs.map} +1 -1
  8. package/dist/contract-types.d.mts +4 -0
  9. package/dist/contract-types.mjs +1 -0
  10. package/dist/control.mjs +2 -8
  11. package/dist/control.mjs.map +1 -1
  12. package/dist/init-quick-reference-prisma7.md +80 -0
  13. package/dist/init-quick-reference.md +95 -0
  14. package/dist/init-readme.md +34 -0
  15. package/dist/init.d.mts +7 -0
  16. package/dist/init.d.mts.map +1 -0
  17. package/dist/init.mjs +272 -0
  18. package/dist/init.mjs.map +1 -0
  19. package/dist/internal__static-context.mjs +1 -1
  20. package/dist/internal__transaction-members.d.mts +1 -1
  21. package/dist/internal__transaction-members.mjs +1 -1
  22. package/dist/internal__validate-contract.mjs +1 -1
  23. package/dist/module-base-C02qpQ9x-BEyIGqx7.mjs +6 -0
  24. package/dist/module-base-C02qpQ9x-BEyIGqx7.mjs.map +1 -0
  25. package/dist/{postgres-members-B7ZvxGYc-D_L3NVGm.mjs → postgres-members-CRPX0rhb-C0keDjWe.mjs} +18 -16
  26. package/dist/postgres-members-CRPX0rhb-C0keDjWe.mjs.map +1 -0
  27. package/dist/{postgres-members-F9CVSrrN-BFAuNPbW.d.mts → postgres-members-DQvChDJ--ByodBWAn.d.mts} +3 -2
  28. package/dist/postgres-members-DQvChDJ--ByodBWAn.d.mts.map +1 -0
  29. package/dist/{postgres-static-BjWEDHSs-Y8MES2qy.mjs → postgres-static-BsLAA6GS-BBKjNHT8.mjs} +3 -3
  30. package/dist/{postgres-static-BjWEDHSs-Y8MES2qy.mjs.map → postgres-static-BsLAA6GS-BBKjNHT8.mjs.map} +1 -1
  31. package/dist/runtime.d.mts +1 -1
  32. package/dist/runtime.mjs +3 -3
  33. package/dist/runtime.mjs.map +1 -1
  34. package/dist/serverless.d.mts +1 -1
  35. package/dist/serverless.mjs +3 -3
  36. package/dist/serverless.mjs.map +1 -1
  37. package/dist/static.mjs +2 -2
  38. package/package.json +12 -10
  39. package/skills/prisma-8/SKILL.md +10 -10
  40. package/skills/prisma-8/references/build.md +12 -16
  41. package/skills/prisma-8/references/contract.md +35 -33
  42. package/skills/prisma-8/references/debug.md +5 -3
  43. package/skills/prisma-8/references/feedback.md +8 -8
  44. package/skills/prisma-8/references/migration-model.md +4 -0
  45. package/skills/prisma-8/references/migration-review.md +6 -5
  46. package/skills/prisma-8/references/migrations.md +73 -26
  47. package/skills/prisma-8/references/queries-mongo.md +3 -3
  48. package/skills/prisma-8/references/queries-postgres.md +25 -9
  49. package/skills/prisma-8/references/queries.md +9 -8
  50. package/skills/prisma-8/references/quickstart.md +19 -19
  51. package/skills/prisma-8/references/runtime.md +23 -23
  52. package/skills/prisma-8/references/supabase.md +7 -7
  53. package/skills/prisma-8/references/upgrade-app.md +1 -1
  54. package/dist/postgres-members-B7ZvxGYc-D_L3NVGm.mjs.map +0 -1
  55. package/dist/postgres-members-F9CVSrrN-BFAuNPbW.d.mts.map +0 -1
@@ -15,9 +15,9 @@ Canonical channels:
15
15
  ## When to Use
16
16
 
17
17
  - A capability-gap entry from another `prisma-8` skill fired and the user said *"yes, file the feature request"*.
18
- - User says *"this is a bug"*, *"file this"*, *"report this"*, *"file an issue against PN"*, *"send feedback"*, *"this should be a feature"*.
18
+ - User says *"this is a bug"*, *"file this"*, *"report this"*, *"file an issue against Prisma 8"*, *"send feedback"*, *"this should be a feature"*.
19
19
  - User describes an unexpected behaviour — wrong exit code, error message that didn't match what happened, type signature that doesn't match runtime behaviour, planner refused a migration that looked safe — and wants it on the framework team's radar.
20
- - User asks *"can I ask the Prisma team about this?"*, *"is there somewhere I can talk to the team?"*, *"is this the intended way to do X?"*, *"how should I integrate <my extension / my tool> with PN?"*, or any other open-ended Q&A or design-feedback prompt — including extension authors asking integration questions.
20
+ - User asks *"can I ask the Prisma team about this?"*, *"is there somewhere I can talk to the team?"*, *"is this the intended way to do X?"*, *"how should I integrate <my extension / my tool> with Prisma 8?"*, or any other open-ended Q&A or design-feedback prompt — including extension authors asking integration questions.
21
21
 
22
22
  ## When Not to Use
23
23
 
@@ -71,7 +71,7 @@ The user is filing a GitHub issue. Is it a bug or a feature request?
71
71
 
72
72
  **Feature request** if any of:
73
73
 
74
- - The user wants a capability that doesn't exist yet (most of the *What PN doesn't do yet* entries land here).
74
+ - The user wants a capability that doesn't exist yet (most of the *What Prisma 8 doesn't do yet* entries land here).
75
75
  - The user wants a better error message, an additional CLI flag, a new middleware, an additional bundler plugin, etc.
76
76
 
77
77
  If both — a bug *and* the user wants a related feature — file two separate issues. Mixing them makes the framework team's triage harder.
@@ -80,7 +80,7 @@ If both — a bug *and* the user wants a related feature — file two separate i
80
80
 
81
81
  For **either** kind:
82
82
 
83
- - **Prisma 8 version**: `pnpm ls @internal/postgres` (or `@internal/mongo`). If the project uses a target package, that version is canonical.
83
+ - **Prisma 8 version**: `pnpm ls @prisma/orm-postgres` (or `@prisma/orm-mongo`). If the project uses a target package, that version is canonical.
84
84
  - **Node version**: `node -v`.
85
85
  - **Package manager**: `pnpm` / `npm` / `yarn` / `bun` / `deno`.
86
86
  - **OS**: `darwin` / `linux` / `win32` and the version string is enough.
@@ -98,7 +98,7 @@ For **bug reports**, additionally:
98
98
  For **feature requests**, additionally:
99
99
 
100
100
  - **Desired API or behaviour** — one paragraph. Concrete shape (CLI flag, config field, middleware export, plugin API) where possible.
101
- - **Where the gap surfaces today** — which skill's *What PN doesn't do yet* entry triggered the request, or the workflow the user was trying to complete.
101
+ - **Where the gap surfaces today** — which skill's *What Prisma 8 doesn't do yet* entry triggered the request, or the workflow the user was trying to complete.
102
102
  - **Current workaround**, if any — one sentence (and the skill body the user is following may already say this).
103
103
 
104
104
  ### 4. Render the body
@@ -110,7 +110,7 @@ Bug-report body shape (fields named to match `.github/ISSUE_TEMPLATE/bug_report.
110
110
  ~~~markdown
111
111
  ## Package and version
112
112
 
113
- <e.g. @internal/postgres@0.5.2>
113
+ <e.g. @prisma/orm-postgres@8.0.0-rc.24>
114
114
 
115
115
  ## What happened?
116
116
 
@@ -209,7 +209,7 @@ When step 1 picked the Discord channel (steps 2–7 do not apply):
209
209
  - Extension-author / partner-integration / breaking-change-coordination questions → the public extension-authors channel, or the user can ping a maintainer directly once they're in the server.
210
210
  2. **Help draft the opening message.** Prisma's Discord is searchable; a well-framed opening message gets a faster, more useful answer. The agent drafts a short message with:
211
211
  - One-sentence summary of what the user is trying to do.
212
- - The Prisma 8 version (`pnpm ls @internal/postgres` or equivalent).
212
+ - The Prisma 8 version (`pnpm ls @prisma/orm-postgres` or equivalent).
213
213
  - A short code snippet (PSL excerpt, query, config file) where relevant — redacted the same way as a GitHub issue body (no `DATABASE_URL`, no customer schema names).
214
214
  - The specific question the user wants answered.
215
215
  3. **Do not auto-post.** The agent surfaces the drafted message to the user — *"here's an opening message you can paste into Discord; want to adjust before sending?"* — and lets the user decide whether to paste it as-is, edit it, or pick a different framing.
@@ -241,7 +241,7 @@ When step 1 picked the Discord channel (steps 2–7 do not apply):
241
241
  ## Checklist
242
242
 
243
243
  - [ ] Classified as bug or feature request (not both in one issue).
244
- - [ ] Environment block present: PN version, Node, package manager, OS.
244
+ - [ ] Environment block present: Prisma 8 version, Node, package manager, OS.
245
245
  - [ ] Reproduction is minimal, public-safe, secret-free.
246
246
  - [ ] Schema fragments use original names where safe; renamed to neutral placeholders only where original names would leak confidential domain detail.
247
247
  - [ ] Title in conventional-commit form (`bug(area): …` / `feat(area): …`).
@@ -31,6 +31,10 @@ Consequences worth internalising:
31
31
  - **The graph does not know where your database is.** "Where is my database" is answered by the database's **marker** (a live-DB record of "this database is at hash X") and, offline, by **refs**. Never by the graph.
32
32
  - **The graph does not know where your next migration should start.** The planner has to be told an origin. That is the entire job of refs and `--from`.
33
33
 
34
+ ### What a migration may contain
35
+
36
+ Because a migration is an edge, `db migrate` can run it on any database whose marker is at its `from` hash, however that database got there: created by `db init`, adopted with `db sign`, restored from a backup, or brought along a different path through the graph. Those databases share a schema but not their rows, so every operation must be correct on any of them. A schema change tests the live schema before and after it runs. Most operation factories do this for you, but not all: on Postgres, `createNativeEnumType` and `dropNativeEnumType` emit no checks. A `rawSql` DDL step you write must carry its own precheck and postcheck. A data change is a data transform; on Postgres and Mongo its `check` decides on each database whether there is work to do. `references/migrations.md` § *Data changes go in a data transform* gives the rule, the reason, and what each target checks.
37
+
34
38
  ### Refs — version-controlled pointers
35
39
 
36
40
  A ref is a small committed file, `migrations/<space>/refs/<name>.json` (for your app: `migrations/app/refs/<name>.json`), containing `{ hash, invariants }`. Two roles, by convention:
@@ -27,7 +27,7 @@ The skill teaches *the system's mental model* — what a ref is, what a marker i
27
27
 
28
28
  ### Origin
29
29
 
30
- The **origin** is the database's *current contract hash*. The database carries a row in PN's marker table that records *"this database is at hash X"*. When the CLI runs online (a `--db <url>` is provided, or `db.connection` is set in `prisma.config.ts`), PN reads the marker and that hash is the origin. Offline (no DB connection), the origin is unknown — many commands degrade to listing the on-disk migrations and skip the per-edge applied/pending status.
30
+ The **origin** is the database's *current contract hash*. The database carries a row in Prisma 8's marker table that records *"this database is at hash X"*. When the CLI runs online (a `--db <url>` is provided, or `db.connection` is set in `prisma.config.ts`), Prisma 8 reads the marker and that hash is the origin. Offline (no DB connection), the origin is unknown — many commands degrade to listing the on-disk migrations and skip the per-edge applied/pending status.
31
31
 
32
32
  A live DB is therefore the authoritative source of origin. The "recorded marker" in any other artifact (refs, local cache, your assumptions) is a working copy that can drift; the live DB never does.
33
33
 
@@ -82,7 +82,7 @@ These codes surface on `migration plan`, `migration ref set`, and `db migrate`
82
82
  | `MIGRATION.HASH_NOT_IN_GRAPH` | `migration plan` (non-empty graph) or `migration ref set` | Resolved hash is not a node in the on-disk migration graph — typical when the default `db` ref points past the graph tip after `db update` cycles. | `migration plan --from <reachable-ref>` (e.g. `--from production`); or realign the ref with `migration ref set db <graph-node-hash>`. |
83
83
  | `MIGRATION.SNAPSHOT_MISSING` | `migration plan` | A named ref has no pointer file (`<name>.json`), and the hash being resolved isn't a node in the migration graph either. | `migration ref set <name> <hash>` to create the ref, `db update --advance-ref <name>` to advance it, or pass a hash that is a graph node. |
84
84
  | `MIGRATION.MARKER_MISMATCH` | `db migrate` (pre-DDL, before the runner), `db migrate --show` | Live DB marker hash is not a graph node. Usually a migration the database applied was planned again or deleted. | Follow the error's next actions, and `references/migrations.md` § *A database whose marker is not in the migration graph*. Never reset the database. |
85
- | `MIGRATION.PATH_UNREACHABLE` | `db migrate` (path resolution) | No migration path from the current marker to the resolved target in the on-disk graph. | Read the improved `fix` payload — it names `fromHash` / `targetHash` and suggests `migration plan --from <from> --to <target>`; run `migration list` to inspect the graph. |
85
+ | `MIGRATION.PATH_UNREACHABLE` | `db migrate` (path resolution) | No migration path from the current marker to the resolved target in the on-disk graph. | Read the improved `fix` payload — it names `fromHash` / `targetHash` and prints the `migration plan` and `db migrate` commands to run, with `--to <target>` unless the target is the emitted contract or the space has no migrations yet. When the space named is an extension's, it prints no plan command: install a version of the extension whose migrations start from the contract the database is at; run `migration list` to inspect the graph. |
86
86
 
87
87
  ## Workflow — *"What's about to run on deploy?"*
88
88
 
@@ -105,7 +105,7 @@ If you omit `--db`, the command runs offline: it lists the migrations on disk bu
105
105
 
106
106
  If you omit `--to`, the destination defaults to the contract head — which answers *"is this branch's contract reachable from the database, and how?"*, not *"what runs on deploy"*. Pass the ref explicitly when the question is about a specific environment.
107
107
 
108
- `migration status` summarises each pending migration's operations by class (`additive`, `widening`, `data`, `destructive`) and reports a destructive-op count when destructive operations are present. Surface that count to the user before they merge or deploy — destructive operations are the class that warrants manual review.
108
+ `migration status` summarises each pending migration's operations by class (`additive`, `widening`, `data`, `destructive`) and reports a destructive-op count when destructive operations are present. Surface that count to the user before they merge or deploy. Review `destructive` and `data` operations before deploy: both can change stored data. Then read each pending `migration.ts` against `references/migrations.md` § *Data changes go in a data transform*. These are findings: an insert, update or delete outside a data transform; a Postgres data transform whose query comes from `db.raw.sql` or contains `fns.raw`; a Postgres or Mongo data transform without `check`; and a hand-written `rawSql` step, unless it is DDL that no operation factory expresses and has both a precheck and a postcheck that test the live schema. `rawSql` steps the planner rendered itself are not findings; if you cannot tell who wrote a step, ask the author.
109
109
 
110
110
  ## Workflow — *"What state is each environment at?"*
111
111
 
@@ -113,7 +113,7 @@ Just `migration status --db $URL` for each environment's DB. The marker (origin)
113
113
 
114
114
  ## Concept — concurrent migrations on the same branch point
115
115
 
116
- This used to be called *diamond convergence* in some PN docs; the situation is the same regardless of the label.
116
+ This used to be called *diamond convergence* in some Prisma 8 docs; the situation is the same regardless of the label.
117
117
 
118
118
  **What's happening.** Two topic branches each authored a migration off the same parent contract hash. The first branch merges to `main`; the destination ref (e.g. `production`) advances to that branch's `to` hash. Your branch's migration still has its `from` hash pointing at the *old* parent. The migration graph, after rebase, no longer has a clean path through your migration:
119
119
 
@@ -204,7 +204,8 @@ This skill is intentionally body-only; the underlying CLI reference (`prisma mig
204
204
  - [ ] Read the `migration status` header (it names config, ref, database) and the summary line (it names the origin/destination distance) before reading the per-edge list.
205
205
  - [ ] For concurrent-migration conflicts: re-applied the *core* workflow (edit → plan → apply) rather than following a memorised "diamond convergence" procedure. Ported any data-transform logic from the abandoned `migration.ts` over.
206
206
  - [ ] For a ref-mismatch: investigated *which* piece of state is wrong (DB ahead, DB behind, DB on a divergent branch). Did NOT `migration ref set` to silence the mismatch.
207
- - [ ] Surfaced the destructive-op count from `migration status` (the only operation class that warrants manual review pre-deploy) before the user merges or deploys.
207
+ - [ ] Surfaced the destructive-op count from `migration status` before the user merges or deploys, and reviewed every `destructive` and `data` operation.
208
+ - [ ] Flagged inserts, updates and deletes outside a data transform, Postgres transforms that use `db.raw.sql` or `fns.raw`, Postgres and Mongo transforms without `check`, and hand-written `rawSql` steps, unless they are DDL that no operation factory expresses and have both a precheck and a postcheck that test the live schema. Did NOT flag `rawSql` steps the planner rendered.
208
209
  - [ ] In CI: the deploy job is `prisma db migrate --to <ref> --db $URL` and nothing else. Did NOT rely on a `--dry-run` flag on `db migrate` (no such flag exists).
209
210
  - [ ] Did NOT confuse `--to` with database selection (`--to` picks the destination hash; `--db` picks the database).
210
211
  - [ ] Did NOT use `--ref` (removed; use `--to`).
@@ -40,22 +40,22 @@ Once the contract changes, you choose how the change reaches the database. This
40
40
  - `migration.ts` — TypeScript authoring source, **framework-rendered** by `migration plan` (or `migration new`). You edit specific holes in it (see *Fill a placeholder* below) and re-emit `ops.json` / `migration.json` by running it.
41
41
  - **Contract snapshots.** `migration.ts` imports its bookend contracts from the shared, content-addressed store at `migrations/snapshots/<hex>/contract.json` + `contract.d.ts` (`<hex>` is the contract's 64-hex storage hash) — not from files inside the migration package.
42
42
  - **Self-emit.** Running `node <package dir>/migration.ts` regenerates `ops.json` and `migration.json` from the (possibly edited) TS source. This is the only supported way to update an existing migration package after edits. `<package dir>` is the directory `migration plan` or `migration new` printed; it sits under the config's `migrations.dir` (by default `migrations/app/<dir>`), so the path depends on that setting. The command works from any directory. Without `--config`, the file uses the config whose migrations directory holds it: the nearest `prisma.config.ts` above it, else the one in the working directory; if neither does, it fails with `CLI.MIGRATION_CONFIG_NOT_FOUND`. If you gave the CLI `--config`, pass the same `--config <path>` to the file.
43
- - **`migration.ts` shape.** Framework-rendered. A class `M extends Migration<Start, End>` (from `@internal/postgres/migration` on Postgres, `@prisma/orm-mongo/target/migration` on Mongo — see the framing block below) that assigns the two snapshot imports to `startContractJson` / `endContractJson` (`Start` is `never` and there is no `startContractJson` on a baseline) and has an `operations` getter returning an array of operation values. **On Postgres the operation factories are methods on the base class** (`this.addColumn({...})`, `this.setNotNull({...})`, `this.dataTransform(...)`) taking one options object; free helpers like `col(...)` build the column descriptors they take. **On Mongo they are free factories** (`createIndex(...)`, `dataTransform(...)`) imported beside `Migration`. The file ends with `MigrationCLI.run(import.meta.url, M)` so executing it self-emits.
43
+ - **`migration.ts` shape.** Framework-rendered. A class `M extends Migration<Start, End>` (from `@prisma/orm-postgres/migration` on Postgres, `@prisma/orm-mongo/target/migration` on Mongo — see the framing block below) that assigns the two snapshot imports to `startContractJson` / `endContractJson` (`Start` is `never` and there is no `startContractJson` on a baseline) and has an `operations` getter returning an array of operation values. **On Postgres the operation factories are methods on the base class** (`this.addColumn({...})`, `this.setNotNull({...})`, `this.dataTransform(...)`) taking one options object; free helpers like `col(...)` build the column descriptors they take. **On Mongo they are free factories** (`createIndex(...)`, `dataTransform(...)`) imported beside `Migration`. The file ends with `MigrationCLI.run(import.meta.url, M)` so executing it self-emits.
44
44
  - **`placeholder(slot)`.** A sentinel the planner emits into the rendered `migration.ts` (from the same `.../migration` import as `Migration`) wherever a data transform is needed. Calling `placeholder(...)` at emit time throws `MIGRATION.UNFILLED_PLACEHOLDER` with `meta.slot` naming the hole. The user replaces the `() => placeholder(...)` arrow with a real query-plan closure (Postgres) or fills `dataTransform({ check, run })` sources (Mongo — see *Fill a placeholder*), then self-emits.
45
- - **`this.dataTransform(endContract, name, { check, run })`.** The data-transform factory. `check` is a rowset query whose presence-of-any-row signals "work remains"; `run` is one or more mutation queries that perform the backfill. Both are lazy closures returning query-plans built against `endContract`. The runner wraps `check` as `EXISTS(...)` for precheck and `NOT EXISTS(...)` for postcheck, so the same closure asserts both "there is work" and "the work is done".
45
+ - **`this.dataTransform(contract, name, { check, run })`.** The Postgres data-transform factory. `check` is a rowset query whose presence-of-any-row signals "work remains"; `run` is one or more mutation queries that perform the backfill. Both are lazy closures returning query plans built with the SQL query builder over the end contract. `contract` is the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns, not the imported `endContract` JSON the planner renders (see *Fill a placeholder*). The runner wraps `check` as `EXISTS(...)` for precheck and `NOT EXISTS(...)` for postcheck, so the same closure asserts both "there is work" and "the work is done".
46
46
  - **`pendingPlaceholders`.** A boolean field on the JSON result of `migration plan`. `true` means the package was written but contains unfilled placeholders — `db migrate` will throw `MIGRATION.UNFILLED_PLACEHOLDER` until you edit `migration.ts` and self-emit.
47
47
  - **`migrationHash`.** Content-addressed identity of a migration package. `MIGRATION.HASH_MISMATCH` fires when the stored hash in `migration.json` disagrees with the hash recomputed from the on-disk files (almost always: someone edited `migration.ts` without self-emitting).
48
48
  - **Marker.** Records "this database is at contract hash X for space Y". **Postgres:** a row in `prisma_contract.marker`. **Mongo:** a document in the `_prisma_migrations` collection (keyed by space). Each successful migration advances the marker once schema verification passes for that space. `db sign` writes the marker from the current contract hash, but only after a schema-verification pass succeeds (it will not sign a database whose live schema disagrees with the contract).
49
49
  - **Apply atomicity.** **Postgres:** one `db migrate` run is one transaction — the runner issues a single `BEGIN`, applies every pending migration for every contract space, then one `COMMIT`; any failure issues `ROLLBACK` for the whole run, so the marker stays where it was before the command. **Mongo:** DDL ops (`createCollection`, `createIndex`, `collMod`, `setValidation`, …) are not wrapped in a multi-document transaction; the runner applies ops, verifies the live schema against the destination contract, and advances the marker only on verify-pass (resumable across spaces — see the MongoDB family doc). Ordinary DDL + `dataTransform` flows stay consistent; partial state from failed mid-migration runs is diagnosed with `db verify` / `db schema`, not assumed away.
50
50
  - **Changed foreign key actions and primary keys (Postgres).** A changed `onDelete`/`onUpdate` plans a drop and an add of the foreign key. A moved or removed primary key plans a drop (and an add), and the foreign keys that reference the old key are dropped first and added back after it. These ask no data-loss question.
51
- - **Policies.** A database records in its marker how it may be changed: its *change policy* (`migrate`, `reconcile` or both; `reconcile` is what `db update` and `db sign` do) and its *data protection policy* (`dataLoss` and `accessWidening`, each `forbidden`, `with-consent` or `permitted`; recorded and compared, not yet enforced). A ref declares the policies its database should have in a `policies` field. See *Policies: what a database says about how it may change* below.
52
- - **Operation classes.** Every operation declares an `operationClass`: `additive`, `widening`, `data`, or `destructive`. The CLI surfaces these in the plan preview and in JSON output. There is no `long-running` class and the framework does not emit `CREATE INDEX CONCURRENTLY` — operations stay transactional.
51
+ - **Policies.** A database records in its marker how it may be changed: its *change policy* (`migrate`, `reconcile` or both; `reconcile` is what `db update` and `db sign` do) and its *data protection policy* (`dataLoss` and `accessWidening`, each `forbidden`, `with-consent` or `permitted`). Every command that changes a database obeys both. A ref declares the policies its database should have in a `policies` field. See *Policies: what a database says about how it may change* below.
52
+ - **Operation classes.** Every operation declares an `operationClass`: `additive`, `widening`, `data`, or `destructive`. `additive` adds structure and leaves existing structure and data as they are. `widening` changes existing structure without losing data; an operation that cannot keep every value fails instead, so a tightened constraint such as `SET NOT NULL` is widening. `destructive` can lose rows or values: dropping a table or column, or a type change that can change values. `data` reads and writes rows as its author wrote them, such as a backfill or a type conversion; a `dataTransform` is always `data`. Each operation factory sets its own class (`this.alterColumnType` is `data` with `using` and `destructive` without it, unless you pass `operationClass`). A `rawSql` step you write takes the class of the factory that would express it, or the class the definitions above give. The CLI surfaces these in the plan preview and in JSON output. There is no `long-running` class and the framework does not emit `CREATE INDEX CONCURRENTLY` — operations stay transactional.
53
53
 
54
54
  ## `migration.ts` is framework-rendered, not hand-authored
55
55
 
56
56
  Files under `migrations/<space-id>/<timestamp>/migration.ts` (for your own app, `<space-id>` is always `app/`) are **rendered for you** by the framework — `prisma migration plan` writes a populated package whenever the contract changes, and `prisma migration new` writes an empty scaffold when you want to author operations directly. You do not write these files from scratch. You edit specific holes the framework leaves behind — chiefly replacing `placeholder("<slot>")` sentinels (Postgres) or filling `dataTransform({ check, run })` pipeline slots (Mongo) — then self-emit.
57
57
 
58
- **Postgres** rendered imports point at `@internal/postgres/migration` (or `@internal/sqlite/migration` for SQLite projects): one line carrying `Migration`, `MigrationCLI`, `col`, `placeholder`, `rawSql`, `sql` when the file writes a `sql` value, and any other free helper the operations need.
58
+ **Postgres** rendered imports point at `@prisma/orm-postgres/migration` (or `@prisma/orm-sqlite/migration` for SQLite projects): one line carrying `Migration`, `MigrationCLI`, `col`, `placeholder`, `rawSql`, `sql` when the file writes a `sql` value, and any other free helper the operations need.
59
59
 
60
60
  **Mongo** rendered imports point at one module too, `@prisma/orm-mongo/target/migration`, which carries `Migration`, `MigrationCLI`, `placeholder`, and the operation factories (`createIndex`, `dataTransform`, …). Raw command classes for data transforms come from `@prisma/orm-mongo/query-ast/execution`.
61
61
 
@@ -63,7 +63,7 @@ Treat the rendered import lines as framework-managed on both targets:
63
63
 
64
64
  - Leave them where they are. Don't rewrite them to a different path; the framework's renderer is the authoritative shape and any change you make by hand will be reverted (and may trip `MIGRATION.HASH_MISMATCH`) the next time the package is re-rendered or self-emitted.
65
65
  - If you need an additional helper symbol, **add it to the existing rendered import line** rather than introducing a second import from a different subpath.
66
- - The "user code imports only from `@internal/<target>`" convention applies to *your* own modules (queries, runtime setup, contract authoring). The framework-rendered `migration.ts` scaffold is the framework's surface, not yours; the rule is suspended for that one file.
66
+ - The "user code imports only from `@prisma/orm-<target>`" convention applies to *your* own modules (queries, runtime setup, contract authoring). The framework-rendered `migration.ts` scaffold is the framework's surface, not yours; the rule is suspended for that one file.
67
67
 
68
68
  ## Diagnostic codes you route on
69
69
 
@@ -72,7 +72,7 @@ Treat the rendered import lines as framework-managed on both targets:
72
72
  | `MIGRATION.UNFILLED_PLACEHOLDER` | Throwing `placeholder(...)` at emit time | Open `migration.ts`, replace the `placeholder("<slot>")` call named by `meta.slot` with the real query closure, self-emit. |
73
73
  | `MIGRATION.FILE_MISSING` | Reading a migration package | `migration.ts`, `migration.json`, or `ops.json` is absent. Recover from version control, re-emit via `migration.ts`, or run `prisma migration new` for a fresh one. |
74
74
  | `MIGRATION.INVALID_DEFAULT_EXPORT` | Loading `migration.ts` | The file's default export is not a `Migration` subclass or factory function. Restore the planner-emitted scaffold from version control or re-run `migration plan` for a clean package. |
75
- | `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` | Building a data-transform query plan | The query builder was instantiated with a contract reference different from the `endContract` passed to `this.dataTransform(...)`. Use the `endContract` imported at module scope for both. |
75
+ | `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` | Building a data-transform query plan | The query builder was built over a different contract than the one passed to `this.dataTransform(...)`. Pass the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns to `this.dataTransform`, and build the queries with that client's `sql`. |
76
76
  | `MIGRATION.HASH_MISMATCH` *Migration package is corrupt* | `db migrate` (or any read of the package) | `ops.json` / `migration.json` were edited without self-emitting. Run `node <package dir>/migration.ts` to re-emit, then re-run `db migrate`. |
77
77
  | `CLI.CONSENT_REQUIRED` | `migration plan` / `db update` run with nobody to answer (`--no-interactive`, CI, `--yes`) | The plan would lose data or (on `db update`) widen access. `meta.unanswered` and `nextActions` list each question with the flags that answer it: `--delete <subject>`, `--rename <subject>:<new name>`, `--allow <Model>`. Re-run with the ones you mean. `--confirm` and `--yes` answer none of them. |
78
78
  | `CLI.CONSENT_UNUSED` | `migration plan` / `db update` | Every question was answered, and a `--delete` or `--allow` was left over: a typo, a subject the plan does not touch, or a `--confirm` (which consents to nothing). Fix or drop the flag. A typo next to a question nobody answered is reported as `CLI.CONSENT_REQUIRED` instead, which names the flag that matched nothing. On `db update --dry-run` the same mistake is `MIGRATION.STATEMENT_ANSWERS_NO_QUESTION`. |
@@ -95,7 +95,7 @@ Treat the rendered import lines as framework-managed on both targets:
95
95
  | A deploy says there is no migration path, or `MIGRATION.MARKER_MISMATCH` | See *A database whose marker is not in the migration graph* | Never reset the database. |
96
96
  | Adding a column that needs a backfill | `migration plan --backfill Model.field` (writes `placeholder`), edit `migration.ts`, self-emit, then `db migrate` | `db update` does not author data transforms; the formal path does. Without `--backfill`, existing rows get a temporary value. |
97
97
  | Changing a field's type so values may not survive | `migration plan --convert Model.field`, fill `using`, self-emit, `db migrate` | Or `--delete Model.field` to let the database cast; the cast may cut or round values (Postgres cuts a longer text to a shorter `varchar`), and a value it cannot cast fails the apply. |
98
- | Recovering from drift (DB diverged from contract) | `db sign` after manual fix, *or* `migration plan` if PN can plan the fix | Depends on which side is right. See *Recover from drift* below. |
98
+ | Recovering from drift (DB diverged from contract) | `db sign` after manual fix, *or* `migration plan` if Prisma 8 can plan the fix | Depends on which side is right. See *Recover from drift* below. |
99
99
 
100
100
  ## Dev → ship transition (the `db` ref pattern)
101
101
 
@@ -221,7 +221,7 @@ Fill in any data transforms (see *Fill a placeholder*), self-emit if you edited
221
221
  pnpm prisma db migrate --db $DATABASE_URL
222
222
  ```
223
223
 
224
- `db migrate` runs without prompting: the data-loss questions were answered when `migration plan` wrote the package. Review destructive ops in the plan output or in `migration show` *before* applying.
224
+ `db migrate` runs without prompting: the data-loss questions were answered when `migration plan` wrote the package. Review `destructive` and `data` operations in the plan output or in `migration show` *before* applying.
225
225
 
226
226
  ## Workflow — Fill a placeholder
227
227
 
@@ -229,13 +229,13 @@ The concept: the planner can detect *that* a data transform is needed but not *w
229
229
 
230
230
  ### Postgres
231
231
 
232
- `--backfill` asks the planner for a data transform it cannot write itself, for example to fill a new required column `name` on a table with rows: `pnpm prisma migration plan --name add_user_name --backfill User.name`. Without the flag the rows get a temporary value instead. Each slot is named by the field and the part to fill, `User.name:check` and `User.name:run`. You fill `check` and `run` closures with real query plans built against `endContract`.
232
+ `--backfill` asks the planner for a data transform it cannot write itself, for example to fill a new required column `name` on a table with rows: `pnpm prisma migration plan --name add_user_name --backfill User.name`. Without the flag the rows get a temporary value instead. Each slot is named by the field and the part to fill, `User.name:check` and `User.name:run`. You fill `check` and `run` closures with real query plans built with the SQL query builder over the end contract.
233
233
 
234
234
  The scaffold the planner emits looks like:
235
235
 
236
236
  ```typescript
237
237
  // migrations/app/20260515T1200_add_user_name/migration.ts
238
- import { col, Migration, MigrationCLI, placeholder } from '@internal/postgres/migration';
238
+ import { col, Migration, MigrationCLI, placeholder } from '@prisma/orm-postgres/migration';
239
239
  import type { Contract as End } from '../../snapshots/93f07d1b…c9e1e5a2/contract';
240
240
  import endContract from '../../snapshots/93f07d1b…c9e1e5a2/contract.json' with { type: 'json' };
241
241
  import type { Contract as Start } from '../../snapshots/f62a4154…d07dddc/contract';
@@ -267,14 +267,14 @@ MigrationCLI.run(import.meta.url, M);
267
267
 
268
268
  (`examples/prisma-8-demo/migrations/app/20260810T1108_add_post_engagement_counters/migration.ts` is a committed rendered package to compare against.)
269
269
 
270
- Replace both `placeholder(...)` calls with query-plan closures built from `endContract`. The `check` closure must return a **rowset query whose presence of any row signals "work remains"** — conventionally `<table>.select('id').where(<violation predicate>).limit(1)`. Scalar/aggregate shapes (`count(*)`, `bool_and(...)`) silently break the contract: the runner wraps `check` twice (`EXISTS(...)` for precheck, `NOT EXISTS(...)` for postcheck), and a query that always returns one row makes `EXISTS` always true and `NOT EXISTS` always false.
270
+ Replace both `placeholder(...)` calls with query-plan closures built with the SQL query builder. The `check` closure must return a **rowset query whose presence of any row signals "work remains"** — conventionally `<table>.select('id').where(<violation predicate>).limit(1)`. Scalar/aggregate shapes (`count(*)`, `bool_and(...)`) silently break the contract: the runner wraps `check` twice (`EXISTS(...)` for precheck, `NOT EXISTS(...)` for postcheck), and a query that always returns one row makes `EXISTS` always true and `NOT EXISTS` always false.
271
271
 
272
- Build the query builder against `endContract` so the storage hashes line up — using a different contract reference raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. The cheapest way to get a typed SQL builder over the end contract is the façade itself: `postgres({ contract: contractFromJson<End>(endContract) })` connects lazily, so constructing it inside `migration.ts` opens no connection; its `sql` is the builder and its `contract` is the validated contract to hand to `this.dataTransform`. The filled-in shape is the rendered scaffold above with only the two `placeholder(...)` arrows replaced (the operation list, including the `this.setNotNull({...})` the planner rendered after the transform, stays as rendered):
272
+ Build the query builder over the end contract, and pass the same client's `contract` to `this.dataTransform`; a plan built over a different contract raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. The cheapest way to get a typed SQL builder over the end contract is the façade itself: `postgres({ contract: contractFromJson<End>(endContract) })` connects lazily, so constructing it inside `migration.ts` opens no connection; its `sql` is the builder and its `contract` is the validated contract to hand to `this.dataTransform`. The filled-in shape is the rendered scaffold above with two changes: the two `placeholder(...)` arrows are replaced, and the first argument of `this.dataTransform` is the client's `contract` instead of the imported `endContract`. The planner renders `endContract`, the raw JSON, which is not a validated contract ([prisma/orm#30504](https://github.com/prisma/orm/issues/30504)). The operation list, including the `this.setNotNull({...})` the planner rendered after the transform, stays as rendered:
273
273
 
274
274
  ```typescript
275
- import { col, Migration, MigrationCLI } from '@internal/postgres/migration';
276
- import postgres from '@internal/postgres/runtime';
277
- import { contractFromJson } from '@internal/postgres/static';
275
+ import { col, Migration, MigrationCLI } from '@prisma/orm-postgres/migration';
276
+ import postgres from '@prisma/orm-postgres/runtime';
277
+ import { contractFromJson } from '@prisma/orm-postgres/static';
278
278
  import type { Contract as End } from '../../snapshots/93f07d1b…c9e1e5a2/contract';
279
279
  import endContract from '../../snapshots/93f07d1b…c9e1e5a2/contract.json' with { type: 'json' };
280
280
  import type { Contract as Start } from '../../snapshots/f62a4154…d07dddc/contract';
@@ -381,6 +381,36 @@ MigrationCLI.run(import.meta.url, M);
381
381
 
382
382
  Self-emit the same way: `node <package dir>/migration.ts`.
383
383
 
384
+ ## Data changes go in a data transform
385
+
386
+ **The rule.** A statement that inserts, updates or deletes rows, or selects rows to decide what to write, goes in a data transform (`dataTransform`), never in a `rawSql` step. `rawSql` is for DDL that no operation factory expresses. DDL includes statements that convert stored values as part of a schema change, such as `ALTER COLUMN … TYPE … USING` and SQLite's table recreation: use the operation factory (`this.alterColumnType`, `this.recreateTable`). A `rawSql` step you write carries a precheck and a postcheck that test the live schema, and the class *Operation classes* under *Key Concepts* describes.
387
+
388
+ **Why.** Migrations form a graph (`references/migration-model.md`), and a migration is an edge. `db migrate` can run a migration on any database whose marker is at its `from` hash, however that database got there. Those databases share a schema but not their rows: on one the work is already done, on another it was never needed. A data transform stays correct on all of them for two reasons:
389
+
390
+ - **`check` is the guard.** The runner skips the transform when `check` finds no rows (the work is done or was never needed), runs `run` otherwise, and fails the migration if `check` still finds rows afterwards. `check` is optional in the type, but a transform without it runs `run` on every database and can never refuse, so always write it.
391
+ - **On Postgres, the queries are checked against a contract.** Self-emit checks each query plan against the contract passed to `this.dataTransform` and refuses a mismatch with `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`.
392
+
393
+ A `rawSql` step that changes rows has neither: no contract checks its SQL, and its checks are whatever its author wrote.
394
+
395
+ **What each target checks.**
396
+
397
+ - **Postgres.** `this.dataTransform(contract, name, { check, run })` takes query plans built with the SQL query builder; in `migration.ts`, use the `sql` and `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns. Only builder queries count. A query from the client's raw lane (`db.raw.sql`) or one containing `fns.raw` passes the contract check, because the check compares only the plan's storage hash, but nothing checks its SQL against the contract. Treat it as raw SQL.
398
+ - **SQLite.** `dataTransform({ id, label, table, description, run })`, imported on the rendered `@prisma/orm-sqlite/migration` line, takes `run: () => string`, a SQL string. It has no `check`, and nothing checks the SQL against a contract. It is still the place for a data change on SQLite. Write `run` so that it changes nothing on a database where the work is done, for example `UPDATE … WHERE "col" IS NULL`.
399
+ - **Mongo.** `dataTransform(name, { check, run })` takes Mongo commands, such as the raw command classes in the example above. Nothing checks them against a contract. `check` works as on Postgres.
400
+
401
+ ### When the SQL query builder cannot express the transform (Postgres)
402
+
403
+ Stop, and tell the user which part of the transform the builder cannot express. If the gap is one of these open issues, name the issue instead of filing a new one:
404
+
405
+ - An insert whose rows come from a select ([prisma/orm#30488](https://github.com/prisma/orm/issues/30488)).
406
+ - An update that sets a column from a subquery or a joined table ([prisma/orm#30489](https://github.com/prisma/orm/issues/30489)). Setting a column from another column of the same row works: `db.public.ask.update((row) => ({ stateEnteredAt: row.createdAt }))`.
407
+
408
+ For any other gap, offer to report it through `references/feedback.md`. Then let the user decide how to proceed. Never choose on your own to write the change as raw SQL (`rawSql`, `db.raw.sql` or `fns.raw`) or as a script that runs outside the migration. If the user knowingly chooses another route, record the choice and the reason where the next person will see it: a comment beside the step in `migration.ts`, and the pull request description.
409
+
410
+ ### How a transform refuses bad data
411
+
412
+ Write `check` to find the rows the transform must fix. If `run` leaves any of them behind, for example rows whose values have no valid mapping, the postcheck fails and the migration stops with `MIGRATION.POSTCHECK_FAILED`. On Postgres `meta.failedCheck.operationId` names the transform. On Mongo `meta.operationId` and `meta.name` do. On Postgres the whole run rolls back. On Mongo nothing is undone: the documents `run` already changed stay changed, and operations that ran earlier stay applied; only the marker does not advance. So on Mongo, write `run` so it is safe to run again, for example by filtering on the documents that still need the change. A SQLite transform has no `check`, so it cannot refuse this way. Do not add a raw step that raises an error. If the user wants the offending rows named, run a read-only query that selects them before migrating.
413
+
384
414
  ## Type changes and new required fields
385
415
 
386
416
  Postgres and SQLite first; MongoDB below. `migration plan` cannot see rows, so these rules are about what you state, not what the table holds.
@@ -400,7 +430,7 @@ The concept: the same `Migration` class shape lets you author operations directl
400
430
  pnpm prisma migration new --name <snake_slug>
401
431
  ```
402
432
 
403
- On Postgres the operations are **methods on the `Migration` base class**, each taking one options object (`this.addColumn({ schema, table, column })`); only helpers such as `col(...)` and `rawSql(...)` are imported, on the rendered `@internal/postgres/migration` line. On Mongo the operations are **free factories** imported from `@prisma/orm-mongo/target/migration`. The authoritative list for either target is the base class / module's declaration file in your `node_modules`.
433
+ On Postgres the operations are **methods on the `Migration` base class**, each taking one options object (`this.addColumn({ schema, table, column })`); only helpers such as `col(...)` and `rawSql(...)` are imported, on the rendered `@prisma/orm-postgres/migration` line. On Mongo the operations are **free factories** imported from `@prisma/orm-mongo/target/migration`. The authoritative list for either target is the base class / module's declaration file in your `node_modules`.
404
434
 
405
435
  **Postgres** operations (representative set, all `this.<name>({...})`):
406
436
 
@@ -411,8 +441,8 @@ On Postgres the operations are **methods on the `Migration` base class**, each t
411
441
  - Enums: `createNativeEnumType`, `addNativeEnumValue`, `dropNativeEnumType`.
412
442
  - Row-level security: `enableRowLevelSecurity`, `disableRowLevelSecurity`, `createRlsPolicy`, `renameRlsPolicy`, `dropRlsPolicy`.
413
443
  - Dependencies: `createSchema`, `createExtension`, `dropExtension`, `setExtensionSchema`, `installExtension`.
414
- - Free helpers on the import line: `col`, `primaryKey`, `unique`, `foreignKey`, `checkExpression`, `lit`, `fn` (column and constraint descriptors), and the raw escape hatch `rawSql({ id, label, operationClass, target, precheck, execute, postcheck, ... })`. The runner runs an operation's postchecks first and skips the operation when they all hold, so a `rawSql` postcheck must hold only when the operation's full effect is in place. If you cannot check that, leave `postcheck` empty: the operation then always runs.
415
- - Data transforms: `this.dataTransform(endContract, name, { check, run })`.
444
+ - Free helpers on the import line: `col`, `primaryKey`, `unique`, `foreignKey`, `checkExpression`, `lit`, `fn` (column and constraint descriptors), and `rawSql({ id, label, operationClass, target, precheck, execute, postcheck, ... })` for DDL that no operation factory expresses. Never use `rawSql` for inserts, updates or deletes; see *Data changes go in a data transform*. The runner runs an operation's postchecks first and skips the operation when they all hold, so a `rawSql` postcheck must hold only when the operation's full effect is in place. If you cannot check that, leave `postcheck` empty: the operation then always runs.
445
+ - Data transforms: `this.dataTransform(contract, name, { check, run })`, with the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns.
416
446
 
417
447
  **Mongo** factories (from `@prisma/orm-mongo/target/migration`):
418
448
 
@@ -470,7 +500,17 @@ Every database records two policies in its marker, and every command obeys them.
470
500
 
471
501
  A database that records nothing permits both. Production records `["migrate"]`, so `db update` and `db sign` refuse it with `MIGRATION.CHANGE_POLICY_FORBIDS`. The off-graph error (`MIGRATION.MARKER_MISMATCH`) reads the policy and gives only the recovery it permits.
472
502
 
473
- **Data protection policy.** `dataLoss` and `accessWidening`, each `data-loss-forbidden` / `data-loss-with-consent` / `data-loss-permitted` (and the `access-widening-` forms). `with-consent` is the default and is today's behaviour: `db update` asks, and a migration carries the consent given when it was planned. No command enforces the data protection settings yet: they are recorded and compared with a ref's, and `forbidden` and `permitted` behave as `with-consent` until enforcement is in place. Do not tell a user that `data-loss-forbidden` protects their data today.
503
+ **Data protection policy.** `dataLoss` and `accessWidening`, each `data-loss-forbidden` / `data-loss-with-consent` / `data-loss-permitted` (and the `access-widening-` forms). `with-consent` is the default and is today's behaviour: `db update` asks, and a migration carries the consent given when it was planned. Every command enforces them before it runs anything:
504
+
505
+ | Level | `db update` | `db migrate`, a Composer deploy | `migration plan --to <ref>` |
506
+ |---|---|---|---|
507
+ | `forbidden` | Refuses the change, even with `--delete` or `--allow` | Refuses a run containing a migration that does it | Refuses to write the migration, when the ref declares the level |
508
+ | `with-consent` | Asks (`--delete`, `--rename`, `--allow`) | Runs | Asks about data loss |
509
+ | `permitted` | Does not ask; an unanswered loss is a delete, and `--rename` still applies; a `--delete` or `--allow` given anyway is accepted | Runs | Asks about data loss |
510
+
511
+ A refusal is `MIGRATION.DATA_PROTECTION_FORBIDS`; `meta.operations` lists each refused operation, and for `db migrate` the migration that contains it. Under `forbidden` the operation cannot run on that database at all, and `--delete` or `--allow` changes nothing. If the subject was only renamed, say so with `--rename`; if a field's type changed, plan it with `migration plan --convert`; otherwise keep the model or field in the contract. When `db migrate` refused a recorded migration, first find out whether another database has applied it. If one has, such as staging under a looser policy, keep the migration as it is: it is the record of what that database ran. Tell the user, because the refusing database cannot run it until its policy changes. If none has, and it should have been a rename or a conversion, delete it before planning it again: left on disk, it is still the one `db migrate` runs. Otherwise take the operation out of the migration. Copying the data elsewhere first does not help: the drop is still a drop. Really dropping data from such a database is a decision for whoever owns it, who changes its policy first. Never loosen the policy yourself to get past the refusal.
512
+
513
+ A loss is an operation whose class is `destructive`. An access change is disabling row-level security or dropping a row-level-security policy (Postgres only); `access-widening-forbidden` refuses both, though a dropped policy may narrow access as well as widen it. In a recorded migration these are recognised from the operation itself, so an access change written as raw SQL is not seen: `access-widening-forbidden` does not stop a hand-written `DISABLE ROW LEVEL SECURITY`. Adding a policy, or changing a policy's condition, is not counted as an access change by any command.
474
514
 
475
515
  **Declaring policies.** A ref declares the policies its database should have. Edit the ref file; every key is optional, and a key you leave out declares nothing:
476
516
 
@@ -594,7 +634,7 @@ The concept: the planner cannot tell whether a dropped model or field was meant
594
634
  - `--delete <subject>` lets the data go: `--delete Legacy`, `--delete User.nickname`. A subject no model stores is named by its storage name (`public.audit_log` on Postgres, `audit_log` on SQLite, `profiles.nickname` for a MongoDB field when `db update` has no snapshot of the origin contract) and can only be deleted. On MongoDB, removing a field from a model is asked about, and `--delete` removes it from every document that holds it.
595
635
  - `--rename <subject>:<new name>` keeps it under a new name: `--rename Profile:User`, or for a field `--rename User.nickname:User.handle` (the new name keeps its model). A field of a renamed model is named through the new name (`--delete User.nickname` after `--rename Profile:User`).
596
636
  - On Postgres, namespaces are subjects too. `--rename public.Invoice:billing.Invoice` moves a model to another namespace, creating the schema if needed. `--rename billing:finance` renames a namespace; namespace renames run first, whatever order the flags are in. A namespace removed from the contract is asked about one model at a time, and `--delete billing` answers all of them; a table in it that no contract declares is its own question, `--delete billing.audit_log`. `public` and a schema another contract space declares cannot be renamed. When a name is both a namespace and a model, name the model with its namespace (`app.billing:app.finance`).
597
- - On Postgres and SQLite, enum values are subjects too. A member removed from an enum, or one that stores a new value, is asked about as `Status.ARCHIVED`. `--rename Status.ARCHIVED:Status.RETIRED` replaces the stored value in every row and list that holds it; `--delete Status.ARCHIVED` sets it to NULL in optional columns and takes it out of lists. While rows of a required column hold it, the apply fails with `MIGRATION.PRECHECK_FAILED` and changes nothing; follow its next actions (rename to a new member, or keep the rows by hand). A member renamed with its stored value kept changes nothing. A member that keeps its name but stores a new value, including two members that swap values, is asked about with `--delete` only; the question gives the `migration.ts` edits that keep the data, and under `db update` the way to plan them with `migration plan --from <hash>` or to change it in two runs: first rename the member to a temporary member with a stored value the enum does not use, then rename it back with its final stored value. Renames that shift values along (3 to 4 while 4 to 5) work in one run; renames that move values in a cycle are refused and say how to write them by hand.
637
+ - On Postgres and SQLite, enum values are subjects too. A member removed from an enum is asked about as `Status.ARCHIVED`. `--rename Status.ARCHIVED:Status.RETIRED` replaces the stored value in every row and list that holds it; `--delete Status.ARCHIVED` sets it to NULL in optional columns and takes it out of lists. While rows of a required column hold it, the apply fails with `MIGRATION.PRECHECK_FAILED` and changes nothing; follow its next actions (rename to a new member, or keep the rows by hand). A member renamed with its stored value kept changes nothing. A member that keeps its name but stores a new value (`ARCHIVED = "archived"` to `ARCHIVED = "old"`) needs no statement: the plan replaces the value in every row and list, and asks nothing. Values that shift along (3 to 4 while 4 to 5) work in one run. Values that move in a cycle, such as two members that swap values, are refused, and so is a member that takes the value of another member that keeps it or is removed; each message gives two plans to make the change, each planned and applied before the next. When the first plan removes a member and you answer `--delete`, a required column cannot keep its rows: delete them, or set them to a value the enum keeps, before that plan applies.
598
638
  - On Postgres and SQLite, fields of value objects are subjects too, named through their own value object (`GeoPoint.lat`, never a path from a model). Each statement acts on every column that holds the value object, in a list or nested in another value object:
599
639
  - `--rename GeoPoint.lat:GeoPoint.latitude` renames the key in every object (`this.renameStoredKey(...)`).
600
640
  - `--delete GeoPoint.lng` removes the key from every object (`this.removeStoredKey(...)`).
@@ -629,20 +669,25 @@ In a terminal the command asks each question in turn; type `delete`, `allow`, or
629
669
  4. **Forgetting to self-emit after editing `migration.ts`.** The next `db migrate` either uses the stale `ops.json` (if you only added comments) or fails with `MIGRATION.HASH_MISMATCH` (if you changed operations). Always self-emit.
630
670
  5. **Routine `db verify` after a successful `db update` or `db migrate`.** Redundant on the happy path — reserve `db verify` for drift diagnosis (manual edits, restore, failed `db migrate`).
631
671
  6. **Aggregate `check` closure in Postgres `this.dataTransform`.** Returning `count(*)` or `bool_and(...)` breaks the precheck/postcheck contract — both sides resolve to constants. Use a rowset shape: `select('id').where(<violation>).limit(1)`.
632
- 7. **Two contract references in one migration.** Building a query plan against a different contract than the one passed to `this.dataTransform(endContract, ...)` raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. Always import `endContract` once at module scope and use the same reference.
672
+ 7. **The wrong contract in `this.dataTransform`.** Pass the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns, and build the queries with that client's `sql`. The planner renders the imported `endContract` JSON there, which is not a validated contract ([prisma/orm#30504](https://github.com/prisma/orm/issues/30504)). A query plan built over a different contract raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`.
633
673
  11. **Calling Postgres operations as free functions.** `addColumn('public', 'user', {...})` does not exist as an import; the operations are `this.addColumn({ schema, table, column })` and friends on the `Migration` base class, with `col(...)` building the column. Only `col`, `rawSql`, `placeholder`, `Migration`, and `MigrationCLI` are imported.
634
- 8. **Renaming a model or field without a statement.** The planner cannot tell a rename from a drop and a create, so without a statement it plans a destructive drop+add. State the rename on the command line: `migration plan --name <slug> --rename User:Person --rename Person.email:Person.emailAddress`, or the same `--rename` flags on `db update`. A field is named through its model as the new contract names it. The planner then renames the table or column and the constraints and indexes named after it; on MongoDB it renames the collection, and the field in every document that holds it (only in that variant's documents for a variant's field). On MongoDB a field is named by its name in the contract, as on SQL: `id @map("_id")` is `User.id`. A statement that keeps the stored name, such as `--rename User.name:User.title` where both are stored as `display_name`, plans nothing; one that changes it renames the field in the documents. A field whose `@map` changes while its name stays is planned as a removal of its old stored name, as on SQL, so the plan asks about it; no statement states a stored-name-only change, so to keep the values, edit the planned `migration.ts` to call `renameField(...)` instead, or rename the field in the database yourself before `db update`. For a rename statements do not cover, such as a model that keeps its name but changes its `@@map`, hand-edit `migration.ts` with `...this.renameTable(...)` or `...this.renameColumn(...)` (Postgres, SQLite) or `renameCollection(...)` (MongoDB), then self-emit.
674
+ 8. **Renaming a model or field without a statement.** The planner cannot tell a rename from a drop and a create, so without a statement it plans a destructive drop+add. State the rename on the command line: `migration plan --name <slug> --rename User:Person --rename Person.email:Person.emailAddress`, or the same `--rename` flags on `db update`. A field is named through its model as the new contract names it. The planner then renames the table or column and the constraints and indexes named after it; on MongoDB it renames the collection, and the field in every document that holds it (only in that variant's documents for a variant's field). On MongoDB a field is named by its name in the contract, as on SQL: `id @map("_id")` is `User.id`. A statement that keeps the stored name, such as `--rename User.name:User.title` where both are stored as `display_name`, plans nothing; one that changes it renames the field in the documents. On MongoDB, a field whose `@map` changes while its name stays is planned as a removal of its old stored name, so the plan asks about it; to keep the values, edit the planned `migration.ts` to call `renameField(...)` instead, or rename the field in the database yourself before `db update`. A MongoDB model that keeps its name but changes its `@@map` is the same: hand-edit `migration.ts` with `renameCollection(...)`, then self-emit.
635
675
  9. **Planning with no `db` ref and no `--from` in a project that already has migrations.** The origin falls through to the empty database, which would make the plan a full-create migration; `migration plan` refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN` rather than writing it. Pick the exit that matches your intent — the error lists them, and `references/migration-model.md` § *The trap* explains which to choose.
636
- 10. **Hand-authoring `migration.ts` from a blank file, or rewriting the rendered import line.** Migration files are framework-rendered — let `prisma migration plan` (or `migration new`) render the package, then edit only the holes the framework leaves for you. On Postgres leave the rendered `@internal/postgres/migration` (or `@internal/sqlite/migration`) import path alone; on Mongo leave `@prisma/orm-mongo/target/migration` as rendered. Add symbols to the existing import line rather than introducing new import paths.
676
+ 10. **Hand-authoring `migration.ts` from a blank file, or rewriting the rendered import line.** Migration files are framework-rendered — let `prisma migration plan` (or `migration new`) render the package, then edit only the holes the framework leaves for you, and, until [prisma/orm#30504](https://github.com/prisma/orm/issues/30504) is fixed, the first argument of `this.dataTransform` (see pitfall 7). On Postgres leave the rendered `@prisma/orm-postgres/migration` (or `@prisma/orm-sqlite/migration`) import path alone; on Mongo leave `@prisma/orm-mongo/target/migration` as rendered. Add symbols to the existing import line rather than introducing new import paths.
637
677
  12. **Replaying migrations onto a database that is already ahead.** `db migrate` on a database with no marker runs every migration, skipping operations already applied. When the database is already past a migration (it has `x int8` where the migration adds `x int4`), the run stops at that migration's precheck with `MIGRATION.PRECHECK_FAILED`. Adopt such a database with `prisma db sign` (after `contract infer` if needed), not by replaying history.
638
678
  13. **Running Prisma 7 `migrate` commands against Prisma 8.** Each one answers `CLI.V7_COMMAND` with its Prisma 8 command: `migrate dev` is `contract emit`, `migration plan --name <name>`, then `db migrate --advance-ref db`; `migrate deploy` is `db migrate`; `migrate reset` has no equivalent, because Prisma 8 has no reset: `db update` brings the database to the contract instead, asking before it loses data, but it keeps existing rows and runs no seed steps or data transforms (a database that changes only through migrations is moved with `db migrate`); `migrate status` is `migration status`; `migrate diff` is `db update --dry-run`, or `migration plan` to write a migration package; `migrate resolve` is `db sign <migration>`, which moves the database marker to that migration after checking its schema, but leaves `migration status` without an applied mark. While Prisma 7 still owns the migrations, install Prisma 7's CLI with `npm install --save-dev @prisma/prisma7@7` and run every one of them except `migrate diff`, whose replacement only reads, as `prisma7 migrate <command>` instead; `migrate resolve` runs as `prisma7 migrate resolve --applied <migration>`.
679
+ 14. **Changing rows outside a data transform.** A `rawSql` step that inserts, updates or deletes rows, or a Postgres transform whose query comes from `db.raw.sql` or contains `fns.raw`. Write it in a `dataTransform` (with a `check` on Postgres and Mongo); on Postgres, build its queries with the SQL query builder. *Data changes go in a data transform* explains why. If the builder cannot express it, stop (see *When the SQL query builder cannot express the transform*).
680
+ 15. **A data transform without `check` (Postgres, Mongo).** It runs `run` on every database, including those where the work is already done, and can never refuse bad data. Always write `check`.
681
+ 16. **Passing a statement for a changed `@@map` or `@map` on Postgres or SQLite.** A model or field that keeps its name is the same model or field, so when only `@@map` or `@map` changes, `migration plan` and `db update` rename the table or column, and its constraints and indexes, with no question and no statement. This needs a snapshot of the contract the database is at, and a table whose control policy is `managed` in both contracts. Without a snapshot, the change is planned as a drop and a create and asked about, as before, except a table name whose only change is a capital first letter (`users` to `Users`): that is refused with `MIGRATION.TABLE_NAME_CASE_CHANGED`, whose message gives the steps to rename the table; for a table that is not `managed`, nothing is renamed, and the plan is what that control policy allows. `--rename User:User` is refused with `MIGRATION.STATEMENT_INVALID`, and a `--delete User` left in a script from earlier releases fails with `CLI.CONSENT_UNUSED`. To get an empty table under the new name instead, remove the model in one change and add it back in a second. A rename the planner cannot order is refused with `MIGRATION.PLANNING_FAILED`: two models or fields that swap tables or columns, a chain where one moves to a name another frees, a model that takes the table of a removed one, and a rename statement that moves something into the old name. The message gives two plans through a name nothing uses (`prisma_swap_<name>`), or, for a takeover, a first plan that removes the model or field holding the name; follow it. One swap is not refused by `migration plan`: when two tables or columns of the same shape swap names and nothing else changes, the storage does not change, so `migration plan` reports no change and writes nothing, and the rows are then read as the other model's; `db update` refuses it. Make such a swap through a name nothing uses in the same way. The table is renamed only when everything stored in it moves, so a variant that gains or loses a table of its own is still asked about, as a data migration. MySQL plans no renames, so there a changed `@@map` is still a drop and a create.
639
682
 
640
683
  ## What Prisma 8 doesn't do yet
641
684
 
642
685
  - **Runtime-apply migrations.** Prisma 8 doesn't apply pending migrations from your app's startup code (the "Drizzle pattern" for serverless / edge). Workaround: run `prisma db migrate` from your deploy pipeline before the app starts. If you need runtime-apply built-in, file a feature request via the `references/feedback.md` skill.
643
686
  - **Seeds-as-first-class.** Prisma 8 doesn't ship a `prisma db seed` equivalent. Workaround: write a TypeScript script that imports your `db` instance and runs your setup queries; invoke it from `package.json`'s scripts. If you need first-class seeding, file a feature request via the `references/feedback.md` skill.
644
687
  - **Migration squashing.** Prisma 8 doesn't squash older migrations into a baseline. They accumulate; for very large histories, manual baseline-and-truncate is the path. If you need built-in squashing, file a feature request via the `references/feedback.md` skill.
645
- - **Renames beyond models, fields, namespaces, enum values and value object fields.** `--rename` covers models and fields on Postgres, SQLite and MongoDB. On Postgres it also moves a model to another namespace and renames a namespace (not on MongoDB or SQLite). On Postgres, SQLite and MongoDB it also renames enum values, fields of value objects and variants. It does not rename value objects or native Postgres enum values, and MongoDB refuses enum value swaps and chains (make them as two changes to the contract, each applied before the next). On MongoDB it also refuses `_id`, a field whose stored name contains `.` or starts with `$`, and a time-series collection; each refusal (`MIGRATION.PLANNING_FAILED`) says what to do instead. MongoDB itself accepts such a stored name, but an update reads `.` as a path into embedded documents and `$` as an operator, so the plan cannot rewrite the field: a type change of it is refused the same way, and a removal or a new required value is not written, so the validator change's document check stops the apply while documents do not fit. If you need one of these, file a feature request via the `references/feedback.md` skill.
688
+ - **Renames beyond models, fields, namespaces, enum values and value object fields.** `--rename` covers models and fields on Postgres, SQLite and MongoDB. On Postgres it also moves a model to another namespace and renames a namespace (not on MongoDB or SQLite). On Postgres, SQLite and MongoDB it also renames enum values, fields of value objects and variants. It does not rename value objects or native Postgres enum values, and MongoDB refuses enum value swaps and chains (make them as two changes to the contract, each applied before the next). Swaps and chains of table and column names, and swaps of enum stored values, are refused on Postgres and SQLite too, with the same two-plan route; chains of enum stored values are planned there. On MongoDB it also refuses `_id`, a field whose stored name contains `.` or starts with `$`, and a time-series collection; each refusal (`MIGRATION.PLANNING_FAILED`) says what to do instead. MongoDB itself accepts such a stored name, but an update reads `.` as a path into embedded documents and `$` as an operator, so the plan cannot rewrite the field: a type change of it is refused the same way, and a removal or a new required value is not written, so the validator change's document check stops the apply while documents do not fit. If you need one of these, file a feature request via the `references/feedback.md` skill.
689
+ - **Some data transforms (Postgres).** The SQL query builder cannot yet insert rows from a select ([prisma/orm#30488](https://github.com/prisma/orm/issues/30488)) or set a column from a subquery or a joined table ([prisma/orm#30489](https://github.com/prisma/orm/issues/30489)). There is no workaround inside a migration: stop and let the user decide (see *When the SQL query builder cannot express the transform*).
690
+ - **Contract checks for SQLite and Mongo data transforms.** SQLite's `dataTransform` takes a SQL string and Mongo's takes commands; nothing checks either against a contract. Workaround: write `run` so it is safe to run again, and review it by hand. If you need a checked form, file a feature request via the `references/feedback.md` skill.
646
691
 
647
692
  ## Graph and history commands
648
693
 
@@ -667,8 +712,10 @@ The CLI collects anonymous usage data by default. To opt out, set `PRISMA_DISABL
667
712
  - [ ] Chose the right path: `db update` (a database whose history does not need to be kept) vs `migration plan` + `db migrate` (a change others will receive, or a database that changes only through migrations).
668
713
  - [ ] For `migration plan`: confirmed the output's `from:` line names the intended origin — not `(baseline)` over an existing graph (`references/migration-model.md`).
669
714
  - [ ] For `migration plan`: ran `migration show <dir>` to review before `db migrate`.
670
- - [ ] Filled every `placeholder(...)` in `migration.ts` (if any), built against `endContract`.
715
+ - [ ] Filled every `placeholder(...)` in `migration.ts` (if any). On Postgres: SQL query builder queries over the end contract, and the client's `contract` passed to `this.dataTransform`. On SQLite and Mongo: the forms in *What each target checks*.
671
716
  - [ ] `check` closures are rowset queries, not scalar aggregates.
717
+ - [ ] Every insert, update and delete is in a `dataTransform`, with a `check` on Postgres and Mongo; on Postgres its queries come from the SQL query builder, not `db.raw.sql` or `fns.raw`.
718
+ - [ ] Every `rawSql` step you wrote is DDL that no operation factory expresses, with a precheck and a postcheck that test the live schema.
672
719
  - [ ] Self-emitted (`node <package dir>/migration.ts`) after editing the TS.
673
720
  - [ ] Ran `db migrate` (or `db update`) and saw it complete.
674
721
  - [ ] Used `db verify` only when diagnosing drift — not as a routine post-apply step.
@@ -1,12 +1,12 @@
1
1
  # Prisma 8 — Queries (Mongo)
2
2
 
3
- > Load this guide when `db.ts` imports from `@internal/mongo/runtime`.
3
+ > Load this guide when `db.ts` imports from `@prisma/orm-mongo/runtime`.
4
4
 
5
5
  Shared concepts (result consumption, script teardown, cross-target pitfalls, capability gaps) live in [`queries.md`](./queries.md).
6
6
 
7
7
  ## Key Concepts
8
8
 
9
- **Mongo** (`mongo({ contract, ... })` from `@internal/mongo/runtime`):
9
+ **Mongo** (`mongo({ contract, ... })` from `@prisma/orm-mongo/runtime`):
10
10
 
11
11
  - **`db.orm.<root>`** — ORM, lowercased plural contract root (`db.orm.users`, `db.orm.posts`). Same fluent chaining; `.where({ field: value })` object equality is the idiomatic filter form.
12
12
  - **`db.query`** — typed aggregation-pipeline builder. Start with `db.query.from('<root>')`, chain `.match(...)` / `.project(...)` / `.group(...)` / `.lookup(...)`, terminal with `.build()`. Run via `(await db.runtime()).query(plan)` for anything that returns documents; `execute(plan)` is only for a write you want an affected count from, and it throws `RUNTIME.MONGO_STATISTICS_UNSUPPORTED` on a find or aggregate.
@@ -78,7 +78,7 @@ const posts = await db.orm.posts
78
78
  // → Array<{ title, authorId, createdAt, author: { name, email, ... } }>
79
79
  ```
80
80
 
81
- Relation names match the contract's `@relation` field names. Nested includes follow the same chaining rules as the parent collection.
81
+ Relation names match the contract's `@relation` field names. `.include(...)` takes only the relation name: there is no refinement callback, so the included documents cannot be filtered, ordered or limited, and their own relations are not loaded. Only a reference relation on a single field can be included; an embedded relation is already part of the document, and naming one in `.include(...)` is a type error.
82
82
 
83
83
  ## Workflow — ORM writes
84
84
 
@@ -1,15 +1,15 @@
1
1
  # Prisma 8 — Queries (Postgres)
2
2
 
3
- > Load this guide when `db.ts` imports from `@internal/postgres/runtime`.
3
+ > Load this guide when `db.ts` imports from `@prisma/orm-postgres/runtime`.
4
4
 
5
5
  Shared concepts (result consumption, script teardown, cross-target pitfalls, capability gaps) live in [`queries.md`](./queries.md).
6
6
 
7
7
  ## Key Concepts
8
8
 
9
- **Postgres** (`postgres({ contract, ... })` from `@internal/postgres/runtime`):
9
+ **Postgres** (`postgres({ contract, ... })` from `@prisma/orm-postgres/runtime`):
10
10
 
11
11
  - **`db.orm.<ns>.<Model>`** — ORM, PascalCase model name (`db.orm.public.User`). Fluent `.where(...).select(...).orderBy(...).all()`, fully typed against `Contract`. Default lane for CRUD with relations.
12
- - **`db.sql.<ns>.<table>`** — SQL builder, lowercase storage name (`db.sql.public.user`). Produces a *plan*. A plan that returns rows (`select`, or a write with `.returning(...)`) runs through `db.query(plan)`; a write with no `RETURNING` runs through `db.execute(plan)`, which resolves `{ affectedRows }`. Use when the ORM is too high-level — explicit `JOIN`, computed projections, set operations, window functions.
12
+ - **`db.sql.<ns>.<table>`** — SQL builder, lowercase storage name (`db.sql.public.user`). Produces a *plan*. A plan that returns rows (`select`, or a write with `.returning(...)`) runs through `db.query(plan)`; a write with no `RETURNING` runs through `db.execute(plan)`, which resolves `{ affectedRows }`. Use when the ORM is too high-level — explicit `JOIN`, computed projections, row locks on a plan. The SQL builder has no set operations (`UNION`, `INTERSECT`, `EXCEPT`), no window functions (`OVER (...)`) and no `WITH`; write those as raw SQL with ``db.raw.sql`…` `` (see *A raw-SQL lane* in [`queries.md`](./queries.md)).
13
13
 
14
14
  Reach for the ORM first; drop to `db.sql` when the ORM can't express the shape. Lane choice is local — one query function picks one lane, not the whole app.
15
15
 
@@ -22,8 +22,9 @@ Reach for the ORM first; drop to `db.sql` when the ORM can't express the shape.
22
22
  | Aggregate (count, sum, avg) | **ORM `.aggregate(...)`** | Typed result; works with grouping (`.groupBy(...).aggregate(...)`). |
23
23
  | `INSERT ... RETURNING` / `UPDATE ... RETURNING` typed result | **ORM mutations** (returns updated rows) or **`db.sql.<ns>.<t>.insert(...).returning(...)`** | ORM returns inserted/updated rows; SQL builder exposes `.returning(...)` explicitly. |
24
24
  | Computed projection (e.g. `ST_DistanceSphere(location, point) AS meters`) alongside model fields | **SQL builder (`db.sql.<ns>.<t>`)** | The ORM projects model fields; arbitrary expression projection is the SQL builder's seam. |
25
- | Complex `JOIN`, set operation, window function | **SQL builder** | The ORM doesn't express arbitrary joins. |
26
- | Postgres-specific feature (`LATERAL`, `FILTER`, custom aggregates) | **SQL builder**, falling back to extension operators when the extension provides them | DSL first; extensions can contribute operators (`postgis`, `pgvector`). |
25
+ | Complex `JOIN` | **SQL builder** | The ORM doesn't express arbitrary joins. |
26
+ | Postgres-specific feature (`LATERAL` joins, `DISTINCT ON`, row locks, custom aggregates) | **SQL builder**, falling back to extension operators when the extension provides them | DSL first; extensions can contribute operators (`postgis`, `pgvector`). |
27
+ | Set operation (`UNION`, `INTERSECT`, `EXCEPT`), window function (`ROW_NUMBER() OVER (...)`), `WITH`, aggregate `FILTER (WHERE ...)` | **Raw SQL (``db.raw.sql`…` ``)** | Neither the ORM nor the SQL builder expresses them. Declare the result columns with `.returnsRow({ ... })` so the rows stay typed. |
27
28
 
28
29
  ## Workflow — ORM reads
29
30
 
@@ -299,7 +300,7 @@ await db.orm.public.User.include('posts', (posts) =>
299
300
 
300
301
  A reducer's result type is the one the target declares for that aggregate — the same types *Workflow — Aggregates* tabulates below, including the `null` a field-taking reducer answers for a parent with no related rows. The reducer set is read from the contract, so an operation a target or extension contributes shows up as a reducer under its own name, with no client change.
301
302
 
302
- Nested `1:N → 1:N` includes (e.g. `User → posts → comments`) require the contract to advertise the `lateral` + `jsonAgg` capabilities for the active target. The Postgres adapter advertises both by default, so most apps get this for free; if the type system rejects a nested include with a *missing capability* error, route to `references/contract.md` to add the required capability declarations and use `references/queries.md` for query-shape guidance.
303
+ Nested includes (e.g. `User → posts → comments`) need no setup. On Postgres, SQLite and MySQL the ORM loads a read and all its includes in one statement. On a database whose adapter does not report the `jsonAgg`, `outerReferencesInDerivedTables` and `jsonAggWithoutTruncation` capabilities (MariaDB), it runs one statement per relation instead; `limit`, `offset`, `distinct` and reducers still run in SQL per parent there, but a `.prepared` read with includes is refused with `ORM.CAPABILITY_MISSING`.
303
304
 
304
305
  ## Workflow — ORM writes
305
306
 
@@ -600,10 +601,11 @@ const plan = db.sql.public.cafe
600
601
  .build();
601
602
  const rows = await db.query(plan);
602
603
 
603
- // Self-join with an alias.
604
+ // Self-join: alias both sides, and read each side through its alias.
604
605
  db.sql.public.post
606
+ .as('p1')
605
607
  .innerJoin(db.sql.public.post.as('p2'), (f, fns) => fns.ne(f.p1.userId, f.p2.userId))
606
- // ...
608
+ .select((f) => ({ first: f.p1.id, second: f.p2.id }))
607
609
  .build();
608
610
  ```
609
611
 
@@ -630,6 +632,20 @@ await db.transaction(async (tx) => {
630
632
 
631
633
  The callback's return value passes through `db.transaction(...)`. Capture inserted ids out of the callback and use them downstream after commit.
632
634
 
635
+ `tx.transaction(async (inner) => ...)` runs work in a savepoint inside the transaction, to any depth; `inner` has the same members as `tx`. If its callback throws, only its work rolls back, the error is rethrown, and `tx` can go on: below, the user is committed and the post is not. Await it before using `tx` again: while it runs, `tx` rejects work with `RUNTIME.TRANSACTION_SUSPENDED`. It takes no options.
636
+
637
+ ```typescript
638
+ await db.transaction(async (tx) => {
639
+ await tx.orm.public.User.create({ id, email });
640
+ await tx
641
+ .transaction(async (inner) => {
642
+ await inner.orm.public.Post.create({ userId: id, title: 'draft' });
643
+ throw new Error('discard the post');
644
+ })
645
+ .catch(() => {});
646
+ });
647
+ ```
648
+
633
649
  To read a row and then write it without another transaction changing it in between, lock it when you read it. The lock lasts until the transaction ends; outside a transaction it is released when the statement ends.
634
650
 
635
651
  ```typescript
@@ -677,7 +693,7 @@ Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the sam
677
693
  2. **Using `.all()` when you wanted one row.** `.all()` issues no implicit limit. Use `.first()` or `.first({ pk })`.
678
694
  3. **Coalescing `count()` with `?? 0` "just in case".** `count()` is `number`, not `number | null` — SQL answers an empty set with `0`. The `?? 0` belongs on `sum` / `avg` / `min` / `max`, and its zero should match the aggregate's own type (`0` for an integer sum, `0n` for `sumBigInt`, `'0'` where the result is a decimal string).
679
695
  4. **Reaching for `.between(a, b)` on a field proxy.** It doesn't exist. Either chain `.where((m) => m.field.gte(a)).where((m) => m.field.lte(b))` or use `and(m.field.gte(a), m.field.lte(b))` inside one `.where()` clause.
680
- 5. **Importing `and` / `or` / `not` from an internal package.** They are exported from `@prisma/orm-postgres/orm-client`; do not reach into `@internal/sql-orm-client`.
696
+ 5. **Importing `and` / `or` / `not` from an internal package.** They are exported from `@prisma/orm-postgres/orm-client`; do not import them from a platform package such as `@prisma/orm-family-sql`.
681
697
  6. **Trying to `db.sql.from(tables.user)`.** That surface does not exist. The builder is table-shaped: `db.sql.<ns>.<tableName>.select(...)`. There is no `db.schema.tables` either.
682
698
  7. **Reading rows with `execute`.** Plans run through the client: `db.query(plan)` for rows, `db.execute(plan)` for a non-returning write (`{ affectedRows }`). Inside a transaction, `tx.query(plan)` / `tx.execute(plan)`. `execute` never yields rows — a `select` or `.returning(...)` plan passed to it gives you statistics, not data.
683
699
  8. **Setting `capabilities: { lateral: true }` in `prisma.config.ts`.** The ORM config (`ormConfig({...})`) does not take `capabilities`. Capabilities are declared by the active adapter and become part of the emitted contract; the Postgres adapter advertises `lateral`, `jsonAgg`, and `returning` out of the box. Enable extension capabilities through `extensions: [...]` in the config (see `references/contract.md`).