@prisma/orm-mongo 8.0.0-rc.9-dev.13 → 8.0.1-dev.2

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 (150) hide show
  1. package/README.md +48 -8
  2. package/dist/components-CWskH7lF-Dkc9ysZz.mjs +18 -0
  3. package/dist/components-CWskH7lF-Dkc9ysZz.mjs.map +1 -0
  4. package/dist/config.d.mts +14 -5
  5. package/dist/config.d.mts.map +1 -1
  6. package/dist/config.mjs +47 -25
  7. package/dist/config.mjs.map +1 -1
  8. package/dist/contract-builder.d.mts +33 -91
  9. package/dist/contract-builder.d.mts.map +1 -1
  10. package/dist/contract-builder.mjs +23 -7
  11. package/dist/contract-builder.mjs.map +1 -1
  12. package/dist/contract-types.d.mts +3 -0
  13. package/dist/contract-types.mjs +1 -0
  14. package/dist/contract__format-version.d.mts +1 -0
  15. package/dist/contract__format-version.mjs +2 -0
  16. package/dist/contract__internal__format-version.d.mts +1 -0
  17. package/dist/contract__internal__format-version.mjs +2 -0
  18. package/dist/contract__validate-once.d.mts +1 -0
  19. package/dist/contract__validate-once.mjs +2 -0
  20. package/dist/contract__validate-storage.d.mts +1 -0
  21. package/dist/contract__validate-storage.mjs +2 -0
  22. package/dist/control.d.mts +1 -1
  23. package/dist/control.d.mts.map +1 -1
  24. package/dist/control.mjs +3 -9
  25. package/dist/control.mjs.map +1 -1
  26. package/dist/driver__runtime.d.mts +3 -0
  27. package/dist/driver__runtime.mjs +3 -0
  28. package/dist/family-contract__data-type.d.mts +1 -0
  29. package/dist/family-contract__data-type.mjs +2 -0
  30. package/dist/init-quick-reference.md +116 -0
  31. package/dist/init-readme.md +35 -0
  32. package/dist/init.d.mts +7 -0
  33. package/dist/init.d.mts.map +1 -0
  34. package/dist/init.mjs +245 -0
  35. package/dist/init.mjs.map +1 -0
  36. package/dist/migration.d.mts +1 -0
  37. package/dist/migration.mjs +2 -0
  38. package/dist/module-base-B70DHaBE-k_c3Klu4.mjs +6 -0
  39. package/dist/module-base-B70DHaBE-k_c3Klu4.mjs.map +1 -0
  40. package/dist/mongo-static-BrplLPTr-DGOk19X8.mjs +74 -0
  41. package/dist/mongo-static-BrplLPTr-DGOk19X8.mjs.map +1 -0
  42. package/dist/{mongo-static-BdSGXYgQ-DSA-2DiK.d.mts → mongo-static-DabeBtmV-DILuhcbE.d.mts} +18 -5
  43. package/dist/mongo-static-DabeBtmV-DILuhcbE.d.mts.map +1 -0
  44. package/dist/runtime.d.mts +49 -44
  45. package/dist/runtime.d.mts.map +1 -1
  46. package/dist/runtime.mjs +104 -42
  47. package/dist/runtime.mjs.map +1 -1
  48. package/dist/static.d.mts +24 -2
  49. package/dist/static.d.mts.map +1 -0
  50. package/dist/static.mjs +2 -2
  51. package/dist/target__codec-ids.d.mts +1 -0
  52. package/dist/target__codec-ids.mjs +2 -0
  53. package/dist/target__codecs.d.mts +1 -0
  54. package/dist/target__codecs.mjs +2 -0
  55. package/dist/target__data-types.d.mts +1 -0
  56. package/dist/target__data-types.mjs +2 -0
  57. package/dist/target__server-version.d.mts +1 -0
  58. package/dist/target__server-version.mjs +2 -0
  59. package/dist/utils__guards.d.mts +1 -0
  60. package/dist/utils__guards.mjs +2 -0
  61. package/dist/utils__text.d.mts +1 -0
  62. package/dist/utils__text.mjs +2 -0
  63. package/dist/utils__upgrade-guides.d.mts +1 -0
  64. package/dist/utils__upgrade-guides.mjs +2 -0
  65. package/package.json +37 -13
  66. package/skills/prisma-8/SKILL.md +23 -18
  67. package/skills/prisma-8/references/build-a-target-package.md +117 -0
  68. package/skills/prisma-8/references/build.md +12 -16
  69. package/skills/prisma-8/references/contract.md +181 -75
  70. package/skills/prisma-8/references/debug.md +35 -24
  71. package/skills/prisma-8/references/feedback.md +8 -8
  72. package/skills/prisma-8/references/migration-model.md +23 -14
  73. package/skills/prisma-8/references/migration-review.md +23 -52
  74. package/skills/prisma-8/references/migrations.md +294 -80
  75. package/skills/prisma-8/references/queries-mongo.md +53 -17
  76. package/skills/prisma-8/references/queries-postgres.md +345 -34
  77. package/skills/prisma-8/references/queries.md +44 -25
  78. package/skills/prisma-8/references/quickstart.md +25 -22
  79. package/skills/prisma-8/references/runtime.md +172 -72
  80. package/skills/prisma-8/references/supabase.md +22 -19
  81. package/skills/prisma-8/references/upgrade-app.md +57 -22
  82. package/skills/prisma-8/references/upgrade-extension.md +72 -23
  83. package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/instructions.md +1 -1
  84. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.10-to-8.0.0-rc.11/instructions.md +34 -0
  85. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/instructions.md +639 -0
  86. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/multifile-psl/add-use-prisma-8-directive.mjs +60 -0
  87. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/psl-verbatim-table-names/add-model-map.mjs +256 -0
  88. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/instructions.md +332 -0
  89. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts +193 -0
  90. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.13-to-8.0.0-rc.14/instructions.md +489 -0
  91. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/instructions.md +1368 -0
  92. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/scripts/data-type-in-contract/data-type-in-contract.ts +1492 -0
  93. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.15-to-8.0.0-rc.16/instructions.md +108 -0
  94. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.16-to-8.0.0-rc.17/instructions.md +755 -0
  95. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/instructions.md +973 -0
  96. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/scripts/sql-expression-literals-psl/rewrite-sql-strings.mjs +271 -0
  97. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +1862 -0
  98. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/client-takes-contract-value/contract-from-json.ts +597 -0
  99. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/data-type-values/data-type-values.ts +1120 -0
  100. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/default-generators-to-on-create/rewrite-default-generators.mjs +86 -0
  101. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/mongo-field-storage-names/mongo-field-storage-names.ts +304 -0
  102. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/remove-nocheck/remove-nocheck.ts +2462 -0
  103. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +513 -0
  104. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts +1206 -0
  105. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.20-to-8.0.0-rc.21/instructions.md +803 -0
  106. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/instructions.md +586 -0
  107. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/scripts/value-objects-in-storage/value-objects-in-storage.ts +1184 -0
  108. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.22-to-8.0.0-rc.23/instructions.md +480 -0
  109. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.22-to-8.0.0-rc.23/scripts/mongo-index-names/mongo-index-names.ts +317 -0
  110. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/instructions.md +336 -0
  111. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/scripts/mongo-convenience-date-time-types/rewrite-mongo-date-types.ts +220 -0
  112. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/scripts/mongo-type-helpers/rewrite-mongo-field-types.ts +621 -0
  113. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.24-to-8.0.0-rc.25/instructions.md +1561 -0
  114. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.9-to-8.0.0-rc.10/instructions.md +13 -0
  115. package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/instructions.md +1 -1
  116. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.10-to-8.0.0-rc.11/instructions.md +34 -0
  117. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/instructions.md +857 -0
  118. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/scripts/psl-verbatim-table-names/add-model-map.mjs +256 -0
  119. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/instructions.md +504 -0
  120. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/scripts/execution-ref-entry-field/rename-execution-ref-keys.ts +193 -0
  121. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.13-to-8.0.0-rc.14/instructions.md +143 -0
  122. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/instructions.md +2168 -0
  123. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/scripts/data-type-in-contract/data-type-in-contract.ts +1492 -0
  124. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.15-to-8.0.0-rc.16/instructions.md +223 -0
  125. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.16-to-8.0.0-rc.17/instructions.md +583 -0
  126. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/instructions.md +1008 -0
  127. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +2186 -0
  128. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/client-takes-contract-value/contract-from-json.ts +597 -0
  129. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/data-type-values/data-type-values.ts +1120 -0
  130. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/default-generators-to-on-create/rewrite-default-generators.mjs +86 -0
  131. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/mongo-field-storage-names/mongo-field-storage-names.ts +304 -0
  132. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/scripts/remove-nocheck/remove-nocheck.ts +2462 -0
  133. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +381 -0
  134. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/scripts/expand-type-aliases/expand-type-aliases.ts +1206 -0
  135. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.20-to-8.0.0-rc.21/instructions.md +570 -0
  136. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/instructions.md +464 -0
  137. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.22-to-8.0.0-rc.23/instructions.md +410 -0
  138. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/instructions.md +303 -0
  139. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/scripts/mongo-convenience-date-time-types/rewrite-mongo-date-types.ts +220 -0
  140. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/scripts/mongo-type-helpers/rewrite-mongo-field-types.ts +621 -0
  141. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.24-to-8.0.0-rc.25/instructions.md +1593 -0
  142. package/dist/adapter__codec-ids.d.mts +0 -1
  143. package/dist/adapter__codec-ids.mjs +0 -2
  144. package/dist/adapter__codec-types.d.mts +0 -1
  145. package/dist/adapter__codec-types.mjs +0 -2
  146. package/dist/adapter__codecs.d.mts +0 -1
  147. package/dist/adapter__codecs.mjs +0 -2
  148. package/dist/mongo-static-BdSGXYgQ-DSA-2DiK.d.mts.map +0 -1
  149. package/dist/mongo-static-_wy-fC4P-mXlhePy0.mjs +0 -38
  150. package/dist/mongo-static-_wy-fC4P-mXlhePy0.mjs.map +0 -1
