@prisma/orm-mongo 8.0.1-dev.5 → 8.0.1-dev.50

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 (215) hide show
  1. package/README.md +6 -5
  2. package/dist/bson.d.mts +2 -1
  3. package/dist/components__runtime.d.mts +3 -1
  4. package/dist/config.d.mts +2 -1
  5. package/dist/config.d.mts.map +1 -1
  6. package/dist/contract-builder.d.mts +11 -12
  7. package/dist/contract-builder.d.mts.map +1 -1
  8. package/dist/contract-types.d.mts +5 -3
  9. package/dist/contract__types.d.mts +3 -1
  10. package/dist/control.d.mts +2 -1
  11. package/dist/control.d.mts.map +1 -1
  12. package/dist/family-contract.d.mts +3 -1
  13. package/dist/family-runtime.d.mts +3 -1
  14. package/dist/family.d.mts +2 -1
  15. package/dist/family__control.d.mts +3 -1
  16. package/dist/init.d.mts +2 -1
  17. package/dist/init.d.mts.map +1 -1
  18. package/dist/migration-tools__aggregate.d.mts +3 -1
  19. package/dist/migration-tools__hash.d.mts +3 -1
  20. package/dist/migration-tools__io.d.mts +3 -1
  21. package/dist/migration-tools__spaces.d.mts +3 -1
  22. package/dist/migration.d.mts +3 -1
  23. package/dist/{mongo-static-CsA9y8_L-Bd252BaW.mjs → mongo-static-b_EkTdd5-xWveruVP.mjs} +4 -4
  24. package/dist/mongo-static-b_EkTdd5-xWveruVP.mjs.map +1 -0
  25. package/dist/orm.d.mts +3 -1
  26. package/dist/query-ast__execution.d.mts +3 -1
  27. package/dist/query-builder.d.mts +3 -1
  28. package/dist/runtime.d.mts +3 -1
  29. package/dist/runtime.d.mts.map +1 -1
  30. package/dist/runtime.mjs +6 -6
  31. package/dist/runtime.mjs.map +1 -1
  32. package/dist/static.d.mts +2 -1
  33. package/dist/static.d.mts.map +1 -1
  34. package/dist/static.mjs +1 -1
  35. package/dist/target.d.mts +2 -1
  36. package/dist/target__codec-ids.d.mts +3 -1
  37. package/dist/target__codec-types.d.mts +3 -1
  38. package/dist/target__migration.d.mts +3 -1
  39. package/dist/target__runtime.d.mts +2 -1
  40. package/dist/value.d.mts +3 -1
  41. package/dist/vite-plugin-contract-emit.d.mts +3 -1
  42. package/package.json +12 -81
  43. package/skills/prisma-8/SKILL.md +9 -9
  44. package/skills/prisma-8/references/contract.md +2 -2
  45. package/skills/prisma-8/references/debug.md +13 -13
  46. package/skills/prisma-8/references/migration-model.md +17 -17
  47. package/skills/prisma-8/references/migration-review.md +21 -21
  48. package/skills/prisma-8/references/migrations.md +58 -42
  49. package/skills/prisma-8/references/queries-mongo.md +9 -8
  50. package/skills/prisma-8/references/queries-postgres.md +59 -16
  51. package/skills/prisma-8/references/queries.md +2 -2
  52. package/skills/prisma-8/references/quickstart.md +11 -11
  53. package/skills/prisma-8/references/runtime.md +5 -5
  54. package/skills/prisma-8/references/scripts/find-detection-hits.ts +57 -0
  55. package/skills/prisma-8/references/upgrade-app.md +81 -24
  56. package/skills/prisma-8/references/upgrade-extension.md +57 -17
  57. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +2482 -0
  58. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-hash-inputs/contract-hash-inputs.ts +2200 -0
  59. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-signature-names/contract-signature-names.ts +759 -0
  60. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/facade-paths-an-application-uses/facade-paths-an-application-uses.ts +689 -0
  61. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/platform-paths-an-extension-uses/platform-paths-an-extension-uses.ts +2053 -0
  62. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/stored-files-format-version/stored-files-format-version.ts +671 -0
  63. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.26-to-8.0.0-rc.27/instructions.md +102 -0
  64. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.27-to-8.0.0-rc.28/instructions.md +5 -0
  65. package/skills/prisma-8/upgrading/extension/upgrades/0.10-to-0.11/instructions.md +2 -1
  66. package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/instructions.md +1 -1
  67. package/skills/prisma-8/upgrading/extension/upgrades/0.8-to-0.9/instructions.md +1 -1
  68. package/skills/prisma-8/upgrading/extension/upgrades/0.9-to-0.10/instructions.md +1 -1
  69. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/instructions.md +2057 -0
  70. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-hash-inputs/contract-hash-inputs.ts +2200 -0
  71. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/contract-signature-names/contract-signature-names.ts +759 -0
  72. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/facade-paths-an-application-uses/facade-paths-an-application-uses.ts +689 -0
  73. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/platform-paths-an-extension-uses/platform-paths-an-extension-uses.ts +2053 -0
  74. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.25-to-8.0.0-rc.26/scripts/stored-files-format-version/stored-files-format-version.ts +671 -0
  75. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.26-to-8.0.0-rc.27/instructions.md +56 -0
  76. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.27-to-8.0.0-rc.28/instructions.md +5 -0
  77. package/dist/adapter.d.mts +0 -1
  78. package/dist/adapter.mjs +0 -2
  79. package/dist/adapter__control.d.mts +0 -3
  80. package/dist/adapter__control.mjs +0 -3
  81. package/dist/adapter__runtime.d.mts +0 -3
  82. package/dist/adapter__runtime.mjs +0 -3
  83. package/dist/components.d.mts +0 -1
  84. package/dist/components.mjs +0 -2
  85. package/dist/components__authoring.d.mts +0 -1
  86. package/dist/components__authoring.mjs +0 -2
  87. package/dist/components__codec.d.mts +0 -1
  88. package/dist/components__codec.mjs +0 -2
  89. package/dist/components__components.d.mts +0 -1
  90. package/dist/components__components.mjs +0 -2
  91. package/dist/components__control.d.mts +0 -1
  92. package/dist/components__control.mjs +0 -2
  93. package/dist/components__emission.d.mts +0 -1
  94. package/dist/components__emission.mjs +0 -2
  95. package/dist/components__execution.d.mts +0 -1
  96. package/dist/components__execution.mjs +0 -2
  97. package/dist/components__ir.d.mts +0 -1
  98. package/dist/components__ir.mjs +0 -2
  99. package/dist/components__psl-ast.d.mts +0 -1
  100. package/dist/components__psl-ast.mjs +0 -2
  101. package/dist/components__utils.d.mts +0 -1
  102. package/dist/components__utils.mjs +0 -2
  103. package/dist/contract.d.mts +0 -1
  104. package/dist/contract.mjs +0 -2
  105. package/dist/contract__apply-specifier-default-control-policy.d.mts +0 -1
  106. package/dist/contract__apply-specifier-default-control-policy.mjs +0 -2
  107. package/dist/contract__contract-validation-error.d.mts +0 -1
  108. package/dist/contract__contract-validation-error.mjs +0 -2
  109. package/dist/contract__default-namespace.d.mts +0 -1
  110. package/dist/contract__default-namespace.mjs +0 -2
  111. package/dist/contract__enum-accessor.d.mts +0 -1
  112. package/dist/contract__enum-accessor.mjs +0 -2
  113. package/dist/contract__format-version.d.mts +0 -1
  114. package/dist/contract__format-version.mjs +0 -2
  115. package/dist/contract__hashing-utils.d.mts +0 -1
  116. package/dist/contract__hashing-utils.mjs +0 -2
  117. package/dist/contract__hashing.d.mts +0 -1
  118. package/dist/contract__hashing.mjs +0 -2
  119. package/dist/contract__internal__format-version.d.mts +0 -1
  120. package/dist/contract__internal__format-version.mjs +0 -2
  121. package/dist/contract__is-plain-record.d.mts +0 -1
  122. package/dist/contract__is-plain-record.mjs +0 -2
  123. package/dist/contract__resolve-domain-model.d.mts +0 -1
  124. package/dist/contract__resolve-domain-model.mjs +0 -2
  125. package/dist/contract__validate-domain.d.mts +0 -1
  126. package/dist/contract__validate-domain.mjs +0 -2
  127. package/dist/contract__validate-once.d.mts +0 -1
  128. package/dist/contract__validate-once.mjs +0 -2
  129. package/dist/contract__validate-storage.d.mts +0 -1
  130. package/dist/contract__validate-storage.mjs +0 -2
  131. package/dist/driver.d.mts +0 -1
  132. package/dist/driver.mjs +0 -2
  133. package/dist/driver__control.d.mts +0 -3
  134. package/dist/driver__control.mjs +0 -3
  135. package/dist/driver__runtime.d.mts +0 -3
  136. package/dist/driver__runtime.mjs +0 -3
  137. package/dist/family-contract__data-type.d.mts +0 -1
  138. package/dist/family-contract__data-type.mjs +0 -2
  139. package/dist/family-contract__entity-kinds.d.mts +0 -1
  140. package/dist/family-contract__entity-kinds.mjs +0 -2
  141. package/dist/family-contract__normal-form.d.mts +0 -1
  142. package/dist/family-contract__normal-form.mjs +0 -2
  143. package/dist/family__control-adapter.d.mts +0 -1
  144. package/dist/family__control-adapter.mjs +0 -2
  145. package/dist/family__ir.d.mts +0 -1
  146. package/dist/family__ir.mjs +0 -2
  147. package/dist/family__migration.d.mts +0 -1
  148. package/dist/family__migration.mjs +0 -2
  149. package/dist/family__pack.d.mts +0 -3
  150. package/dist/family__pack.mjs +0 -3
  151. package/dist/family__runtime.d.mts +0 -1
  152. package/dist/family__runtime.mjs +0 -2
  153. package/dist/family__schema-verify.d.mts +0 -1
  154. package/dist/family__schema-verify.mjs +0 -2
  155. package/dist/migration-tools__contract-snapshot-store.d.mts +0 -1
  156. package/dist/migration-tools__contract-snapshot-store.mjs +0 -2
  157. package/dist/mongo-static-CsA9y8_L-Bd252BaW.mjs.map +0 -1
  158. package/dist/query-ast.d.mts +0 -1
  159. package/dist/query-ast.mjs +0 -2
  160. package/dist/query-ast__control.d.mts +0 -1
  161. package/dist/query-ast__control.mjs +0 -2
  162. package/dist/query-builder__contract-free.d.mts +0 -1
  163. package/dist/query-builder__contract-free.mjs +0 -2
  164. package/dist/target__codecs.d.mts +0 -1
  165. package/dist/target__codecs.mjs +0 -2
  166. package/dist/target__control.d.mts +0 -1
  167. package/dist/target__control.mjs +0 -2
  168. package/dist/target__data-types.d.mts +0 -1
  169. package/dist/target__data-types.mjs +0 -2
  170. package/dist/target__pack.d.mts +0 -3
  171. package/dist/target__pack.mjs +0 -3
  172. package/dist/target__server-version.d.mts +0 -1
  173. package/dist/target__server-version.mjs +0 -2
  174. package/dist/utils.d.mts +0 -1
  175. package/dist/utils.mjs +0 -2
  176. package/dist/utils__abortable.d.mts +0 -1
  177. package/dist/utils__abortable.mjs +0 -2
  178. package/dist/utils__array-equal.d.mts +0 -1
  179. package/dist/utils__array-equal.mjs +0 -2
  180. package/dist/utils__assertions.d.mts +0 -1
  181. package/dist/utils__assertions.mjs +0 -2
  182. package/dist/utils__canonical-stringify.d.mts +0 -1
  183. package/dist/utils__canonical-stringify.mjs +0 -2
  184. package/dist/utils__casts.d.mts +0 -1
  185. package/dist/utils__casts.mjs +0 -2
  186. package/dist/utils__defined.d.mts +0 -1
  187. package/dist/utils__defined.mjs +0 -2
  188. package/dist/utils__guards.d.mts +0 -1
  189. package/dist/utils__guards.mjs +0 -2
  190. package/dist/utils__hash-content.d.mts +0 -1
  191. package/dist/utils__hash-content.mjs +0 -2
  192. package/dist/utils__internal-error.d.mts +0 -1
  193. package/dist/utils__internal-error.mjs +0 -2
  194. package/dist/utils__json.d.mts +0 -1
  195. package/dist/utils__json.mjs +0 -2
  196. package/dist/utils__promise.d.mts +0 -1
  197. package/dist/utils__promise.mjs +0 -2
  198. package/dist/utils__redact-db-url.d.mts +0 -1
  199. package/dist/utils__redact-db-url.mjs +0 -2
  200. package/dist/utils__result.d.mts +0 -1
  201. package/dist/utils__result.mjs +0 -2
  202. package/dist/utils__simplify-deep.d.mts +0 -1
  203. package/dist/utils__simplify-deep.mjs +0 -2
  204. package/dist/utils__structured-error.d.mts +0 -1
  205. package/dist/utils__structured-error.mjs +0 -2
  206. package/dist/utils__suppress-idle-connection-errors.d.mts +0 -1
  207. package/dist/utils__suppress-idle-connection-errors.mjs +0 -2
  208. package/dist/utils__text.d.mts +0 -1
  209. package/dist/utils__text.mjs +0 -2
  210. package/dist/utils__types.d.mts +0 -1
  211. package/dist/utils__types.mjs +0 -2
  212. package/dist/utils__upgrade-guides.d.mts +0 -1
  213. package/dist/utils__upgrade-guides.mjs +0 -2
  214. package/dist/value__mongodb-types.d.mts +0 -1
  215. package/dist/value__mongodb-types.mjs +0 -2