@@ -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.runtime().query(plan)`; a write with no `RETURNING` runs through `db.runtime().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
 
@@ -62,6 +63,111 @@ db.orm.public.User.where({ kind: 'admin' });
62
63
 
63
64
  Operators on the field proxy include `.eq`, `.neq`, `.lt`, `.lte`, `.gt`, `.gte`, `.like`, `.ilike`, `.in([...])`, `.isNull()`, `.isNotNull()`. Extensions add target-specific operators on extension-typed columns (`pgvector`'s `.cosineDistance(...)`, `postgis`'s `.within(...)` / `.intersectsBbox(...)` / `.distanceSphere(...)`).
64
65
 
66
+ **Full-text search** is built into the Postgres target, on any text column: `.fullTextMatches(q)` is the predicate, `.fullTextRank(q)` scores a row so you can order by relevance, and `.fullTextHeadline(q)` returns the text with `<b>` around the matches. The argument `q` is a `tsquery`, built with a helper from `@prisma/orm-postgres/target/full-text`. A bare string is a type error, because Postgres would read it as `tsquery` syntax without lowercasing or stemming it. Pick the helper by where the text comes from:
67
+
68
+ - A search box: `websearchToTsquery(input)`. `"an exact phrase"`, `-excluded` and `or` work, and it never errors. `plaintoTsquery` requires every word; `phrasetoTsquery` requires the words in order.
69
+ - User input inside operator syntax, such as typeahead: the `tsquery` tag, `` tsquery`${term}:*` ``. The literal parts are trusted `tsquery` syntax you write. Each interpolated value becomes exactly one quoted term, so user input cannot add operators or break the syntax; an empty value adds no words, like a stop word. A value with several words becomes a phrase: `` tsquery`${'new y'}:*` `` gives `'new':* <-> 'y':*`, so the words must be adjacent and in order, and `:*` applies to each word. Do not put quotes around the interpolation yourself: `` tsquery`'${term}':*` `` is a syntax error for every input. Postgres `to_tsquery` then lowercases and stems every word. `` tsquery({ language: 'german' })`...` `` picks the configuration.
70
+ - Operator syntax you write in full: `toTsquery("'zebra' & !'graze'")`. Malformed text fails at execution, so never pass user input to it; use the `tsquery` tag for that.
71
+
72
+ The four parsers are also `fns` members in the SQL builder. Each takes the text (a string, or a text column of any kind, `varchar` included) and `{ language? }`, and binds the text as a parameter. The `tsquery` tag is an import in both the ORM and the SQL builder. A `tsquery` value read back from a query can be passed straight back as the query.
73
+
74
+ Each operation takes an options object as its second argument. `language` (default `'english'`) is the configuration for the column's `to_tsvector`, the expression the index covers; the parser's or tag's own `language` governs the query side, and the two normally match. It only accepts the configurations a stock PostgreSQL server ships with (`'simple'`, `'german'`, `'french'`, …); `fullTextRank` also takes `normalization` (the `ts_rank` bitmask, 0 to 63) and `coverDensity` (for `ts_rank_cd`); `fullTextHeadline` also takes `startSel`, `stopSel`, `maxWords`, `minWords` and `highlightAll`. Every one of them is written into the SQL as a literal, so anything invalid throws `RUNTIME.ARGUMENT_INVALID` when the query is built.
75
+
76
+ ```typescript
77
+ import { tsquery, websearchToTsquery } from '@prisma/orm-postgres/target/full-text';
78
+
79
+ // ORM: filter by the search-box query, order by relevance. Build the query once and reuse it.
80
+ const q = websearchToTsquery(query);
81
+ const hits = await db.orm.public.Message
82
+ .select('id', 'text')
83
+ .where((m) => m.text.fullTextMatches(q))
84
+ .orderBy((m) => m.text.fullTextRank(q).desc())
85
+ .limit(20)
86
+ .all();
87
+
88
+ // ORM: typeahead, the typed text as a prefix term.
89
+ const suggestions = await db.orm.public.Message
90
+ .select('id', 'text')
91
+ .where((m) => m.text.fullTextMatches(tsquery`${term}:*`))
92
+ .all();
93
+
94
+ // SQL builder: the same query filters and highlights, so the snippet marks what selected the row.
95
+ const snippets = db.sql.public.message
96
+ .select('id')
97
+ .select('snippet', (f, fns) =>
98
+ fns.fullTextHeadline(f.text, q, { startSel: '<mark>', stopSel: '</mark>', maxWords: 20 }),
99
+ )
100
+ .where((f, fns) => fns.fullTextMatches(f.text, q))
101
+ .build();
102
+ ```
103
+
104
+ Without an index Postgres recomputes `to_tsvector` for every row, and it only uses one whose expression is the same `to_tsvector` over the same configuration literal and the same column. `@@fullTextIndex` declares that index for you — pass it the field and, if you use one, the same language:
105
+
106
+ ```prisma
107
+ @@fullTextIndex([text], name: "message_text_search")
108
+ @@fullTextIndex([text], where: sql`archived_at IS NULL`, name: "message_text_search_live")
109
+ ```
110
+
111
+ Give the index and the operation the same `language`: a mismatch raises no error, the query silently falls back to a sequential scan.
112
+
113
+ In a TypeScript contract, the same helper from `@prisma/orm-postgres/contract-builder`:
114
+
115
+ ```typescript
116
+ model('Message', { fields: { id, text } }).sql(({ cols }) => ({
117
+ indexes: [fullTextIndex(cols.text, { name: 'message_text_search' })],
118
+ }));
119
+ ```
120
+
121
+ **Searching several columns with weights.** One index can cover several columns. Each top-level item of the list is a weight group, strongest first; fields in a nested list share a weight:
122
+
123
+ ```prisma
124
+ @@fullTextIndex([[title, subtitle], body], name: "post_search")
125
+ ```
126
+
127
+ **Searching an index in the ORM: `using`.** Every collection has a method under `using` for each full-text index of its model's table, named after the index. It filters to the matching rows and orders them by relevance, best first, and returns the same collection, so it chains like `where`:
128
+
129
+ ```typescript
130
+ const q = websearchToTsquery(query);
131
+ const posts = await db.orm.public.Post.select('id', 'title').using.post_search(q).limit(20).all();
132
+ const mine = await db.orm.public.Post.where({ userId }).using.post_search(q).all();
133
+ const users = await db.orm.public.User
134
+ .include('posts', (posts) => posts.using.post_search(q).limit(3))
135
+ .all();
136
+ ```
137
+
138
+ The relevance order is added where the method is called: an `orderBy` before it sorts first, one after it breaks ties. A custom collection class stays the class, so `this.using.post_search(q)` works in a class method. A model with no full-text index has no full-text methods, and a misspelled name is a type error. With the pgvector extension, `using` also has `<field>_nearest(vector, maxDistance?)` for each vector field, such as `db.orm.public.Post.using.embedding_nearest(v, 0.5)`: nearest by cosine distance first. `using` is reserved: a custom class cannot define its own `using`.
139
+
140
+ **Searching an index by hand: name it.** For anything `using` does not do, such as another order or `fullTextHeadline`, name the full-text index and pass it to `fns.fullTextMatches` and `fns.fullTextRank` in place of a column. The operation searches the document the index was built over, with the index's weight groups and language, so the query always matches the index, Postgres uses it, and a title match ranks above a body match. The index states its language, so passing `language` with one is a type error. An index of another type, or a name the model's table does not have, is a type error too.
141
+
142
+ In the ORM, every `where` and `orderBy` callback receives a second argument `{ fns, indexes }`: `fns` is the SQL builder's functions, and `indexes` holds the indexes of the model's table under the name the contract gave each, `name:` or `map:`. A value from `fns`, such as a rank, has `.asc()` and `.desc()`:
143
+
144
+ ```typescript
145
+ const q = websearchToTsquery(query);
146
+ const posts = await db.orm.public.Post
147
+ .select('id', 'title')
148
+ .where((_p, { fns, indexes }) => fns.fullTextMatches(indexes.post_search, q))
149
+ .orderBy((_p, { fns, indexes }) => fns.fullTextRank(indexes.post_search, q).desc())
150
+ .limit(20)
151
+ .all();
152
+ ```
153
+
154
+ The same argument reaches the callbacks inside an include refinement, a fragment and a relation filter (`some`, `every`, `none`), where the index's columns follow the alias the ORM gives the related table. A condition from `fns` combines with the ORM's `and`, `or` and `not`. The body of a fragment for any model (`db.orm.fragment(fields, body)`) gets `fns` but no indexes.
155
+
156
+ In the SQL builder, a table's `indexes` holds the same references:
157
+
158
+ ```typescript
159
+ const post = db.sql.public.post;
160
+ const posts = post
161
+ .select('id', 'title')
162
+ .where((_f, fns) => fns.fullTextMatches(post.indexes.post_search, q))
163
+ .orderBy((_f, fns) => fns.fullTextRank(post.indexes.post_search, q), { direction: 'desc' })
164
+ .build();
165
+ ```
166
+
167
+ An index read from an aliased table searches that alias's columns, so `post.as('p').indexes.post_search` works in a self-join.
168
+
169
+ To search several columns that no index covers, build the document with `fullTextDocument` from `@prisma/orm-postgres/target/full-text`, which takes the weight groups of columns, and pass the language in the options: `fns.fullTextMatches(fullTextDocument([[f.title, f.subtitle], [f.body]]), q, { language: 'english' })`. Postgres uses an index only for a query over the same document, so a document with another grouping, order or language than an index runs without it, and raises no error. `fullTextHeadline` stays per column. One column, `fns.fullTextMatches(f.title, q)` or `row.title.fullTextMatches(q)`, searches that column and uses a single-field index with the same language.
170
+
65
171
  **There is no `.between(a, b)` operator.** Express ranges either as two chained `.where(...)` clauses (the idiomatic form — clauses AND-compose) or with the `and(...)` combinator inside one clause:
66
172
 
67
173
  ```typescript
@@ -80,7 +186,7 @@ await db.orm.public.Sale
80
186
 
81
187
  The two forms emit the same SQL. Pick chained `.where()` when each clause adds a separate condition that reads as its own thought; pick `and(...)` when one logical predicate happens to have two parts and you want the visual grouping. Don't reach for a `between` helper — there isn't one.
82
188
 
83
- **Combinators** (`and`, `or`, `not`) compose predicates, and **relation predicates** (`.some(...)`, `.none(...)`, `.every(...)`) recurse into a relation. `.some()` and `.none()` take an optional predicate — `u.posts.none()` means "has no posts", `u.posts.some()` means "has at least one" — while `.every(...)` requires one: `u.posts.every((p) => p.published.eq(true))`. The combinators are exported from the façade's `orm-client` subpath:
189
+ **Combinators** (`and`, `or`, `not`) compose predicates, and **relation predicates** (`.some(...)`, `.none(...)`, `.every(...)`) recurse into a relation. `.some()` and `.none()` take an optional predicate — `u.posts.none()` means "has no posts", `u.posts.some()` means "has at least one" — while `.every(...)` requires one: `u.posts.every((p) => p.published.eq(true))`. The combinators are exported from the database package's `orm-client` subpath:
84
190
 
85
191
  ```typescript