@@ -17,10 +17,10 @@ Reach for the ORM first; drop to `db.query` when the ORM can't express the shape
17
17
 
18
18
  | Need | Choose | Why |
19
19
  |---|---|---|
20
- | Standard CRUD with reference relations | **ORM (`db.orm.<root>`)** | Collection-shaped; object `.where({ ... })`; `.create` / `.update` / `.delete` / `.upsert`. |
20
+ | Standard CRUD with reference relations | **ORM (`db.orm.<root>`)** | Collection-shaped; object `.where({ ... })`; `.create` / `.updateFirst` / `.deleteFirst` / `.upsert`. |
21
21
  | Eager-load a reference relation | **ORM `.include('<relation>')`** | Lowers to `$lookup`; composes with `.where` / `.select` / `.orderBy` / `.limit`. |
22
22
  | Polymorphic root (discriminated variants) | **ORM `.variant('<discriminator value>')`** | Narrows to the variant declaring that value and injects the discriminator filter. |
23
- | Field-level Mongo updates (`$push`, `$inc`, dot-path `$set`) | **ORM `.update((f) => [f.field.inc(1)])`** | Field-accessor callback; plain-object `.update({ ... })` for whole-field replacement. |
23
+ | Field-level Mongo updates (`$push`, `$inc`, dot-path `$set`) | **ORM `.updateFirst((f) => [f.field.inc(1)])`** | Field-accessor callback; plain-object `.updateFirst({ ... })` for whole-field replacement. |
24
24
  | Aggregation pipeline (group, facet, `$lookup` with reshaping) | **Query builder (`db.query.from(...)`)** | Full pipeline surface; typed row shape through `.build()`. |
25
25
  | Typed cross-collection join in a pipeline | **Query builder `.lookup((from) => from('users').on(...).as('author'))`** | `$lookup` with compile-time foreign-root checking. |
26
26
  | Bulk writes with pipeline semantics | **Query builder write terminals** (`.insertOne`, `.updateMany`, `.findOneAndUpdate`, `.upsertOne`, …) | Filtered writes after `.match(...)`; plans execute through the runtime. |
@@ -94,12 +94,12 @@ const user = await db.orm.users.create({
94
94
  });
95
95
 
96
96
  // Update one — plain object replaces top-level fields.
97
- await db.orm.users.where({ id: user.id }).update({ bio: 'Writer' });
97
+ await db.orm.users.where({ id: user.id }).updateFirst({ bio: 'Writer' });
98
98
 
99
99
  // Update one — field operations ($push, $inc, dot-path $set).
100
100
  await db.orm.users
101
101
  .where({ id: user.id })
102
- .update((u) => [u.tags.push('admin'), u.loginCount.inc(1)]);
102
+ .updateFirst((u) => [u.tags.push('admin'), u.loginCount.inc(1)]);
103
103
 
104
104
  // Update many / delete many — iterate or count.
105
105
  const updated = await db.orm.users
@@ -107,7 +107,8 @@ const updated = await db.orm.users
107
107
  .updateAll({ bio: 'filled' });