86
192
  import { and, or, not } from '@prisma/orm-postgres/orm-client';
@@ -95,7 +201,7 @@ await db.orm.public.User
95
201
  .all();
96
202
  ```
97
203
 
98
- **Sorting and pagination.** `.orderBy(...)` accepts a single lambda or an array of lambdas (each calling `.asc()` / `.desc()` on a field). `.limit(n)` limits; `.offset(n)` offsets.
204
+ **Sorting and pagination.** `.orderBy(...)` accepts a single lambda or an array of lambdas. Each calls `.asc()` / `.desc()` on a field, an extension-operation result, a to-one relation's field, or a to-many relation's `count(...)`. Every `.asc()` / `.desc()` takes `{ nulls: 'first' | 'last' }`. `.limit(n)` limits; `.offset(n)` offsets.
99
205
 
100
206
  ```typescript
101
207
  await db.orm.public.Post
@@ -105,7 +211,7 @@ await db.orm.public.Post
105
211
  .all();
106
212
  ```
107
213
 
108
- **Cursor pagination.** Call `.cursor({ field: lastValue })` after `.orderBy(...)` to resume from a known position. The cursor requires a prior `orderBy` — the type system enforces this. Direction (forward or backward) follows the sort: ascending order means "greater than the cursor value", descending means "less than".
214
+ **Cursor pagination.** Call `.cursor({ field: lastValue })` after `.orderBy(...)` to resume from a known position. `.cursor(...)` and `.distinctOn(...)` require a prior `orderBy` — the type system enforces this on the collection they are called on, so a cast on the argument does not get past it. Direction (forward or backward) follows the sort: ascending order means "greater than the cursor value", descending means "less than".
109
215
 
110
216
  ```typescript
111
217
  const page1 = await db.orm.public.Post
@@ -121,7 +227,29 @@ const page2 = await db.orm.public.Post
121
227
  .all();
122
228
  ```
123
229
 
124
- Cursor keys must match fields in the active `orderBy`. For a composite `orderBy`, pass a value for each ordering column — a partial cursor seeks only on the columns you supply, which gives an incomplete keyset. An empty cursor object is a no-op: you get the unfiltered first page back.
230
+ **Ordering by a relation.** A to-one relation (`1:1`, `N:1`) exposes the related model's orderable fields; a to-many relation (`1:N`, `N:M`) exposes `count(predicate?)`, through the junction for `N:M`. One hop only. Each lowers to a correlated scalar subquery, so the main query gains no join.
231
+
232
+ ```typescript
233
+ await db.orm.public.Post
234
+ .orderBy([(p) => p.author.name.asc(), (p) => p.id.asc()])
235
+ .all();
236
+
237
+ await db.orm.public.User
238
+ .orderBy((u) => u.posts.count((p) => p.views.gt(10)).desc())
239
+ .all();
240
+
241
+ await db.orm.public.User
242
+ .orderBy((u) => u.tags.count().desc())
243
+ .all();
244
+
245
+ await db.orm.public.User
246
+ .orderBy((u) => u.invitedBy.name.desc({ nulls: 'last' }))
247
+ .all();
248
+ ```
249
+
250
+ A missing related row (null foreign key) orders as `NULL`. To-one relations have no `count`; to-many relations expose no fields.
251
+
252
+ Cursor keys must match fields in the active `orderBy`. For a composite `orderBy`, pass a value for each ordering column — a partial cursor seeks only on the columns you supply, which gives an incomplete keyset. An empty cursor object is a no-op: you get the unfiltered first page back. `cursor()` keys on plain columns only: it throws `ORM.ARGUMENT_INVALID` when an active order is a relation field, a relation `count(...)`, an extension-operation result (`fullTextRank`, vector distance) or sets `nulls`. `distinctOn()` throws the same only when one of its leading orders, as many as there are `distinctOn` columns, is not a plain column; relation, count and operation orders after them are fine. Paginate those orders with `.limit(n).offset(n)`.
125
253
 
126
254
  **`.first()` vs `.first({ pk })` vs `.all()`.** Use `.first()` for a single row (issues a `LIMIT 1`); use `.first({ pk })` for primary-key lookups; reserve `.all()` for the genuine many case (no implicit `LIMIT`).
127
255
 
@@ -172,7 +300,7 @@ await db.orm.public.User.include('posts', (posts) =>
172
300
 
173
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.
174
302
 
175
- 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`.
176
304
 
177
305
  ## Workflow — ORM writes
178
306
 
@@ -208,6 +336,145 @@ await db.orm.public.User
208
336
 
209
337
  The ORM returns inserted / updated rows by default. The `.returning(...)` selector lives on the SQL builder (next section), where you build a plan and execute it explicitly.
210
338
 
339
+ **A write needs a filter on every code path.** `update`, `updateAll`, `updateAndCount`, `delete`, `deleteAll` and `deleteAndCount` compile only on a collection that is known to be filtered. A collection that is filtered on one path and not on another is not:
340
+
341
+ ```typescript
342
+ const posts = search ? db.orm.public.Post.where({ title: search }) : db.orm.public.Post;
343
+ await posts.deleteAll(); // error: The 'this' context of type '...' is not assignable to method's 'this' of type 'HasWhere'
344
+ ```
345
+
346
+ Make the write only where the filter was applied, or filter on every path:
347
+
348
+ ```typescript
349
+ if (search) {
350
+ await db.orm.public.Post.where({ title: search }).deleteAll();
351
+ }
352
+ ```
353
+
354
+ The same holds for an `if` with an early return, a `switch`, a loop and a reassigned `let`.
355
+
356
+ **A write refuses what it would ignore.** `updateAll`, `updateAndCount`, `deleteAll` and `deleteAndCount` change every row that matches the filter, and throw `ORM.ARGUMENT_INVALID` on a collection with a `limit`, an `offset`, a `cursor`, `distinct` or `distinctOn`; an `orderBy` is accepted. To change a page of rows, read their ids first and filter on them. `update` and `delete` change the one row `first()` returns, so the order, offset, cursor, `distinct` and `distinctOn` choose it; after `limit(0)` they change nothing and return `null`. `update` with a relation callback finds its row by the filter alone and throws on any of these and on an order.
357
+
358
+ ## Workflow — Custom collection classes
359
+
360
+ A custom collection class gives a model its own named queries. Extend `Collection` and pass the class to the client with the `collections` option. `db.orm` then returns the class for that model, and so does `tx.orm` inside `db.transaction(...)`:
361
+
362
+ ```typescript
363
+ import { Collection, type Filtered, type Ordered, type QueryFragment } from '@prisma/orm-postgres/orm-client';
364
+ import postgres from '@prisma/orm-postgres/runtime';
365
+ import { contractFromJson } from '@prisma/orm-postgres/static';
366
+ import type { Contract } from './prisma/contract.d';
367
+ import contractJson from './prisma/contract.json' with { type: 'json' };
368
+
369
+ class PostCollection extends Collection<Contract, 'Post'> {
370
+ byAuthor(userId: string) {
371
+ return this.where({ userId });
372
+ }
373
+
374
+ newestFirst() {
375
+ return this.orderBy((p) => p.createdAt.desc());
376
+ }
377
+ }
378
+
379
+ export const contract = contractFromJson<Contract>(contractJson);
380
+ export const db = postgres({ contract, url: process.env['DATABASE_URL']!, collections: { Post: PostCollection } });
381
+
382
+ const { Post } = db.orm.public;
383
+ ```
384
+
385
+ `postgresServerless({ contract, collections })` takes the same option, and every connection it opens uses the classes. The client's type carries the classes as its second type parameter: `PostgresClient<Contract, { Post: typeof PostCollection }>`. A parameter typed `PostgresClient<Contract>` still accepts a client with classes.
386
+
387
+ Class methods chain with each other and with the built-in methods, in any order, and after `.include(...)`:
388
+
389
+ ```typescript
390
+ await Post.byAuthor(userId).newestFirst().limit(20).all();
391
+ await Post.where({ title }).byAuthor(userId).all();
392
+ await Post.include('user').newestFirst().all();
393
+ ```
394
+
395
+ After `.select(...)` or `.variant(...)` the class methods are gone: those return the base `Collection` type. Call class methods before them. Inside an include refinement, the related collection is the base `Collection` type, not its registered class.
396
+
397
+ Inside a class body, a class method called on the result of another call loses what that call established. So a class method whose body chains two class methods loses the first call's facts for every caller: with `latest() { return this.byAuthor(id).newestFirst(); }`, `Post.latest()` is known to be ordered but not filtered. The same holds for `.prepared` after `.include(...)` inside the class: it describes the class's row without the included relation. Inside the class, follow a class method with built-in methods (`this.byAuthor(id).orderBy(...)`), or chain the class methods from outside the class, where they keep every fact.
398
+
399
+ `with(fn)` calls a function with the collection and returns its result. The function is a query fragment, described in Workflow — Query fragments below, of type `QueryFragment<In, Out>`, so a query can be written once and applied to any collection of that class:
400
+
401
+ ```typescript
402
+ const newest: QueryFragment<PostCollection, Ordered<PostCollection>> = (posts) => posts.newestFirst();
403
+ await Post.with(newest).limit(20).all();
404
+ ```
405
+
406
+ What a chain has established is part of its type. Write a filtered collection as `Filtered<C>` and an ordered one as `Ordered<C>`; `Filtered<C>` is `C & HasWhere`, the name error messages print. A function that takes `Filtered<PostCollection>` accepts only a collection that is filtered:
407
+
408
+ ```typescript
409
+ function deleteMatching(posts: Filtered<PostCollection>) {
410
+ return posts.deleteAll();
411
+ }
412
+
413
+ await deleteMatching(Post.byAuthor(userId)).toArray();
414
+ ```
415
+
416
+ ## Workflow — Query fragments
417
+
418
+ A piece of a query used in several places is a function. Do not build a filter object and spread it into each query; write a function and pass it to `.where(...)`, `.orderBy(...)` or `.with(...)`. A **row fragment** is a function of the model accessor, and `.where(...)` and `.orderBy(...)` take it. A **query fragment** (a **fragment** for short) is a function from a collection to a collection, and `.with(...)` runs it. A **scope** is a fragment that only imposes conditions on the query, such as `createdSince` below, and is also run with `.with(...)`. When the condition is a function of one row and needs no declared fields, pass a row fragment to `.where(...)`. When the same condition should apply to every model that has some fields, write a scope: it declares the fields, checks them at run time, and returns the collection with the `Filtered` fact. `.with(...)` also runs what `.where(...)` cannot express, such as a shared `select` and `include`, an order, a limit or offset, or a variant.
419
+
420
+ **The same filter on several models.** Define a scope with `db.orm.fragment(fields, body)`; the method is named `fragment` because it cannot know whether the body only filters. Declare each field the fragment needs with the same builder the schema uses, from the `field` and `type` that `@prisma/orm-postgres/contract-builder` exports, adding `.optional()` for a field that may be null. The body sees only those fields:
421
+
422
+ ```typescript
423
+ import { field, type } from '@prisma/orm-postgres/contract-builder';
424
+
425
+ const createdSince = (since: Temporal.Instant) =>
426
+ db.orm.fragment({ createdAt: field.column(type.TimestamptzTemporal()) }, (rows) =>
427
+ rows.where((r) => r.createdAt.gte(since)),
428
+ );
429
+
430
+ await db.orm.public.User.with(createdSince(since)).all();
431
+ await db.orm.public.Post.with(createdSince(since)).deleteAll();
432
+ ```
433
+
434
+ Pick the builder whose codec matches the field's codec in `contract.d.ts`: a PSL `TimestamptzTemporal` is `field.column(type.TimestamptzTemporal())` (`pg/timestamptz-temporal@1`), a `String` is `field.column(type.String())` (`pg/text@1`), a `Uuid` is `field.column(type.Uuid())` (`pg/uuid@1`). `field.column(columnType)` is the explicit form. A package that offers a fragment and does not import the database package writes `{ codecId: 'pg/text@1', nullable: false }`, with a codec of the contract. For a list field such as `String[]`, add `.many()` to the builder or `many: { elementNullable: false }` to the object; for a `String?[]`, whose elements may be null, add `.many({ elementsNullable: true })` or `many: { elementNullable: true }`. Without it the declaration does not match a list field, and with it the element nullability must match too. A list of value objects such as `Address[]` is stored as one `jsonb` value and is still a list: `field.column(jsonbColumn).many()`. The body may call `where`, `orderBy`, `limit` and `offset`. The result keeps the collection's class and records the filter, so `update` and `delete` are allowed after a fragment that filters. `updateAll`, `deleteAll` and their `AndCount` forms change every matching row and throw `ORM.ARGUMENT_INVALID` when the chain has a `limit`, `offset`, `cursor`, `distinct` or `distinctOn`, so do not put a limit in a fragment that will be followed by one of them. `update` and `delete` change the one row `first()` returns, so the order, offset, cursor, `distinct` and `distinctOn` choose it, and after `limit(0)` they change nothing and return `null`; `update` with a relation callback throws on an order, a limit, an offset, a cursor, `distinct` or `distinctOn`, because it finds its row by the filter alone. A model without the field, or with the field under another codec or nullability, is a compile error, and a run-time `ORM.FIELD_UNKNOWN`. A custom collection class carries no namespace in its type, so at compile time it matches only a field that every model of that name has, with the same codec and nullability, and its real namespace is checked at run time. The codec, the nullability, whether the field is a list and the nullability of its elements are compared; the column type's parameters are not, so `field.column(type.Char(36))` (`char(36)`) also matches a `char(10)` field.
435
+
436
+ For a filter used inside a larger `where`, a plain function of the row works too. Type the field with `CodecField<Contract, CodecId, Nullable>`, the type of any field with that codec:
437
+
438
+ ```typescript
439
+ import { and, type CodecField } from '@prisma/orm-postgres/orm-client';
440
+
441
+ type CreatedAt = CodecField<Contract, 'pg/timestamptz-temporal@1'>;
442
+ const created = (since: Temporal.Instant) => (row: { createdAt: CreatedAt }) => row.createdAt.gte(since);
443
+
444
+ await db.orm.public.Post.where((p) => and(created(since)(p), p.title.ilike('%orm%'))).all();
445
+ ```
446
+
447
+ Both forms check values against the codec's type, not the field's. For a field that narrows its codec's values, such as an enum stored as `pg/text@1`, they accept values the field would refuse: `row.kind.eq('superuser')` compiles even when `kind` has no such member. Write a filter on such a field inline, on the model, where the field's own type checks the value.
448
+
449
+ **The same `select` and `include` in several queries.** Define it once with `.fragment(...)` on the model's root collection, such as `db.orm.public.Post`, run it with `.with(...)`, and name its row with `CollectionRowOf`:
450
+
451
+ ```typescript
452
+ import type { CollectionRowOf } from '@prisma/orm-postgres/orm-client';
453
+
454
+ const postSummary = db.orm.public.Post.fragment((posts) =>
455
+ posts.select('id', 'title', 'createdAt').include('tags'),
456
+ );
457
+ type PostSummary = CollectionRowOf<ReturnType<typeof postSummary>>;
458
+
459
+ await db.orm.public.Post.where({ userId }).with(postSummary).limit(20).all();
460
+ await db.orm.public.User.include('posts', (posts) => posts.with(postSummary)).all();
461
+ ```
462
+
463
+ The body receives the plain collection of the model, without a custom class's methods. Apply the fragment before `.select(...)` or `.variant(...)`: it is refused on a collection they narrowed. Its result is always typed as the plain collection, even when the body keeps the row, so a custom class's methods are gone after it, and a filter or order applied before it is not recorded, although an earlier `.where(...)` still runs. `update` and `delete` are refused after it unless the body itself calls `where`, and `cursor` unless the body calls `orderBy`. For a filter on one model, use a class method or `db.orm.fragment`. A fragment for one model refuses a collection of another model or namespace at run time with `ORM.ARGUMENT_INVALID`. Calling `.fragment(...)` on a collection with chained calls throws `ORM.ARGUMENT_INVALID`, because the fragment is built from the model alone; a filter, an order or an include before it, or a receiver typed by a type parameter such as `this` in a class method, is a compile error. Inside a class method, chain on `this` directly instead.
464
+
465
+ **A field to order by, from a request.** Pass the request's string to `orderByField` with the fields the endpoint allows. Do not index the field proxy with the raw string:
466
+
467
+ ```typescript
468
+ import { orderByField } from '@prisma/orm-postgres/orm-client';
469
+
470
+ await db.orm.public.Post
471
+ .orderBy(orderByField(db.orm.public.Post, input.orderBy, input.direction, ['title', 'createdAt']))
472
+ .limit(20)
473
+ .all();
474
+ ```
475
+
476
+ Pass the request's direction string as it is; `undefined` means `'asc'`. The allowed list is required: without it a request could order by a secret field and learn its values from the order of the results. A name outside the list, a relation, a field that cannot be ordered, or a direction other than `'asc'` or `'desc'` throws `ORM.ARGUMENT_INVALID` before the query runs; answer it as a bad request. Only the model's own fields can be named, not the fields of one variant.
477
+
211
478
  ## Workflow — Aggregates