108
108
  for await (const row of updated) { /* each modified doc */ }
109
109
 
110
- await db.orm.users.where({ id: user.id }).delete();
110
+ // Delete the first matching document.
111
+ await db.orm.users.where({ id: user.id }).deleteFirst();
111
112
 
112
113
  // Upsert — filter via .where(), split create vs update branches.
113
114
  await db.orm.users.where({ email: 'alice@example.com' }).upsert({
@@ -118,7 +119,7 @@ await db.orm.users.where({ email: 'alice@example.com' }).upsert({
118
119
 
119
120
  **Count-only terminals.** `.createAndCount(...)`, `.updateAndCount(...)`, `.deleteAndCount()` return numbers without re-reading full documents — useful for bulk operations where you only need the modified count.
120
121
 
121
- **Upsert + dot-path.** The upsert `update` callback cannot use dot-path field operations — use top-level field replacement in the upsert branch or a separate `.update((u) => [...])` call.
122
+ **Upsert + dot-path.** The upsert `update` callback cannot use dot-path field operations — use top-level field replacement in the upsert branch or a separate `.updateFirst((u) => [...])` call.
122
123
 
123
124
  ## Workflow — Aggregates
124
125
 
@@ -206,7 +207,7 @@ const [updated] = await runtime.query(
206
207
 
207
208
  Update callbacks return arrays of field operations (`.set`, `.inc`, `.push`, `.pull`, …). Pipeline-style updates use `f.stage.set(...)` inside an aggregation chain, then `.updateMany()` with no callback.
208
209
 
209
- **Plans vs ORM.** The ORM's `.create` / `.update` / `.all` issue queries directly. Don't pass ORM collections to `runtime.query` / `runtime.execute` — those entry points are for `db.query` plans (and migration/runtime internals).
210
+ **Plans vs ORM.** The ORM's `.create` / `.updateFirst` / `.all` issue queries directly. Don't pass ORM collections to `runtime.query` / `runtime.execute` — those entry points are for `db.query` plans (and migration/runtime internals).
210
211
 
211
212
  ## Workflow — Prepared statements (`db.prepare`)
212
213
 
@@ -245,7 +246,7 @@ In an ORM read, a placeholder goes in `limit`, `offset`, a scalar field's value
245
246
 
246
247
  1. **Reaching for the lower-level lane when the ORM would have done.** Default to the ORM; drop to `db.query` only for shapes the ORM can't express.
247
248
  2. **Using `.all()` when you wanted one row.** Use `.where({ ... }).first()` — not `.all()`.
248
- 3. **Calling `.update()` / `.delete()` without `.where()`.** Mutations other than `.create` / `.createAll` require a filter — the compiler enforces this at the type level where possible.
249
+ 3. **Calling `.updateFirst()` / `.deleteFirst()` without `.where()`.** Mutations other than `.create` / `.createAll` require a filter — the compiler enforces this at the type level where possible.
249
250
  4. **Using PascalCase model names on ORM.** Roots are lowercased plurals from the contract (`db.orm.users`, not `db.orm.User`).
250
251
  5. **Expecting Postgres-style lambda `.where((u) => u.email.eq(...))` on ORM.** Prefer object equality `.where({ email: '...' })`; richer operators need `MongoFilterExpr` helpers (a gap in the database package today).
251
252
  6. **Expecting `db.transaction(...)`.** The Mongo package does not expose it today. Multi-document atomicity requires MongoDB transactions on a replica set via the driver — not yet wrapped in the Prisma 8 database package. Route to *What Prisma 8 doesn't do yet* / `references/feedback.md` if the user needs this.
@@ -61,7 +61,7 @@ db.orm.public.User.where((u) => u.email.eq('alice@example.com'));
61
61
  db.orm.public.User.where({ kind: 'admin' });
62
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
+ Operators on the field proxy include `.eq`, `.neq`, `.lt`, `.lte`, `.gt`, `.gte`, `.like`, `.ilike`, `.in([...])` (or a prepared list parameter, see *Prepared `in` with a list parameter*), `.isNull()`, `.isNotNull()`. Extensions add target-specific operators on extension-typed columns (`pgvector`'s `.cosineDistance(...)`, `postgis`'s `.within(...)` / `.intersectsBbox(...)` / `.distanceSphere(...)`).
65
65
 
66
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
67
 
@@ -151,7 +151,7 @@ const posts = await db.orm.public.Post
151
151
  .all();
152
152
  ```
153
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.
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.fragment(fields, body)`) gets `fns` but no indexes.
155
155
 
156
156
  In the SQL builder, a table's `indexes` holds the same references:
157
157
 
@@ -313,17 +313,17 @@ const summary = await db.orm.public.User
313
313
  .select('id', 'email', 'kind')
314
314
  .create({ id, email, displayName, kind, createdAt });
315
315
 
316
- // Update by predicate.
317
- await db.orm.public.User.where({ id }).update({ email: newEmail });
316
+ // Update the first row the filter matches.
317
+ await db.orm.public.User.where({ id }).updateFirst({ email: newEmail });
318
318
 
319
319
  // Update with selected return.
320
320
  await db.orm.public.User
321
321
  .where({ id })
322
322
  .select('id', 'email', 'kind')
323
- .update({ email: newEmail });
323
+ .updateFirst({ email: newEmail });
324
324
 
325
- // Delete by predicate.
326
- await db.orm.public.User.where({ id }).delete();
325
+ // Delete the first row the filter matches.
326
+ await db.orm.public.User.where({ id }).deleteFirst();
327
327
 
328
328
  // Upsert — typed by the create branch's shape.
329
329
  await db.orm.public.User
@@ -336,7 +336,7 @@ await db.orm.public.User
336
336
 
337
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.
338
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:
339
+ **A write needs a filter on every code path.** `updateFirst`, `updateAll`, `updateAndCount`, `deleteFirst`, `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
340
 
341
341
  ```typescript
342
342
  const posts = search ? db.orm.public.Post.where({ title: search }) : db.orm.public.Post;
@@ -353,7 +353,19 @@ if (search) {
353
353
 
354
354
  The same holds for an `if` with an early return, a `switch`, a loop and a reassigned `let`.
355
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.
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. `updateFirst` and `deleteFirst` 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`. `updateFirst` with a relation callback finds its row by the filter alone and throws on any of these and on an order.
357
+
358
+ **Setting values from SQL: the callback form.** `updateAll` and `updateAndCount` also take a callback `(model, { fns, indexes })`, the arguments of a `where` callback, that returns the values to set. It runs once per call and its values go into one `UPDATE`:
359
+
360
+ ```typescript
361
+ await db.orm.public.Post.where({ published: false }).updateAll((p, { fns }) => ({
362
+ slug: p.title,
363
+ title: 'Draft',
364
+ views: fns.raw`${p.views} + 1`.returns('pg/int4@1'),
365
+ }));
366
+ ```
367
+
368
+ A value is a plain value, another field of the same codec, an `fns` result of the field's codec, or `fns.raw` with `.returns(codecId)`; there are no arithmetic functions, so an increment uses `fns.raw`. Only `updateAll` and `updateAndCount` take the callback; `updateFirst`, `upsert` and nested writes take the object form only. A value must match the field's codec and nullability and, for a copy of another field, its input type, or the call is a type error. A field comparison such as `p.views.gt(100)` is not a value. The full rules and limits are in the ORM client's README, section [Updating with expressions](https://github.com/prisma/orm/blob/main/packages/3-extensions/sql-orm-client/README.md#updating-with-expressions).
357
369
 
358
370
  ## Workflow — Custom collection classes
359
371
 
@@ -417,13 +429,13 @@ await deleteMatching(Post.byAuthor(userId)).toArray();
417
429
 
418
430
  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
431
 
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:
432
+ **The same filter on several models.** Define a scope with `db.fragment(fields, body)`, on the client and on `tx`; 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
433
 
422
434
  ```typescript
423
435
  import { field, type } from '@prisma/orm-postgres/contract-builder';
424
436
 
425
437
  const createdSince = (since: Temporal.Instant) =>
426
- db.orm.fragment({ createdAt: field.column(type.TimestamptzTemporal()) }, (rows) =>
438
+ db.fragment({ createdAt: field.column(type.TimestamptzTemporal()) }, (rows) =>
427
439
  rows.where((r) => r.createdAt.gte(since)),
428
440
  );
429
441
 
@@ -431,7 +443,7 @@ await db.orm.public.User.with(createdSince(since)).all();
431
443
  await db.orm.public.Post.with(createdSince(since)).deleteAll();
432
444
  ```
433
445
 
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.
446
+ 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 `updateFirst` and `deleteFirst` 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. `updateFirst` and `deleteFirst` 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`; `updateFirst` 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
447
 
436
448
  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
449
 
@@ -460,7 +472,7 @@ await db.orm.public.Post.where({ userId }).with(postSummary).limit(20).all();
460
472
  await db.orm.public.User.include('posts', (posts) => posts.with(postSummary)).all();
461
473
  ```
462
474
 
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.
475
+ 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. `updateFirst` and `deleteFirst` 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.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
476
 
465
477
  **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
478
 
@@ -558,6 +570,37 @@ const rows = await db.query(plan);
558
570
 
559
571
  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.).
560
572
 
573
+ ### Prepared `in` with a list parameter
574
+
575
+ A prepared statement (see *Prepared statements* in [`queries.md`](./queries.md)) can take a whole list as one parameter. Declare it with `many: { elementNullable }`; the value is an array, and one statement serves every list length. Use it for "rows whose id is in this list" instead of a fixed list of placeholders, which fixes the length in the SQL. When a list's length or values matter to the query plan, a literal `IN` list may plan better.
576
+
577
+ The example uses the demo schema's ids, `Uuid` in its Prisma schema (`pg/uuid@1`); use your id column's codec id, which must match the column's exactly.
578
+
579
+ ```typescript
580
+ const ids = { codecId: 'pg/uuid@1', many: { elementNullable: false } } as const;
581
+
582
+ // SQL builder: in / notIn take a list expression of the left operand's codec.
583
+ const postsByUser = await db.prepare({ ids }, (p) =>
584
+ db.sql.public.post.select('id', 'title').where((f, fns) => fns.in(f.userId, p.ids)).build(),
585
+ );
586
+
587
+ // ORM: in / notIn on a scalar field take the same list parameter.
588
+ const usersExcept = await db.prepare({ ids }, (p) =>
589
+ db.orm.public.User.where((u) => u.id.notIn(p.ids)).select('id', 'email').prepared.all(),
590
+ );
591
+
592
+ const rows = await postsByUser.query(db.runtime(), { ids: userIds });
593
+ ```
594
+
595
+ - It renders `= ANY($1::uuid[])` for `in` and `<> ALL($1::uuid[])` for `notIn`, with the same results as `IN` / `NOT IN`; an empty array matches no row for `in` and every row for `notIn`.
596
+ - The SQL builder also takes a list column on the right: `fns.in(p.tag, f.tags)`, with `p.tag` a scalar parameter declared `{ tag: 'pg/text@1' }` and `tags` a hypothetical `String[]` column (the demo schema has none). The left operand must be an expression (a column or a parameter), not a plain value.
597
+ - The SQL builder's `fns.eq` / `fns.ne` compare a list column with a list parameter, another list of the same element type, or an array: `fns.eq(f.tags, p.tags)`.
598
+ - The ORM takes a list parameter only on a scalar field, and only when neither the list nor its elements may be null (`nullable` absent or `false`, `elementNullable: false`); anything else is a compile error. At run time a nullable or element-nullable list parameter, one on a list field and one in a comparison other than `in` / `notIn` fail with `ORM.FILTER_UNSUPPORTED`; the codec match is checked by the types only.
599
+ - A list parameter needs `db.scalarList` in the contract's required capabilities (`postgres15` to `postgres18` all include it); without it `prepare` throws `ORM.CAPABILITY_MISSING`. SQLite, MySQL and MariaDB have no list parameters.
600
+ - Passing a value that is neither an array nor `null` fails when the statement runs, with `RUNTIME.ENCODE_FAILED`. `null` is not checked at run time, as for a single-value parameter: it binds SQL `NULL` and matches no row.
601
+ - A list of enum values uses the enum column's codec. The demo's `user_type` enum is stored as text (`@@type("pg/text@1")`), so a list of `User.kind` values is `{ codecId: 'pg/text@1', many: { elementNullable: false } }`. A native PostgreSQL enum column (`pg/enum@1`) also names its database type in `typeParams`, as the column does: for a native enum type `user_type`, `{ codecId: 'pg/enum@1', typeParams: { typeName: 'user_type' }, many: { elementNullable: false } }` renders `= ANY($1::"user_type"[])`.
602
+ - A list of `char(n)` values is cast to `bpchar[]`, PostgreSQL's `character` with no length, so no element is cut short.
603
+
561
604
  ### `INSERT` / `UPDATE` / `DELETE` with `RETURNING`
562
605
 
563
606
  ```typescript
@@ -586,7 +629,7 @@ const { affectedRows } = await db.execute(deletePlan);
586
629
 
587
630
  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
631
 
589
- `.returning(...)` requires the contract to require `sql.returning`. `postgres15` to `postgres18` list it.
632
+ `.returning(...)` requires the contract to require `db.returning`. `postgres15` to `postgres18` list it.
590
633
 
591
634
  ### Computed projections and joins
592
635
 
@@ -696,7 +739,7 @@ Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the sam
696
739
  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`.
697
740
  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.
698
741
  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`).
742
+ 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 `db.lateral`, `db.jsonAgg` and `db.returning`. To require one more, add its key to that list (see `references/contract.md`).
700
743
  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).
701
744
  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
745
  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.
@@ -719,7 +762,7 @@ Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the sam
719
762
  - [ ] Expressed ranges as chained `.where(...)` clauses or a single `and(...)` clause — did NOT reach for a non-existent `.between(...)` operator.
720
763
  - [ ] 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.
721
764
  - [ ] For ORM combinators, imported `and` / `or` / `not` from `@prisma/orm-postgres/orm-client`.
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.
765
+ - [ ] Wrote a query piece shared between places as a function: a query fragment from `db.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
766
  - [ ] 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.
724
767
  - [ ] Wrapped multi-statement work in `db.transaction(async (tx) => { ... })` where atomicity matters.
725
768
  - [ ] For top-N grouped aggregates at meaningful scale, dropped to `db.sql.<ns>.<table>` rather than JS-side sort + slice over `groupBy(...).aggregate(...)`.
@@ -151,7 +151,7 @@ There is no `.stream()` method on a client or on a connection.
151
151
 
152
152
  This section covers the SQL clients. MongoDB's `db.prepare` has the same shape, takes query-builder plans and ORM `.prepared` reads, and runs against `await db.runtime()`; see *Workflow — Prepared statements* in [`queries-mongo.md`](queries-mongo.md).
153
153
 
154
- `db.prepare(declaration, (params) => plan)` builds a statement once and binds it per call. The declaration names each parameter's codec (`{ email: 'pg/text@1' }`); the callback receives typed `params`, builds the plan with `db.sql` (or an ORM `.prepared` description), and returns it. A row-returning plan gives a `PreparedStatement` you run with `ps.query(target, params)`; a plan whose result is an affected count gives a `PreparedExecution` you run with `ps.execute(target, params)`. A prepared statement runs on what it is given: the runtime, a connection, a transaction's `tx`, or a Supabase role-bound client, which runs it under its role. `ps.query(tx, params)` runs inside the transaction. Preparing sends nothing to the database. Inside a transaction, `tx.prepare(...)` prepares without the outer client. Declaring a parameter the plan never references throws `RUNTIME.PREPARE_UNUSED_PARAM`. `runtime.prepare(declaration, (params) => plan)` is the same thing on a `Runtime`.
154
+ `db.prepare(declaration, (params) => plan)` builds a statement once and binds it per call. The declaration names each parameter's codec (`{ email: 'pg/text@1' }`); the callback receives typed `params`, builds the plan with `db.sql` (or an ORM `.prepared` description), and returns it. A row-returning plan gives a `PreparedStatement` you run with `ps.query(target, params)`; a plan whose result is an affected count gives a `PreparedExecution` you run with `ps.execute(target, params)`. A prepared statement runs on what it is given: the runtime, a connection, a transaction's `tx`, or a Supabase role-bound client, which runs it under its role. `ps.query(tx, params)` runs inside the transaction. Preparing sends nothing to the database. Inside a transaction, `tx.prepare(...)` prepares without the outer client. Declaring a parameter the plan never references throws `RUNTIME.PREPARE_UNUSED_PARAM`. On Postgres a parameter declared with `many: { elementNullable }` holds a whole list for `in` / `notIn`; see *Prepared `in` with a list parameter* in [`queries-postgres.md`](./queries-postgres.md). `runtime.prepare(declaration, (params) => plan)` is the same thing on a `Runtime`.
155
155
 
156
156
  ```typescript
157
157
  // examples/prisma-8-demo/src/queries/get-user-by-email-prepared.ts
@@ -229,7 +229,7 @@ Target-specific pitfalls live in the per-target guides.
229
229
  - **Many-to-many relations work through the junction.** `.include('tags', (tag) => tag.select(...))` traverses an N:M relation's `through` table, and nested `create` / `connect` / `disconnect` on an N:M relation write the junction rows for you (`examples/prisma-8-demo/src/orm-client/get-post-tags.ts`, `create-post-with-tags.ts`). The one refusal: a junction with required payload columns the relation API cannot populate throws `ORM.OPERATION_UNSUPPORTED` — write that junction directly or use the SQL builder.
230
230
  - **Ordering grouped aggregates by an aggregate alias (Postgres).** `db.orm.<ns>.<Model>.groupBy(...)` supports `.orderBy(...)` on group keys plus `.limit(...)` / `.offset(...)`, but the grouped collection cannot order by an aggregate alias such as `SUM(amount)`. A "top-N groups by SUM" query therefore falls back to JS-side sort + slice over the full grouped result, which is fine at small cardinalities and bad at scale. Workarounds: (a) drop to `db.sql.<ns>.<table>` and write the `GROUP BY` + `ORDER BY` + `LIMIT` against the aggregated table directly; (b) live with the JS-side sort/slice if the grouped cardinality is bounded. File a feature request via `references/feedback.md` if this is hitting you in production.
231
231
  - **Set operations, window functions and `WITH` in the SQL builder.** `db.sql` has no `union` / `intersect` / `except`, no `OVER (...)` and no common table expressions. Write the whole query as raw SQL (next entry). If you want them in the builder, file a feature request via `references/feedback.md`.
232
- - **A raw-SQL lane.** This one exists. Write whole-query raw SQL through the client's raw lane: ``db.raw.sql`SELECT ...`.returnsRow({ ... }).build()`` for rows, or `.affectedCount()` for a mutation's row count. Each declared column names the codec that decodes it, so the row stays typed. For an expression fragment inside a builder query, use `fns.raw` in a `.select(...)` callback instead.
232
+ - **A raw-SQL lane.** This one exists. Write whole-query raw SQL through the client's raw lane: ``db.raw.sql`SELECT ...`.returnsRow({ ... }).build()`` for rows, or `.affectedCount()` for a mutation's row count. Each declared column names the codec that decodes it, so the row stays typed. For an expression fragment inside a builder query, use `fns.raw` in a `.select(...)` callback instead, ending it with `.returns(codecId)`; an expression that holds an array, such as ``fns.raw`array_append(${f.tags}, 'x')` ``, ends with `.returns({ codecId: 'pg/text@1', many: { elementNullable: false } })`, so a list column's `update` value or `fns.eq` accepts it.
233
233
  - **TypedSQL (`.sql` files compiled into typed callables).** Not implemented. For a repeated query, use `db.prepare(...)` (see *Prepared statements* above) or a function that returns the built plan and `db.query(plan)` at the call site. If you want a `.sql`-file compile path, file a feature request via `references/feedback.md`.
234
234
  - **`EXPLAIN` / query-plan inspection.** Prisma 8 does not expose an `.explain()` method. Workaround: connect a `pg.Pool` you control via the runtime's `pg:` binding (see `references/runtime.md`) and issue `EXPLAIN ANALYZE` through it. If you want a first-class plan-inspection surface, file a feature request via `references/feedback.md`.
235
235
  - **Multi-statement batching (Prisma-7-style `db.$transaction([call1, call2])`).** Prisma 8 runs each call sequentially. Workaround: wrap atomically-related work in `db.transaction(async (tx) => { ... })` on Postgres. If you want batch-as-array semantics, file a feature request via `references/feedback.md`.
@@ -7,7 +7,7 @@ This skill takes the user from zero (or near-zero) to a first working query agai
7
7
 
8
8
  - **First-touch orientation** — the user has arrived at a Prisma 8 project for the first time (a scaffold tool like `npx createprisma` dropped them in, they cloned a teammate's repo, or they ran `prisma orm init` themselves and now want to make their first move) and they're asking *"what can I do with Prisma 8?"*, *"where do I start?"*, or *"what's next?"*. The goal is to anchor them on the contract, get them connected to a database, round-trip one row, and let further commands surface organically.
9
9
  - **Greenfield** — new project, fresh database. User runs `prisma orm init` themselves. `init` seeds a starter contract with a sample model, so the path joins the first-touch orientation arc as soon as the database is initialised.
10
- - **Brownfield-DB** — existing database, no contract yet. Infer the contract from the database with `contract infer`, sign the marker with `db sign`, then write queries against one of the existing tables.
10
+ - **Brownfield-DB** — existing database, no contract yet. Infer the contract from the database with `contract infer`, sign the database with `db sign`, then write queries against one of the existing tables.
11
11
 
12
12
  This skill does **not** cover migrating from another ORM (Drizzle, Prisma 6/7, Sequelize, TypeORM, Kysely, Knex, raw drivers). Those are separately-installable skills.
13
13
 
@@ -37,7 +37,7 @@ This skill does **not** cover migrating from another ORM (Drizzle, Prisma 6/7, S
37
37
  - **Why the application lists them.** The application must have exactly one copy of each. Prisma does not accept a value that another copy of its own code created, and a package manager takes a peer dependency only from the application's own list. A monorepo whose applications are on different Prisma releases can still get two copies under npm workspaces and under Bun's hoisted linker; keep such applications on one release, or use pnpm, Yarn or Bun's isolated linker.
38
38
  - **Yarn Plug'n'Play.** `prisma orm init` does not support it. With Yarn, set `nodeLinker: node-modules` in `.yarnrc.yml` first.
39
39
  - **`db.ts`**: the runtime entry point. Lives next to the contract source at `src/prisma/db.ts`. Imports the contract artefacts and exports a `db` value the rest of the app uses.
40
- - **Marker**: a row in the `prisma_contract.marker` table (Postgres) or a document in the `_prisma_migrations` collection (Mongo) that records the contract hash per contract space. Lets Prisma 8 detect drift between contract and live DB. Created by `db init` (greenfield / first-touch orientation) or `db sign` (brownfield).
40
+ - **Contract signature**: a row in the `prisma.signatures` table (Postgres) or a document in the `_prisma_migrations` collection (Mongo) that records the contract hash per contract space. Lets Prisma 8 detect drift between contract and live DB. Created by `db init` (greenfield / first-touch orientation) or `db sign` (brownfield).
41
41
 
42
42
  ### Canonical on-disk layout
43
43
 
@@ -109,7 +109,7 @@ If that prints `[{ id: 1, email: 'alice@example.com' }]`, the project is wired e
109
109
  - The contract source exists at `src/prisma/contract.{prisma,ts}` (a starter model from `init`, or the inferred contract from `contract infer`, or whatever the bootstrap tool generated).
110
110
  - `src/prisma/db.ts` exists and instantiates the runtime with the emitted contract.
111
111
  - `DATABASE_URL` is set in `.env` (or wherever the runtime's config tells it to look).
112
- - The database has been initialised (`db init`) or marker-signed (`db sign`), so the marker row exists and the schema matches the contract.
112
+ - The database has been initialised (`db init`) or signed (`db sign`), so its contract signature exists and the schema matches the contract.
113
113
 
114
114
  The three workflows below each describe how their path gets the user to that state. After that, the arc above is the same.
115
115
 
@@ -135,7 +135,7 @@ Before saying anything specific to the user, read:
135
135
  - The contract source the config declares (canonically `src/prisma/contract.prisma` or `src/prisma/contract.ts`; a project scaffolded by an older init may have it at `prisma/contract.{prisma,ts}` instead — check the `contract` field of the config) — what starter models, if any, exist.
136
136
  - `src/prisma/db.ts` (next to the contract) — the runtime entry point.
137
137
  - `.env` / `.env.example` — is `DATABASE_URL` set, or only the example?
138
- - Optionally `pnpm prisma db verify` — does the live DB match the contract? (Exit `4` with findings means drift or no marker; `2` means it could not run.)
138
+ - Optionally `pnpm prisma db verify` — does the live DB match the contract? (Exit `4` with findings means drift or no contract signature; `2` means it could not run.)
139
139
 
140
140
  Then **say the contract path back to the user, with its role attached**. Something like: *"Your contract is at `src/prisma/contract.prisma`, and it currently declares a `User` model. The contract describes your app — every query type, migration, and runtime type the framework gives you flows from this file. Let's get your app connected to a database next."* The exact wording is up to the agent; what matters is that the user leaves the first response knowing *where the contract is* and *that it is the source of truth*.
141
141
 
@@ -144,8 +144,8 @@ Then **say the contract path back to the user, with its role attached**. Somethi
144
144
  The motivation is *"so your app can actually run against your database"*, not *"so the prerequisite checklist passes"*. The mechanics depend on what's already in place from Step 1:
145
145
 
146
146
  - **Everything already wired.** Go straight to writing and reading a row (see *Your first arc — connect, write, read* above). Adapt the snippet to whatever model the contract declares.
147
- - **`DATABASE_URL` not set.** Have the user set it in `.env` (not in `prisma.config.ts` — see Pitfall 5). Then `pnpm prisma db init` to apply the current contract to that database and write the marker row. Now the app can connect.
148
- - **Database is connectable but not yet aware of the contract** (marker row missing; `db verify` reports drift). Run `pnpm prisma db init`. (`db update` is the alternative for quick dev cycles — it's looser, doesn't write a migration history, and is what users reach for when they want to iterate on the schema fast. Mention it if the user asks how to make schema changes flow to the DB; don't pre-explain it.)
147
+ - **`DATABASE_URL` not set.** Have the user set it in `.env` (not in `prisma.config.ts` — see Pitfall 5). Then `pnpm prisma db init` to apply the current contract to that database and write the contract signature row. Now the app can connect.
148
+ - **Database is connectable but not yet aware of the contract** (signature row missing; `db verify` reports drift). Run `pnpm prisma db init`. (`db update` is the alternative for quick dev cycles — it's looser, doesn't write a migration history, and is what users reach for when they want to iterate on the schema fast. Mention it if the user asks how to make schema changes flow to the DB; don't pre-explain it.)
149
149
  - **Contract is empty** (bootstrap left the source blank). Add **one** model with **two** fields (e.g. `User { id, email }`), `pnpm prisma contract emit`, then `pnpm prisma db init`. Minimal — get the round-trip working, *then* extend.
150
150
 
151
151
  The user encounters `db init` (and optionally `db update`, `contract emit`) here because they're the commands their current move *requires*. They learn what those commands are by using them.
@@ -214,7 +214,7 @@ The flags `init` accepts (run `prisma orm init --help` for the source of truth):
214
214
  After init succeeds, the path converges on *Your first arc — connect, write, read* above. `init` has already seeded a starter contract with `User` and `Post` models (with a relation between them) and run `contract emit` once; the only remaining prerequisites are setting `DATABASE_URL` and initialising the database. Two commands:
215
215
 
216
216
  1. Set `DATABASE_URL` in `.env` (copy from `.env.example`).
217
- 2. Initialise the database: `pnpm prisma db init`. Creates tables, indexes, constraints, and writes the marker row — using the starter contract `init` generated.
217
+ 2. Initialise the database: `pnpm prisma db init`. Creates tables, indexes, constraints, and writes the contract signature row — using the starter contract `init` generated.
218
218
 
219
219
  Then run the snippet from *Your first arc* above against the `User` model. When the user is ready to extend the contract — add more models, change fields, add relations — chain to `references/contract.md`. For more queries, chain to `references/queries.md`.
220
220
 
@@ -222,7 +222,7 @@ Then run the snippet from *Your first arc* above against the `User` model. When
222
222
 
223
223
  ## Workflow — Brownfield-DB (existing database, no contract)
224
224
 
225
- The concept: against an existing database with no Prisma 8 contract, `contract infer` walks the live schema (tables, columns, indexes — including expression and partial ones — constraints, and RLS enablement + policies) and writes a PSL contract that describes it. Where authoring would generate a CHECK constraint the database does not carry (the element-non-null check on a list column), infer writes the list with nullable elements (`String?[]`), which derives no such check, so the contract declares exactly what the database enforces. The reverse gap is closed too: a hand-written CHECK constraint the database enforces that authoring would never have generated comes back as `@@check(expression: <reprint>, map: "<name>")`, so it is a declared object from the first pull instead of an invisible extra a later destructive plan could drop. That inferred check warns (`PN_EXACT_NAME_BODY_COMPARISON`) the next time you run `contract emit` — expected, not a defect: the warning fires on any `map:` body regardless of who wrote it, and the comparison stays sound because both sides are Postgres's own reprint. Columns come back as the convenience types with their defaults, and only the arguments that differ: `int2` as `Int(storage: int2)`, `numeric(10,2)` as `Decimal(precision: 10, scale: 2)`, `varchar(12)` as `String(storage: varchar, length: 12)`, `json` as `Json`, `jsonb` as `Json(storage: jsonb)`, `timestamptz(3)` as `DateTime` (a JavaScript `Date`), a `timestamptz` with no declared precision as `DateTime(precision: 6)`, `timestamp(3)` as `DateTime(storage: timestamp)`, `date` as `Date`, `time` as `Time` and `interval` as `Duration` (ISO strings). A `Date` holds milliseconds, so a timestamp column whose values use microseconds reads with them dropped: change such a field to `DateTime(as: temporal)` or `DateTime(as: string)` to keep them. The result is a *starting point*, not the final contract — review and clean it up, then `db sign` to record the current contract hash as the marker (instead of letting `db init` try to recreate the schema from scratch). By default `db sign` also sets the `db` ref and stores the contract snapshot, so the next `migration plan` chains from the adopted schema — even when the database is named with `--db`. `--advance-ref <name>` writes another ref instead and `--no-advance-ref` writes none; in either case the next plan needs `--from` or a `db` ref you set yourself.
225
+ The concept: against an existing database with no Prisma 8 contract, `contract infer` walks the live schema (tables, columns, indexes — including expression and partial ones — constraints, and RLS enablement + policies) and writes a PSL contract that describes it. Where authoring would generate a CHECK constraint the database does not carry (the element-non-null check on a list column), infer writes the list with nullable elements (`String?[]`), which derives no such check, so the contract declares exactly what the database enforces. The reverse gap is closed too: a hand-written CHECK constraint the database enforces that authoring would never have generated comes back as `@@check(expression: <reprint>, map: "<name>")`, so it is a declared object from the first pull instead of an invisible extra a later destructive plan could drop. That inferred check warns (`PN_EXACT_NAME_BODY_COMPARISON`) the next time you run `contract emit` — expected, not a defect: the warning fires on any `map:` body regardless of who wrote it, and the comparison stays sound because both sides are Postgres's own reprint. Columns come back as the convenience types with their defaults, and only the arguments that differ: `int2` as `Int(storage: int2)`, `numeric(10,2)` as `Decimal(precision: 10, scale: 2)`, `varchar(12)` as `String(storage: varchar, length: 12)`, `json` as `Json`, `jsonb` as `Json(storage: jsonb)`, `timestamptz(3)` as `DateTime` (a JavaScript `Date`), a `timestamptz` with no declared precision as `DateTime(precision: 6)`, `timestamp(3)` as `DateTime(storage: timestamp)`, `date` as `Date`, `time` as `Time` and `interval` as `Duration` (ISO strings). A `Date` holds milliseconds, so a timestamp column whose values use microseconds reads with them dropped: change such a field to `DateTime(as: temporal)` or `DateTime(as: string)` to keep them. The result is a *starting point*, not the final contract — review and clean it up, then `db sign` to record the current contract hash as the contract signature (instead of letting `db init` try to recreate the schema from scratch). By default `db sign` also sets the `db` ref and stores the contract snapshot, so the next `migration plan` chains from the adopted schema — even when the database is named with `--db`. `--advance-ref <name>` writes another ref instead and `--no-advance-ref` writes none; in either case the next plan needs `--from` or a `db` ref you set yourself.
226
226
 
227
227
  ```bash
228
228
  mkdir my-app && cd my-app
@@ -250,7 +250,7 @@ Then re-emit and sign:
250
250
 
251
251
  ```bash
252
252
  pnpm prisma contract emit
253
- pnpm prisma db sign # writes the marker and sets the db ref
253
+ pnpm prisma db sign # writes the contract signature and sets the db ref
254
254
  pnpm prisma db verify # exit 0 immediately after a pull; exit 4 with findings if the DB drifts later
255
255
  ```
256
256
 
@@ -304,7 +304,7 @@ This skill is intentionally body-only; `prisma orm init --help`, `contract infer
304
304
 
305
305
  - [ ] Confirmed which path applies (first-touch orientation / greenfield / brownfield) before proposing commands.
306
306
  - [ ] **First-touch orientation:** named the contract path back to the user and framed its role (*source of truth from which query types, migrations, and runtime types flow*) before proposing any commands.
307
- - [ ] **All paths:** brought the project to the *Your first arc* prerequisites (config, contract source, `db.ts`, `DATABASE_URL`, marker row) *before* writing application code.
307
+ - [ ] **All paths:** brought the project to the *Your first arc* prerequisites (config, contract source, `db.ts`, `DATABASE_URL`, contract signature row) *before* writing application code.
308
308
  - [ ] **All paths:** ran the first arc — one `create` + one `select` against the starter (or inferred) model — and got the round-trip working green.
309
309
  - [ ] **All paths:** did *not* edit the contract source as part of the first arc. Schema extension is the *next* move, not the first.
310
310
  - [ ] **All paths:** did *not* lead with a feature tour, capability inventory, or recital of CLI commands. Commands surfaced as the user's current move required them.
@@ -314,7 +314,7 @@ This skill is intentionally body-only; `prisma orm init --help`, `contract infer
314
314
  - [ ] **All paths (application projects):** the project ended up in the canonical `src/prisma/contract.{prisma,ts}` + `src/prisma/db.ts` + `migrations/app/` layout (what `init` scaffolds by default). An extension or aggregate-root package keeps its own `src/contract.{prisma,ts}` + `migrations/<timestamp>_<slug>/` layout — do not relocate it.
315
315
  - [ ] **Brownfield path:** ran `contract infer --db "$DATABASE_URL" --output src/prisma/contract.prisma`, reviewed the result, then `contract emit` + `db sign` (which by default also sets the `db` ref, so the next `migration plan` chains from the adopted schema; not with `--no-advance-ref` or `--advance-ref <name>`).
316
316
  - [ ] Set `DATABASE_URL` in `.env` and confirmed the value is reachable.
317
- - [ ] Initialised the DB (`db init` greenfield / first-touch orientation) or signed the marker (`db sign` brownfield — by default sets the `db` ref too, with or without `--db`).
317
+ - [ ] Initialised the DB (`db init` greenfield / first-touch orientation) or signed the database (`db sign` brownfield — by default sets the `db` ref too, with or without `--db`).
318
318
  - [ ] Did NOT hand-edit `contract.json` or `contract.d.ts`.
319
319
  - [ ] Did NOT set `DATABASE_URL` in `prisma.config.ts`.
320
320
  - [ ] Confirmed the user understands what the *next* skill is for their workflow (typically `references/queries.md` for more queries, then `references/contract.md` when they're ready to extend the schema).
@@ -169,7 +169,7 @@ The rule to remember: inside a request, `db` does everything the `db` from `post
169
169
  - **Never call `connect` at module scope.** A connection opened there is shared by every request in the isolate, and fails in four ways: its database connection goes stale after the isolate idles, concurrent requests queue behind each other on one `pg.Client`, nothing closes it when a request ends, and Cloudflare Workers reject a socket used across requests.
170
170
  - **`db.orm` is the way to use the ORM.** For custom collection classes, pass `collections` to `postgresServerless({ contract, collections })` at module scope; every connection's `db.orm` and `tx.orm` then returns the classes. See *Workflow — Custom collection classes* in [`queries-postgres.md`](queries-postgres.md).
171
171
  - **Anything that takes a runtime gets `db.runtime()`.** That includes `withTransaction(runtime, fn)` and a prepared statement's `query(runtime, params)`. Do not pass `db` itself.
172
- - **Inside `db.transaction(async (tx) => ...)`, run every query through `tx`.** A connection has one database connection, so inside `db.transaction(async (tx) => ...)` a query through `db` is not independent of the transaction; run every query through `tx`. A query that uses the connection's database connection directly, such as a `db.orm` read, a `db.orm` create of one row, an `updateAll(...)` or `deleteAll()`, or `db.query(...)`, runs inside the open transaction without saying so. An operation that asks for a database connection of its own, such as a `db.orm` `update(...)` or `delete()` of one row, `db.runtime().connection()`, a `db.orm` create that also writes related rows, or a nested `db.transaction(...)`, waits for the database connection the transaction holds, and the request hangs.
172
+ - **Inside `db.transaction(async (tx) => ...)`, run every query through `tx`.** A connection has one database connection, so inside `db.transaction(async (tx) => ...)` a query through `db` is not independent of the transaction; run every query through `tx`. A query that uses the connection's database connection directly, such as a `db.orm` read, a `db.orm` create of one row, an `updateAll(...)` or `deleteAll()`, or `db.query(...)`, runs inside the open transaction without saying so. An operation that asks for a database connection of its own, such as a `db.orm` `updateFirst(...)` or `deleteFirst()` of one row, `db.runtime().connection()`, a `db.orm` create that also writes related rows, or a nested `db.transaction(...)`, waits for the database connection the transaction holds, and the request hangs.
173
173
  - **After `db.close()`** (or the end of the `await using` scope), `db.runtime()` throws `DRIVER.NOT_CONNECTED` ("Postgres connection is closed"), and ORM queries, `db.transaction(...)` and prepared statements that start after the runtime was idle for a turn reject with `DRIVER.NOT_CONNECTED` ("Runtime is closed"). Call `postgres.connect({ url })` again for a new connection.
174
174
 
175
175
  How connections read rows, and the `cursor` option on the serverless client (with the Hyperdrive caveat), is in `references/queries.md` § *Streaming*.
@@ -282,7 +282,7 @@ const user = await db.orm.public.User.first({ id: 1 }, (meta) =>
282
282
  // Un-annotated queries always hit the database.
283
283
 
284
284
  // The write invalidates 'user-1' once it has committed; inside db.transaction(fn), when that commits.
285
- await db.orm.public.User.where({ id: 1 }).update({ name: 'Alicia' }, (meta) =>
285
+ await db.orm.public.User.where({ id: 1 }).updateFirst({ name: 'Alicia' }, (meta) =>
286
286
  meta.annotate(invalidateAnnotation({ keys: ['user-1'] })),
287
287
  );
288
288
 
@@ -309,7 +309,7 @@ Order matters: `beforeEncode` runs in registration order for every middleware be
309
309
 
310
310
  ## Workflow — Configure the connection
311
311
 
312
- The concept: the runtime takes one of three binding shapes — `url`, `pg` (a pre-constructed `pg.Pool` or `pg.Client`), or `binding` (an explicit kind tag). They're mutually exclusive. The `pg` form is for projects that already manage their own pool (e.g. a Lambda layer); `url` is the default. Pool tuning is `poolOptions.connectionTimeoutMillis` / `poolOptions.idleTimeoutMillis` / `poolOptions.max` (pool size, 10 by default) — *not* `driverOptions`. Behind a server-side connection pooler, `poolOptions: { max: 1 }` keeps one connection; queries then take turns on it, so a query waits while a transaction is open. Inside `db.transaction(async (tx) => …)` send every query through `tx`: with one connection, a query through `db` waits for the connection its own transaction holds and fails after `connectionTimeoutMillis`. Reads are buffered by default; setting `cursor` (`{ batchSize: 100 }`; `{}` or `{ batchSize: undefined }` for batches of 100; a `batchSize` that is not a positive integer fails the factory call) makes them stream through a server-side cursor, and there is no flag that turns cursors off (see `references/queries.md` § *Streaming*). `postgresServerless()` takes the same `cursor` option. Pass `log` (an object with `info`, `warn`, `error` and an optional `debug`; `console` works, and the type is `Log` from `@prisma/orm-postgres/family-runtime`) to receive what the runtime logs: the marker-verification warnings `CONTRACT.MARKER_MISSING` and `CONTRACT.MARKER_MISMATCH` from the client's first use of the database (its first query, connection or transaction), the warnings `lints()` emits for rules whose severity is `warn`, and the errors a middleware's `activityEnded` or `activityFinalized` hook throws, which the runtime logs and swallows. If `log` has a `debug` method, it also receives debug events, for example when a middleware intercepts a statement. `budgets()` violations reach `log` only in `mode: 'permissive'` (see *Lints and budgets middleware*). Without `log`, the runtime logs to the console: errors to `console.error` and warnings to `console.warn`, which in Node write to standard error, info events to `console.info`, and debug events nowhere. To silence it, pass a logger that does nothing: `log: { info() {}, warn() {}, error() {} }`. `postgresServerless()`, `sqlite()` and `supabase()` take the same option.
312
+ The concept: the runtime takes one of three binding shapes — `url`, `pg` (a pre-constructed `pg.Pool` or `pg.Client`), or `binding` (an explicit kind tag). They're mutually exclusive. The `pg` form is for projects that already manage their own pool (e.g. a Lambda layer); `url` is the default. Pool tuning is `poolOptions.connectionTimeoutMillis` / `poolOptions.idleTimeoutMillis` / `poolOptions.max` (pool size, 10 by default) — *not* `driverOptions`. Behind a server-side connection pooler, `poolOptions: { max: 1 }` keeps one connection; queries then take turns on it, so a query waits while a transaction is open. Inside `db.transaction(async (tx) => …)` send every query through `tx`: with one connection, a query through `db` waits for the connection its own transaction holds and fails after `connectionTimeoutMillis`. Reads are buffered by default; setting `cursor` (`{ batchSize: 100 }`; `{}` or `{ batchSize: undefined }` for batches of 100; a `batchSize` that is not a positive integer fails the factory call) makes them stream through a server-side cursor, and there is no flag that turns cursors off (see `references/queries.md` § *Streaming*). `postgresServerless()` takes the same `cursor` option. Pass `log` (an object with `info`, `warn`, `error` and an optional `debug`; `console` works, and the type is `Log` from `@prisma/orm-postgres/family-runtime`) to receive what the runtime logs: the contract-signature-verification warnings `CONTRACT.SIGNATURE_MISSING` and `CONTRACT.SIGNATURE_MISMATCH` from the client's first use of the database (its first query, connection or transaction), the warnings `lints()` emits for rules whose severity is `warn`, and the errors a middleware's `activityEnded` or `activityFinalized` hook throws, which the runtime logs and swallows. If `log` has a `debug` method, it also receives debug events, for example when a middleware intercepts a statement. `budgets()` violations reach `log` only in `mode: 'permissive'` (see *Lints and budgets middleware*). Without `log`, the runtime logs to the console: errors to `console.error` and warnings to `console.warn`, which in Node write to standard error, info events to `console.info`, and debug events nowhere. To silence it, pass a logger that does nothing: `log: { info() {}, warn() {}, error() {} }`. `postgresServerless()`, `sqlite()` and `supabase()` take the same option.
313
313
 
314
314
  ```typescript
315
315
  // Default — URL string, factory constructs the pool.
@@ -322,7 +322,7 @@ postgres({
322
322
  // max: 10, // optional: the most connections the pool opens
323
323
  },
324
324
  // cursor: { batchSize: 100 }, // optional — stream reads in batches instead of buffering
325
- // log: logger, // optional — where marker and lints() warnings go; the console by default
325
+ // log: logger, // optional — where contract signature and lints() warnings go; the console by default
326
326
  });
327
327
 
328
328
  // BYO pool — pass a pg.Pool you already created.
@@ -415,7 +415,7 @@ export const contract = contractFromJson<Contract>(contractJson);
415
415
  export const db = sqlite({ contract, path: 'app.db' });
416
416
  ```
417
417
 
418
- `path` is optional at construct time (you can call `db.connect({ path })` later); omit it and the database package still returns a client. The SQLite package exposes the same `db.sql`, `db.orm`, `db.raw`, `db.prepare(...)`, `db.transaction(...)`, `db.close()`, and `[Symbol.asyncDispose]` surfaces as Postgres, with one addressing difference: SQLite has no schemas, so `db.sql` and `db.orm` are the unbound namespace itself (`db.orm.User`, `db.sql.user`) instead of Postgres's `db.orm.public.User` / `db.sql.public.user`. `db.orm` and `tx.orm` also offer `fragment` beside the models, unless a model is named `fragment`: `const titled = db.orm.fragment({ title: { codecId: 'sqlite/text@1', nullable: false } }, (rows) => rows.where((r) => r.title.eq('Hello')));` then `await db.orm.Post.with(titled).all();`. The Mongo package shares `db.orm`, `db.close()`, and `[Symbol.asyncDispose]` but has no `db.sql` and no `db.transaction(...)`.
418
+ `path` is optional at construct time (you can call `db.connect({ path })` later); omit it and the database package still returns a client. The SQLite package exposes the same `db.sql`, `db.orm`, `db.raw`, `db.prepare(...)`, `db.transaction(...)`, `db.close()`, and `[Symbol.asyncDispose]` surfaces as Postgres, with one addressing difference: SQLite has no schemas, so `db.sql` and `db.orm` are the unbound namespace itself (`db.orm.User`, `db.sql.user`) instead of Postgres's `db.orm.public.User` / `db.sql.public.user`. `db.fragment` and `tx.fragment` make a fragment, and `db.orm` holds only the models: `const titled = db.fragment({ title: { codecId: 'sqlite/text@1', nullable: false } }, (rows) => rows.where((r) => r.title.eq('Hello')));` then `await db.orm.Post.with(titled).all();`. The Mongo package shares `db.orm`, `db.close()`, and `[Symbol.asyncDispose]` but has no `db.sql` and no `db.transaction(...)`.
419
419
 
420
420
  The `db.sql` / `db.orm` surfaces stay the same in name; the operators each surface exposes are target-shaped (Mongo has no `JOIN`).
421
421
 
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Prints the files of the project that a change's `detection` block of an upgrade guide finds, one path per line, relative to the working directory, which is the project root.
4
+ *
5
+ * Usage: node find-detection-hits.ts [--all] <glob> [<pattern>...] [--contains <text>...]
6
+ *
7
+ * A file is a hit when `glob` matches its path and any pattern, compiled with `new RegExp(pattern)` and no flags, matches its whole content, or its content contains any `--contains` text. With `--all`, for a detection with `anyMatch: false`, every pattern must match and every text be contained. Pass each pattern and text as it reads once decoded from the guide's YAML.
8
+ *
9
+ * It skips `node_modules` and `.git`, and does not follow symbolic links: a link to a file in the project is found through that file. A `**` in the glob does not enter a folder whose name starts with a dot, but a glob that names one, such as `.github/workflows/*.yml`, does.
10
+ */
11
+ import { readdirSync, readFileSync } from 'node:fs';
12
+ import { join, matchesGlob } from 'node:path';
13
+
14
+ const SKIPPED = new Set(['node_modules', '.git']);
15
+
16
+ function* projectFiles(dir: string, prefix: string): Generator<string> {
17
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
18
+ const path = prefix === '' ? entry.name : `${prefix}/${entry.name}`;
19
+ if (entry.isDirectory() && !SKIPPED.has(entry.name))
20
+ yield* projectFiles(join(dir, entry.name), path);
21
+ else if (entry.isFile()) yield path;
22
+ }
23
+ }
24
+
25
+ function main(args: readonly string[]): number {
26
+ const all = args[0] === '--all';
27
+ const [glob, ...rest] = all ? args.slice(1) : args;
28
+ if (glob === undefined || glob === '' || glob.startsWith('--')) {
29
+ process.stderr.write(
30
+ 'Usage: node find-detection-hits.ts [--all] <glob> [<pattern>...] [--contains <text>...]\n',
31
+ );
32
+ return 1;
33
+ }
34
+ const split = rest.includes('--contains') ? rest.indexOf('--contains') : rest.length;
35
+ const patterns = rest.slice(0, split).map((pattern) => new RegExp(pattern));
36
+ const texts = rest.slice(split + 1);
37
+ const root = process.cwd();
38
+ const hits: string[] = [];
39
+ for (const path of projectFiles(root, '')) {
40
+ if (!matchesGlob(path, glob)) continue;
41
+ const content = readFileSync(join(root, path), 'utf8');
42
+ const results = [
43
+ ...patterns.map((pattern) => pattern.test(content)),
44
+ ...texts.map((text) => content.includes(text)),
45
+ ];
46
+ if (all ? results.every(Boolean) : results.some(Boolean)) hits.push(path);
47
+ }
48
+ process.stdout.write(
49
+ hits
50
+ .sort()
51
+ .map((path) => `${path}\n`)
52
+ .join(''),
53
+ );
54
+ return 0;
55
+ }
56
+
57
+ process.exitCode = main(process.argv.slice(2));