212
479
 
213
480
  ```typescript
@@ -238,17 +505,17 @@ const byKind = await db.orm.public.User
238
505
  | --- | --- | --- |
239
506
  | `count()` | `number` | `0` |
240
507
  | `countBigInt()` | `bigint` | `0n` |
241
- | `sum(field)` over `int2` / `int4` / `int8` / `BigIntNumber` | `number \| null` | `null` (SQL `SUM` over zero rows is `NULL`) |
508
+ | `sum(field)` over `int2` / `int4` / `int8` / `BigInt(as: number)` | `number \| null` | `null` (SQL `SUM` over zero rows is `NULL`) |
242
509
  | `sumBigInt(field)` over any integer | `bigint \| null` | `null` |
243
510
  | `sum(field)` over `float4` / `float8` | `number \| null` | `null` |
244
511
  | `sum(field)` over `numeric` | decimal `string \| null` | `null` |
245
- | `sum(field)` over `UnboundedInt` | `bigint \| null` — that column's own family | `null` |
512
+ | `sum(field)` over `BigInt(storage: numeric)` | `bigint \| null` — that column's own family | `null` |
246
513
  | `avg(field)` over any integer | `number \| null` | `null` |
247
514
  | `avgDecimal(field)` over any integer or `numeric` | decimal `string \| null` | `null` |
248
515
  | `avg(field)` over a float | `number \| null` | `null` |
249
516
  | `min(field)` / `max(field)` | the column's own type `\| null` — `text` where the column is `varchar` | `null` |
250
517
 
251
- **`count()`, and `sum` over an integer column, throw outside ±(2^53 − 1) — they never round.** Those two are the results a guarded integer codec produces. The rows above the guard does not reach: `sum` over `numeric`, `UnboundedInt`, or a float column, and every `avg`, which is a fraction already. The error is `RUNTIME.DECODE_FAILED` (`… value must be an integer within the safe integer range, got …`), and it fires on the include path too. That is the trade the defaults make: a `number` you can compare, serialise, and do arithmetic with, and a loud failure instead of a quietly wrong total. Switch that one call to `sumBigInt` / `countBigInt` where the magnitude is real.
518
+ **`count()`, and `sum` over an integer column, throw outside ±(2^53 − 1) — they never round.** Those two are the results a guarded integer codec produces. The rows above the guard does not reach: `sum` over `numeric`, `BigInt(storage: numeric)`, or a float column, and every `avg`, which is a fraction already. The error is `RUNTIME.DECODE_FAILED` (`… value must be an integer within the safe integer range, got …`), and it fires on the include path too. That is the trade the defaults make: a `number` you can compare, serialise, and do arithmetic with, and a loud failure instead of a quietly wrong total. Switch that one call to `sumBigInt` / `countBigInt` where the magnitude is real.
252
519
 
253
520
  **Float and Decimal columns keep their own family.** `sum` over `numeric` is still a decimal string, and `sum` over `float8` still a `number` — the defaults policy is about integers, and a column whose author chose `numeric` already chose its representation.
254
521
 
@@ -273,7 +540,7 @@ If `?? 0` is showing up on every aggregate, that's a signal you're calling `sum`
273
540
 
274
541
  ## Workflow — SQL builder (`db.sql.<ns>.<table>`)
275
542
 
276
- The concept: `db.sql.<ns>.<table>` is a table-shaped builder that produces a *plan*. The plan is a serialisable description of the query (AST + parameters); you run it through the runtime. Pick the runtime method by the result the plan declares: `db.runtime().query(plan)` for rows (it returns the same `AsyncIterableResult` as `.all()`, so `await` it for an array), `db.runtime().execute(plan)` for a write with no `RETURNING` (it resolves `{ affectedRows }` and returns no rows). The builder gives you the lanes the ORM doesn't express — explicit `JOIN`, arbitrary expression projection, target-specific operations through extension helpers — without dropping to raw SQL.
543
+ The concept: `db.sql.<ns>.<table>` is a table-shaped builder that produces a *plan*. The plan is a serialisable description of the query (AST + parameters); you run it through the client. Pick the method by the result the plan declares: `db.query(plan)` for rows (it returns the same `AsyncIterableResult` as `.all()`, so `await` it for an array), `db.execute(plan)` for a write with no `RETURNING` (it resolves `{ affectedRows }` and returns no rows). The builder gives you the lanes the ORM doesn't express — explicit `JOIN`, arbitrary expression projection, target-specific operations through extension helpers — without dropping to raw SQL.
277
544
 
278
545
  ```typescript
279
546
  // src/queries/posts.ts — adjust the relative import to match file depth.
@@ -286,7 +553,7 @@ const plan = db.sql.public.post
286
553
  .limit(limit)
287
554
  .build();
288
555
 
289
- const rows = await db.runtime().query(plan);
556
+ const rows = await db.query(plan);
290
557
  ```
291
558
 
292
559
  The `.where(...)` callback receives `(fields, fns)` — `fields` is the field proxy (column references), `fns` is the operator namespace (`fns.eq`, `fns.ne`, `fns.gt`, …). Extensions inject extension-shaped helpers into the same `fns` namespace (`fns.distanceSphere`, `fns.cosineDistance`, etc.).
@@ -296,10 +563,10 @@ The `.where(...)` callback receives `(fields, fns)` — `fields` is the field pr
296
563
  ```typescript
297
564
  // Insert and return selected columns. `insert()` takes an array of rows.
298
565
  const plan = db.sql.public.user
299
- .insert([{ email }])
566
+ .insert([{ email, displayName, kind }])
300
567
  .returning('id', 'email')
301
568
  .build();
302
- const [row] = await db.runtime().query(plan);
569
+ const [row] = await db.query(plan);
303
570
 
304
571
  // Update with predicate and returning.
305
572
  const updatePlan = db.sql.public.user
@@ -307,17 +574,19 @@ const updatePlan = db.sql.public.user
307
574
  .where((f, fns) => fns.eq(f.id, userId))
308
575
  .returning('id', 'email')
309
576
  .build();
310
- const rows = await db.runtime().query(updatePlan);
577
+ const rows = await db.query(updatePlan);
311
578
 
312
579
  // Delete with predicate, no RETURNING — `execute` resolves the affected count.
313
580
  const deletePlan = db.sql.public.user
314
581
  .delete()
315
582
  .where((f, fns) => fns.eq(f.id, userId))
316
583
  .build();
317
- const { affectedRows } = await db.runtime().execute(deletePlan);
584
+ const { affectedRows } = await db.execute(deletePlan);
318
585
  ```
319
586
 
320
- `.returning(...)` requires the target adapter to advertise the `returning` capability. The Postgres adapter advertises it by default.
587
+ Each row must include every column that is not nullable and has no default; leaving one out is a type error that names the column. A value typed `T | undefined` for such a column is also an error, so narrow it first.
588
+
589
+ `.returning(...)` requires the contract to require `sql.returning`. `postgres15` to `postgres18` list it.
321
590
 
322
591
  ### Computed projections and joins
323
592
 
@@ -330,18 +599,21 @@ const plan = db.sql.public.cafe
330
599
  .orderBy((f) => f.id, { direction: 'asc' })
331
600
  .limit(limit)
332
601
  .build();
333
- const rows = await db.runtime().query(plan);
602
+ const rows = await db.query(plan);
334
603
 
335
- // Self-join with an alias.
604
+ // Self-join: alias both sides, and read each side through its alias.
336
605
  db.sql.public.post
606
+ .as('p1')
337
607
  .innerJoin(db.sql.public.post.as('p2'), (f, fns) => fns.ne(f.p1.userId, f.p2.userId))
338
- // ...
608
+ .select((f) => ({ first: f.p1.id, second: f.p2.id }))
339
609
  .build();
340
610
  ```
341
611
 
612
+ The SQL builder's `.orderBy(column, { direction, nulls })` takes the same null placement: `.orderBy('invited_by_id', { direction: 'asc', nulls: 'first' })` renders `ORDER BY "invited_by_id" ASC NULLS FIRST`.
613
+
342
614
  ## Workflow — Transactions
343
615
 
344
- The concept: `db.transaction(fn)` opens a transaction and passes a `tx` context to the callback. `tx.orm` and `tx.sql` mirror `db.orm` / `db.sql` but ride the same transaction; `tx.query(plan)` / `tx.execute(plan)` run a SQL-builder plan within it (rows vs affected count, as on the runtime). The transaction commits on the callback's successful return and rolls back on any thrown error.
616
+ The concept: `db.transaction(fn)` opens a transaction and passes a `tx` context to the callback. `tx` offers the client's query members with the same types, and each runs inside the transaction: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query(plan)` (rows) and `execute(plan)` (affected count), plus `toSql`, `enums` and `nativeEnums`. A prepared statement runs on what it is given, so `ps.query(tx, params)` runs inside the transaction. See *Workflow — Transactions* in `references/runtime.md` for raw SQL and `tx.prepare`. The transaction commits on the callback's successful return and rolls back on any thrown error.
345
617
 
346
618
  ```typescript
347
619
  await db.transaction(async (tx) => {
@@ -360,6 +632,42 @@ await db.transaction(async (tx) => {
360
632
 
361
633
  The callback's return value passes through `db.transaction(...)`. Capture inserted ids out of the callback and use them downstream after commit.
362
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
+
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.
650
+
651
+ ```typescript
652
+ await db.transaction(async (tx) => {
653
+ // ORM: locks only the model's own rows (`FOR UPDATE OF "product"`).
654
+ const product = await tx.orm.public.Product.where({ id }).forUpdate().first();
655
+
656
+ // SQL builder: the same lock on a plan.
657
+ const [row] = await tx.query(
658
+ tx.sql.public.product.select('id', 'stock').where((f, fns) => fns.eq(f.id, id)).forUpdate().build(),
659
+ );
660
+
661
+ // Work queue: claim the next unclaimed job, skipping jobs other workers hold.
662
+ const job = await tx.orm.public.Job.where({ state: 'queued' })
663
+ .orderBy((j) => j.createdAt.asc())
664
+ .forUpdate({ skipLocked: true })
665
+ .first();
666
+ });
667
+ ```
668
+
669
+ The four methods are `forUpdate()`, `forNoKeyUpdate()`, `forShare()` and `forKeyShare()`, each with `{ nowait: true }` or `{ skipLocked: true }`. On the ORM a lock cannot be combined with `include`, `groupBy`, `aggregate`, `distinct`, `distinctOn` or a mutation terminal (`ORM.LOCK_INCOMPATIBLE`).
670
+
363
671
  ## Namespace-aware accessors
364
672
 
365
673
  On Postgres both `db.sql` and `db.orm` are keyed by storage namespace (the Postgres schema) — always, not only when a contract declares more than one. A model outside any `namespace { }` block is in `public`:
@@ -368,14 +676,14 @@ On Postgres both `db.sql` and `db.orm` are keyed by storage namespace (the Postg
368
676
  // db.sql.<namespace>.<table>
369
677
  const plan = db.sql.public.user.select('id', 'email').build();
370
678
  const authPlan = db.sql.auth.users.select('id', 'token').build();
371
- const rows = await db.runtime().query(plan);
679
+ const rows = await db.query(plan);
372
680
 
373
681
  // db.orm.<namespace>.<Model>
374
682
  const user = await db.orm.public.User.create({ id: 1, email: 'a@x.io' });
375
683
  const authUser = await db.orm.auth.User.create({ id: 2, token: 'tok' });
376
684
  ```
377
685
 
378
- There is no flat `db.sql.user` / `db.orm.User` on the Postgres façade (`Db` is "one facet per storage namespace, and nothing else"); reaching for one is a type error. The flat spelling belongs to SQLite, whose façade exposes its single unbound namespace directly — see `references/queries.md` § *Namespace-aware accessors*.
686
+ There is no flat `db.sql.user` / `db.orm.User` on the Postgres package (`Db` is "one facet per storage namespace, and nothing else"); reaching for one is a type error. The flat spelling belongs to SQLite, whose database package exposes its single unbound namespace directly — see `references/queries.md` § *Namespace-aware accessors*.
379
687
 
380
688
  Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the same `.include()` syntax; the ORM resolves the correct schema-qualified join automatically.
381
689
 
@@ -385,19 +693,21 @@ Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the sam
385
693
  2. **Using `.all()` when you wanted one row.** `.all()` issues no implicit limit. Use `.first()` or `.first({ pk })`.
386
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).
387
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.
388
- 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`.
389
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.
390
- 7. **Trying to `db.execute(plan)` directly, or reading rows with `execute`.** Plans run through the runtime: `db.runtime().query(plan)` for rows, `db.runtime().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.
391
- 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`).
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.
699
+ 8. **Setting `capabilities: { lateral: true }` in `prisma.config.ts`.** The ORM config (`ormConfig({...})`) does not take `capabilities`. The contract lists every capability it requires in `requiredCapabilities`, beside the path in the contract entry or in `defineContract`, usually `[...postgres18, ...postgresDriver]`, which includes `sql.lateral`, `sql.jsonAgg` and `sql.returning`. To require one more, add its key to that list (see `references/contract.md`).
392
700
  9. **Confabulating a TypedSQL or `.stream()` surface.** Neither exists. Raw SQL does: the client's raw lane, ``db.raw.sql`…` ``. Reusable statements do: `db.prepare(...)` (see *Prepared statements* in [`queries.md`](./queries.md)). Streaming: `for await` over a read terminal or `runtime.query(plan)` — with the caveats in *Streaming* in [`queries.md`](./queries.md).
393
- 10. **Mixing the ORM mutation return with `runtime.query(plan)` / `runtime.execute(plan)`.** ORM terminals issue the query themselves and return rows. The runtime methods are for SQL-builder plans.
394
- 11. **Ordering grouped rows by an aggregate metric.** The grouped collection supports `.orderBy(...)` on group keys plus `.limit(...)` / `.offset(...)`, but it cannot order by an aggregate alias such as `SUM(amount)`. Sorting the materialized aggregate result in JS is fine at small cardinalities; for large grouped result sets, drop to `db.sql.<ns>.<table>`.
701
+ 10. **Mixing the ORM mutation return with `db.query(plan)` / `db.execute(plan)`.** ORM terminals issue the query themselves and return rows. `query` and `execute` are for plans.
702
+ 11. **Adding a `cursor()` to a relation, count, operation or `nulls` order.** It throws `ORM.ARGUMENT_INVALID`. Use `.limit(n).offset(n)`, or order by plain columns.
703
+ 12. **Ordering grouped rows by an aggregate metric.** The grouped collection supports `.orderBy(...)` on group keys plus `.limit(...)` / `.offset(...)`, but it cannot order by an aggregate alias such as `SUM(amount)`. Sorting the materialized aggregate result in JS is fine at small cardinalities; for large grouped result sets, drop to `db.sql.<ns>.<table>`.
704
+ 13. **Locking a parent row with `forUpdate()` while other transactions write rows that reference it.** Every insert or update of a row with a foreign key to the locked row takes `FOR KEY SHARE` on it to check the key, and `FOR KEY SHARE` conflicts with `FOR UPDATE`, so those writes wait and can deadlock. Use `forNoKeyUpdate()`: it still blocks writes to the row, but not the foreign-key check.
395
705
 
396
706
  ## Reference Files
397
707
 
398
- - Example queries under [`examples/prisma-8-demo/src/orm-client/`](examples/prisma-8-demo/src/orm-client/) and [`examples/prisma-8-demo/src/queries/`](examples/prisma-8-demo/src/queries/) — canonical ORM and SQL-builder shapes.
708
+ - Example queries under [`examples/prisma-8-demo/src/orm-client/`](https://github.com/prisma/orm/tree/main/examples/prisma-8-demo/src/orm-client) and [`examples/prisma-8-demo/src/queries/`](https://github.com/prisma/orm/tree/main/examples/prisma-8-demo/src/queries) — canonical ORM and SQL-builder shapes.
399
709
  - ORM client source under `packages/3-extensions/sql-orm-client/src/`.
400
- - SQL builder source under `packages/2-sql/4-lanes/sql-builder/src/`.
710
+ - SQL builder source under `packages/2-sql-family/4-lanes/sql-builder/src/`.
401
711
 
402
712
  ## Checklist
403
713
 
@@ -409,7 +719,8 @@ Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the sam
409
719
  - [ ] Expressed ranges as chained `.where(...)` clauses or a single `and(...)` clause — did NOT reach for a non-existent `.between(...)` operator.
410
720
  - [ ] For cursor pagination, used `.orderBy(...).cursor({ field: lastValue }).limit(n).all()` — did NOT hand-write a `.where(p => p.field.lt(cursor))` workaround when the `.cursor()` API serves the same purpose.
411
721
  - [ ] For ORM combinators, imported `and` / `or` / `not` from `@prisma/orm-postgres/orm-client`.
412
- - [ ] Ran SQL-builder plans via `db.runtime().query(plan)` when they return rows and `db.runtime().execute(plan)` only for non-returning writes (`tx.query` / `tx.execute` inside a transaction). Passed `insert()` an array of rows.
722
+ - [ ] Wrote a query piece shared between places as a function: a query fragment from `db.orm.fragment(fields, body)` or `collection.fragment(body)` run with `.with(...)`, a `where` callback typed with `CodecField`, or `orderByField` for an order parameter from a request.
723
+ - [ ] Ran SQL-builder plans via `db.query(plan)` when they return rows and `db.execute(plan)` only for non-returning writes (`tx.query` / `tx.execute` inside a transaction). Passed `insert()` an array of rows.
413
724
  - [ ] Wrapped multi-statement work in `db.transaction(async (tx) => { ... })` where atomicity matters.
414
725
  - [ ] For top-N grouped aggregates at meaningful scale, dropped to `db.sql.<ns>.<table>` rather than JS-side sort + slice over `groupBy(...).aggregate(...)`.
415
726
  - [ ] Did NOT confabulate TypedSQL, `.stream()`, `db.batch`, `.between(...)`, a collection-level `.count()`, a `capabilities` field on the config, or a `db.sql.from(tables.user)` API — routed to *What Prisma 8 doesn't do yet* / `references/feedback.md` instead. Raw SQL is spelled `db.raw.sql`, not `db.sql.raw`.