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

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 (240) 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/control.d.mts +1 -1
  15. package/dist/control.d.mts.map +1 -1
  16. package/dist/control.mjs +3 -9
  17. package/dist/control.mjs.map +1 -1
  18. package/dist/init-quick-reference.md +116 -0
  19. package/dist/init-readme.md +35 -0
  20. package/dist/init.d.mts +7 -0
  21. package/dist/init.d.mts.map +1 -0
  22. package/dist/init.mjs +245 -0
  23. package/dist/init.mjs.map +1 -0
  24. package/dist/migration.d.mts +1 -0
  25. package/dist/migration.mjs +2 -0
  26. package/dist/module-base-B70DHaBE-k_c3Klu4.mjs +6 -0
  27. package/dist/module-base-B70DHaBE-k_c3Klu4.mjs.map +1 -0
  28. package/dist/mongo-static-Bti-jnlq-BGWHFTsS.mjs +74 -0
  29. package/dist/mongo-static-Bti-jnlq-BGWHFTsS.mjs.map +1 -0
  30. package/dist/{mongo-static-BdSGXYgQ-DSA-2DiK.d.mts → mongo-static-DabeBtmV-DILuhcbE.d.mts} +18 -5
  31. package/dist/mongo-static-DabeBtmV-DILuhcbE.d.mts.map +1 -0
  32. package/dist/runtime.d.mts +50 -44
  33. package/dist/runtime.d.mts.map +1 -1
  34. package/dist/runtime.mjs +106 -44
  35. package/dist/runtime.mjs.map +1 -1
  36. package/dist/static.d.mts +24 -2
  37. package/dist/static.d.mts.map +1 -0
  38. package/dist/static.mjs +2 -2
  39. package/dist/target__codec-ids.d.mts +1 -0
  40. package/dist/target__codec-ids.mjs +2 -0
  41. package/package.json +25 -70
  42. package/skills/prisma-8/SKILL.md +23 -18
  43. package/skills/prisma-8/references/build-a-target-package.md +117 -0
  44. package/skills/prisma-8/references/build.md +12 -16
  45. package/skills/prisma-8/references/contract.md +184 -78
  46. package/skills/prisma-8/references/debug.md +36 -25
  47. package/skills/prisma-8/references/feedback.md +8 -8
  48. package/skills/prisma-8/references/migration-model.md +23 -14
  49. package/skills/prisma-8/references/migration-review.md +23 -52
  50. package/skills/prisma-8/references/migrations.md +298 -82
  51. package/skills/prisma-8/references/queries-mongo.md +53 -17
  52. package/skills/prisma-8/references/queries-postgres.md +345 -34
  53. package/skills/prisma-8/references/queries.md +44 -25
  54. package/skills/prisma-8/references/quickstart.md +25 -22
  55. package/skills/prisma-8/references/runtime.md +172 -72
  56. package/skills/prisma-8/references/supabase.md +24 -21
  57. package/skills/prisma-8/references/upgrade-app.md +57 -22
  58. package/skills/prisma-8/references/upgrade-extension.md +72 -23
  59. package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/instructions.md +1 -1
  60. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.10-to-8.0.0-rc.11/instructions.md +34 -0
  61. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/instructions.md +639 -0
  62. 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
  63. 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
  64. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/instructions.md +332 -0
  65. 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
  66. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.13-to-8.0.0-rc.14/instructions.md +489 -0
  67. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/instructions.md +1368 -0
  68. 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
  69. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.15-to-8.0.0-rc.16/instructions.md +108 -0
  70. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.16-to-8.0.0-rc.17/instructions.md +755 -0
  71. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/instructions.md +973 -0
  72. 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
  73. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +1862 -0
  74. 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
  75. 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
  76. 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
  77. 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
  78. 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
  79. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +513 -0
  80. 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
  81. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.20-to-8.0.0-rc.21/instructions.md +803 -0
  82. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/instructions.md +586 -0
  83. 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
  84. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.22-to-8.0.0-rc.23/instructions.md +480 -0
  85. 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
  86. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/instructions.md +336 -0
  87. 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
  88. 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
  89. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.24-to-8.0.0-rc.25/instructions.md +1561 -0
  90. package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.9-to-8.0.0-rc.10/instructions.md +13 -0
  91. package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/instructions.md +1 -1
  92. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.10-to-8.0.0-rc.11/instructions.md +34 -0
  93. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.11-to-8.0.0-rc.12/instructions.md +857 -0
  94. 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
  95. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.12-to-8.0.0-rc.13/instructions.md +504 -0
  96. 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
  97. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.13-to-8.0.0-rc.14/instructions.md +143 -0
  98. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.14-to-8.0.0-rc.15/instructions.md +2168 -0
  99. 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
  100. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.15-to-8.0.0-rc.16/instructions.md +223 -0
  101. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.16-to-8.0.0-rc.17/instructions.md +583 -0
  102. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.17-to-8.0.0-rc.18/instructions.md +1008 -0
  103. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.18-to-8.0.0-rc.19/instructions.md +2186 -0
  104. 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
  105. 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
  106. 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
  107. 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
  108. 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
  109. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.19-to-8.0.0-rc.20/instructions.md +381 -0
  110. 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
  111. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.20-to-8.0.0-rc.21/instructions.md +570 -0
  112. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.21-to-8.0.0-rc.22/instructions.md +464 -0
  113. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.22-to-8.0.0-rc.23/instructions.md +410 -0
  114. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.23-to-8.0.0-rc.24/instructions.md +303 -0
  115. 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
  116. 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
  117. package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.24-to-8.0.0-rc.25/instructions.md +1593 -0
  118. package/dist/adapter.d.mts +0 -1
  119. package/dist/adapter.mjs +0 -2
  120. package/dist/adapter__codec-ids.d.mts +0 -1
  121. package/dist/adapter__codec-ids.mjs +0 -2
  122. package/dist/adapter__codec-types.d.mts +0 -1
  123. package/dist/adapter__codec-types.mjs +0 -2
  124. package/dist/adapter__codecs.d.mts +0 -1
  125. package/dist/adapter__codecs.mjs +0 -2
  126. package/dist/adapter__control.d.mts +0 -3
  127. package/dist/adapter__control.mjs +0 -3
  128. package/dist/adapter__runtime.d.mts +0 -3
  129. package/dist/adapter__runtime.mjs +0 -3
  130. package/dist/components.d.mts +0 -1
  131. package/dist/components.mjs +0 -2
  132. package/dist/components__authoring.d.mts +0 -1
  133. package/dist/components__authoring.mjs +0 -2
  134. package/dist/components__codec.d.mts +0 -1
  135. package/dist/components__codec.mjs +0 -2
  136. package/dist/components__components.d.mts +0 -1
  137. package/dist/components__components.mjs +0 -2
  138. package/dist/components__control.d.mts +0 -1
  139. package/dist/components__control.mjs +0 -2
  140. package/dist/components__emission.d.mts +0 -1
  141. package/dist/components__emission.mjs +0 -2
  142. package/dist/components__execution.d.mts +0 -1
  143. package/dist/components__execution.mjs +0 -2
  144. package/dist/components__ir.d.mts +0 -1
  145. package/dist/components__ir.mjs +0 -2
  146. package/dist/components__psl-ast.d.mts +0 -1
  147. package/dist/components__psl-ast.mjs +0 -2
  148. package/dist/components__utils.d.mts +0 -1
  149. package/dist/components__utils.mjs +0 -2
  150. package/dist/contract.d.mts +0 -1
  151. package/dist/contract.mjs +0 -2
  152. package/dist/contract__apply-specifier-default-control-policy.d.mts +0 -1
  153. package/dist/contract__apply-specifier-default-control-policy.mjs +0 -2
  154. package/dist/contract__contract-validation-error.d.mts +0 -1
  155. package/dist/contract__contract-validation-error.mjs +0 -2
  156. package/dist/contract__default-namespace.d.mts +0 -1
  157. package/dist/contract__default-namespace.mjs +0 -2
  158. package/dist/contract__enum-accessor.d.mts +0 -1
  159. package/dist/contract__enum-accessor.mjs +0 -2
  160. package/dist/contract__hashing-utils.d.mts +0 -1
  161. package/dist/contract__hashing-utils.mjs +0 -2
  162. package/dist/contract__hashing.d.mts +0 -1
  163. package/dist/contract__hashing.mjs +0 -2
  164. package/dist/contract__is-plain-record.d.mts +0 -1
  165. package/dist/contract__is-plain-record.mjs +0 -2
  166. package/dist/contract__resolve-domain-model.d.mts +0 -1
  167. package/dist/contract__resolve-domain-model.mjs +0 -2
  168. package/dist/contract__validate-domain.d.mts +0 -1
  169. package/dist/contract__validate-domain.mjs +0 -2
  170. package/dist/driver.d.mts +0 -1
  171. package/dist/driver.mjs +0 -2
  172. package/dist/driver__control.d.mts +0 -3
  173. package/dist/driver__control.mjs +0 -3
  174. package/dist/family-contract__canonicalization-hooks.d.mts +0 -1
  175. package/dist/family-contract__canonicalization-hooks.mjs +0 -2
  176. package/dist/family-contract__entity-kinds.d.mts +0 -1
  177. package/dist/family-contract__entity-kinds.mjs +0 -2
  178. package/dist/family__control-adapter.d.mts +0 -1
  179. package/dist/family__control-adapter.mjs +0 -2
  180. package/dist/family__ir.d.mts +0 -1
  181. package/dist/family__ir.mjs +0 -2
  182. package/dist/family__migration.d.mts +0 -1
  183. package/dist/family__migration.mjs +0 -2
  184. package/dist/family__pack.d.mts +0 -3
  185. package/dist/family__pack.mjs +0 -3
  186. package/dist/family__runtime.d.mts +0 -1
  187. package/dist/family__runtime.mjs +0 -2
  188. package/dist/family__schema-verify.d.mts +0 -1
  189. package/dist/family__schema-verify.mjs +0 -2
  190. package/dist/migration-tools__contract-snapshot-store.d.mts +0 -1
  191. package/dist/migration-tools__contract-snapshot-store.mjs +0 -2
  192. package/dist/mongo-static-BdSGXYgQ-DSA-2DiK.d.mts.map +0 -1
  193. package/dist/mongo-static-_wy-fC4P-mXlhePy0.mjs +0 -38
  194. package/dist/mongo-static-_wy-fC4P-mXlhePy0.mjs.map +0 -1
  195. package/dist/query-ast.d.mts +0 -1
  196. package/dist/query-ast.mjs +0 -2
  197. package/dist/query-ast__control.d.mts +0 -1
  198. package/dist/query-ast__control.mjs +0 -2
  199. package/dist/query-builder__contract-free.d.mts +0 -1
  200. package/dist/query-builder__contract-free.mjs +0 -2
  201. package/dist/target__control.d.mts +0 -1
  202. package/dist/target__control.mjs +0 -2
  203. package/dist/target__pack.d.mts +0 -3
  204. package/dist/target__pack.mjs +0 -3
  205. package/dist/utils.d.mts +0 -1
  206. package/dist/utils.mjs +0 -2
  207. package/dist/utils__abortable.d.mts +0 -1
  208. package/dist/utils__abortable.mjs +0 -2
  209. package/dist/utils__array-equal.d.mts +0 -1
  210. package/dist/utils__array-equal.mjs +0 -2
  211. package/dist/utils__assertions.d.mts +0 -1
  212. package/dist/utils__assertions.mjs +0 -2
  213. package/dist/utils__canonical-stringify.d.mts +0 -1
  214. package/dist/utils__canonical-stringify.mjs +0 -2
  215. package/dist/utils__casts.d.mts +0 -1
  216. package/dist/utils__casts.mjs +0 -2
  217. package/dist/utils__defined.d.mts +0 -1
  218. package/dist/utils__defined.mjs +0 -2
  219. package/dist/utils__hash-content.d.mts +0 -1
  220. package/dist/utils__hash-content.mjs +0 -2
  221. package/dist/utils__internal-error.d.mts +0 -1
  222. package/dist/utils__internal-error.mjs +0 -2
  223. package/dist/utils__json.d.mts +0 -1
  224. package/dist/utils__json.mjs +0 -2
  225. package/dist/utils__promise.d.mts +0 -1
  226. package/dist/utils__promise.mjs +0 -2
  227. package/dist/utils__redact-db-url.d.mts +0 -1
  228. package/dist/utils__redact-db-url.mjs +0 -2
  229. package/dist/utils__result.d.mts +0 -1
  230. package/dist/utils__result.mjs +0 -2
  231. package/dist/utils__simplify-deep.d.mts +0 -1
  232. package/dist/utils__simplify-deep.mjs +0 -2
  233. package/dist/utils__structured-error.d.mts +0 -1
  234. package/dist/utils__structured-error.mjs +0 -2
  235. package/dist/utils__suppress-idle-connection-errors.d.mts +0 -1
  236. package/dist/utils__suppress-idle-connection-errors.mjs +0 -2
  237. package/dist/utils__types.d.mts +0 -1
  238. package/dist/utils__types.mjs +0 -2
  239. package/dist/value__mongodb-types.d.mts +0 -1
  240. package/dist/value__mongodb-types.mjs +0 -2
@@ -11,7 +11,7 @@ The three-step user model:
11
11
 
12
12
  Once the contract changes, you choose how the change reaches the database. This skill covers the two paths (`db update` and `migration plan` + `db migrate`), the migration-package contract, the `migration.ts` authoring API, and the failure modes you recover from without leaving the loop.
13
13
 
14
- **Targets.** Migration authoring is first-class for **Postgres** and **Mongo**. The CLI reads the target from `prisma.config.ts` (set during `prisma orm init --target …`). Migration commands do not accept a `--target` flag — use a config scoped to the target you need. Examples below call out target-specific imports, markers, factories, and transaction behavior where they diverge.
14
+ **Targets.** This reference covers migration authoring for **Postgres** and **Mongo**. The CLI reads the target from `prisma.config.ts` (set during `prisma orm init --target …`). Migration commands do not accept a `--target` flag — use a config scoped to the target you need. Examples below call out target-specific imports, markers, factories, and transaction behavior where they diverge.
15
15
 
16
16
  ## When to Use
17
17
 
@@ -20,6 +20,7 @@ Once the contract changes, you choose how the change reaches the database. This
20
20
  - User wants to run pending migrations against a local DB.
21
21
  - User hit `MIGRATION.HASH_MISMATCH`, `MIGRATION.UNFILLED_PLACEHOLDER`, or a partially-applied migration.
22
22
  - User mentions: *migrate, migration, db push, db update, `prisma migrate dev`, `prisma migrate deploy`, drift, hash mismatch, data backfill*.
23
+ - A deploy or `db migrate` fails with `MIGRATION.MARKER_MISMATCH` (older Composer releases: "no authored path"), or someone proposes resetting a database → *A database whose marker is not in the migration graph* below. For `MIGRATION.PATH_UNREACHABLE`, where the marker is in the graph but no migration reaches the target, plan from the marker to the target instead (`references/debug.md`).
23
24
 
24
25
  ## When Not to Use
25
26
 
@@ -30,29 +31,31 @@ Once the contract changes, you choose how the change reaches the database. This
30
31
 
31
32
  ## Key Concepts
32
33
 
33
- - **`db update` (quick path).** Reads the emitted contract, diffs against the live DB, applies the change. Optional `--dry-run` prints the plan without executing. A destructive operation is applied only with consent: interactively you type the database name; non-interactively pass `--confirm <database>` (`--yes` does not grant it). **Writes no migration directory.** Operations needing data transforms are not handled by this path — `db update` excludes the `data` operation class entirely and short-circuits where a data transform would be required. Use only against a database that has no shared history with anyone else (your local dev DB).
34
- - **`migration plan` (formal path).** Reads the emitted contract, diffs it against a resolved origin — explicit `--from`, else the `db` ref, else the empty database; there is no "head of the graph" to chain from (see `references/migration-model.md`) — and writes a new migration package under `migrations/app/<YYYYMMDDTHHMM>_<snake_slug>/`. If any operation needs a data transform, the package's `migration.ts` contains `placeholder(...)` calls you fill in.
34
+ - **`db update` (quick path).** Reads the emitted contract, diffs against the live DB, applies the change. Optional `--dry-run` prints the plan without executing. Before an apply it asks what each operation that would lose data means, answered by `--delete <subject>` or `--rename <subject>:<new name>`, and whether each operation that would change who can read or write a model's data may run, answered by `--allow <Model>` (see *Answer the data-loss questions* below). **Writes no migration directory.** Operations needing data transforms are not handled by this path — `db update` excludes the `data` operation class entirely and short-circuits where a data transform would be required. It refuses `--convert` and `--backfill` (`MIGRATION.STATEMENT_NEEDS_MIGRATION_FILE`) and prints the `migration plan` command to run instead. Use it on a database whose migration history does not need to be kept (a local, development, staging or preview database), shared or not. Never use it on a database that changes only through migrations, such as production: it leaves no migration behind. A database says which it is in its *change policy* (see *Policies: what a database says about how it may change* below); `db update` refuses one whose policy permits only migrations.
35
+ - **`migration plan` (formal path).** Reads the emitted contract, diffs it against a resolved origin — explicit `--from`, else the `db` ref, else the empty database; there is no "head of the graph" to chain from (see `references/migration-model.md`) — and writes a new migration package under `migrations/app/<YYYYMMDDTHHMM>_<snake_slug>/`. A plan that would lose data is written only once `--delete`, `--rename` or, for a type change, `--convert` says what each such operation means. The package's `migration.ts` contains `placeholder(...)` calls only where `--convert` or `--backfill` asked for a slot (see *Type changes and new required fields*).
35
36
  - **The `app/` segment in migration paths is the consuming application's contract-space id.** Every migration *you* author lives under `migrations/app/`. Extensions your contract depends on get their own sibling directories (`migrations/<extension-space-id>/`) — those are managed by the extension package and you don't write into them. The `app/` segment lands automatically the first time you run `migration plan` / `db init` against an app-level config.
36
37
  - **Migration package files** (inside each `migrations/app/<dir>/`):
37
38
  - `migration.json` — manifest (metadata + `migrationHash`).
38
39
  - `ops.json` — canonical operation list. Content-addressed; `migrationHash` is computed over this.
39
40
  - `migration.ts` — TypeScript authoring source, **framework-rendered** by `migration plan` (or `migration new`). You edit specific holes in it (see *Fill a placeholder* below) and re-emit `ops.json` / `migration.json` by running it.
40
41
  - **Contract snapshots.** `migration.ts` imports its bookend contracts from the shared, content-addressed store at `migrations/snapshots/<hex>/contract.json` + `contract.d.ts` (`<hex>` is the contract's 64-hex storage hash) — not from files inside the migration package.
41
- - **Self-emit.** Running `node migrations/app/<dir>/migration.ts` regenerates `ops.json` and `migration.json` from the (possibly edited) TS source. This is the only supported way to update an existing migration package after edits.
42
- - **`migration.ts` shape.** Framework-rendered. A class `M extends Migration<Start, End>` (from `@internal/postgres/migration` on Postgres, `@prisma/orm-mongo/target/migration` on Mongo — see the framing block below) that assigns the two snapshot imports to `startContractJson` / `endContractJson` (`Start` is `never` and there is no `startContractJson` on a baseline) and has an `operations` getter returning an array of operation values. **On Postgres the operation factories are methods on the base class** (`this.addColumn({...})`, `this.setNotNull({...})`, `this.dataTransform(...)`) taking one options object; free helpers like `col(...)` build the column descriptors they take. **On Mongo they are free factories** (`createIndex(...)`, `dataTransform(...)`) imported beside `Migration`. The file ends with `MigrationCLI.run(import.meta.url, M)` so executing it self-emits.
42
+ - **Self-emit.** Running `node <package dir>/migration.ts` regenerates `ops.json` and `migration.json` from the (possibly edited) TS source. This is the only supported way to update an existing migration package after edits. `<package dir>` is the directory `migration plan` or `migration new` printed; it sits under the config's `migrations.dir` (by default `migrations/app/<dir>`), so the path depends on that setting. The command works from any directory. Without `--config`, the file uses the config whose migrations directory holds it: the nearest `prisma.config.ts` above it, else the one in the working directory; if neither does, it fails with `CLI.MIGRATION_CONFIG_NOT_FOUND`. If you gave the CLI `--config`, pass the same `--config <path>` to the file.
43
+ - **`migration.ts` shape.** Framework-rendered. A class `M extends Migration<Start, End>` (from `@prisma/orm-postgres/migration` on Postgres, `@prisma/orm-mongo/target/migration` on Mongo — see the framing block below) that assigns the two snapshot imports to `startContractJson` / `endContractJson` (`Start` is `never` and there is no `startContractJson` on a baseline) and has an `operations` getter returning an array of operation values. **On Postgres the operation factories are methods on the base class** (`this.addColumn({...})`, `this.setNotNull({...})`, `this.dataTransform(...)`) taking one options object; free helpers like `col(...)` build the column descriptors they take. **On Mongo they are free factories** (`createIndex(...)`, `dataTransform(...)`) imported beside `Migration`. The file ends with `MigrationCLI.run(import.meta.url, M)` so executing it self-emits.
43
44
  - **`placeholder(slot)`.** A sentinel the planner emits into the rendered `migration.ts` (from the same `.../migration` import as `Migration`) wherever a data transform is needed. Calling `placeholder(...)` at emit time throws `MIGRATION.UNFILLED_PLACEHOLDER` with `meta.slot` naming the hole. The user replaces the `() => placeholder(...)` arrow with a real query-plan closure (Postgres) or fills `dataTransform({ check, run })` sources (Mongo — see *Fill a placeholder*), then self-emits.
44
- - **`this.dataTransform(endContract, name, { check, run })`.** The data-transform factory. `check` is a rowset query whose presence-of-any-row signals "work remains"; `run` is one or more mutation queries that perform the backfill. Both are lazy closures returning query-plans built against `endContract`. The runner wraps `check` as `EXISTS(...)` for precheck and `NOT EXISTS(...)` for postcheck, so the same closure asserts both "there is work" and "the work is done".
45
+ - **`this.dataTransform(contract, name, { check, run })`.** The Postgres data-transform factory. `check` is a rowset query whose presence-of-any-row signals "work remains"; `run` is one or more mutation queries that perform the backfill. Both are lazy closures returning query plans built with the SQL query builder over the end contract. `contract` is the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns, not the imported `endContract` JSON the planner renders (see *Fill a placeholder*). The runner wraps `check` as `EXISTS(...)` for precheck and `NOT EXISTS(...)` for postcheck, so the same closure asserts both "there is work" and "the work is done".
45
46
  - **`pendingPlaceholders`.** A boolean field on the JSON result of `migration plan`. `true` means the package was written but contains unfilled placeholders — `db migrate` will throw `MIGRATION.UNFILLED_PLACEHOLDER` until you edit `migration.ts` and self-emit.
46
47
  - **`migrationHash`.** Content-addressed identity of a migration package. `MIGRATION.HASH_MISMATCH` fires when the stored hash in `migration.json` disagrees with the hash recomputed from the on-disk files (almost always: someone edited `migration.ts` without self-emitting).
47
- - **Marker.** Records "this database is at contract hash X for space Y". **Postgres:** a row in `prisma_contract.marker`. **Mongo:** a document in the `_prisma_migrations` collection (keyed by space). Each successful migration advances the marker once schema verification passes for that space. `db sign` writes the marker from the current contract hash, but only after a schema-verification pass succeeds (it will not sign a database whose live schema disagrees with the contract).
48
+ - **Marker.** Records "this database is at contract hash X for space Y". **Postgres:** a row in `prisma.signatures`. **Mongo:** a document in the `_prisma_migrations` collection (keyed by space). Each successful migration advances the marker once schema verification passes for that space. `db sign` writes the marker from the current contract hash, but only after a schema-verification pass succeeds (it will not sign a database whose live schema disagrees with the contract).
48
49
  - **Apply atomicity.** **Postgres:** one `db migrate` run is one transaction — the runner issues a single `BEGIN`, applies every pending migration for every contract space, then one `COMMIT`; any failure issues `ROLLBACK` for the whole run, so the marker stays where it was before the command. **Mongo:** DDL ops (`createCollection`, `createIndex`, `collMod`, `setValidation`, …) are not wrapped in a multi-document transaction; the runner applies ops, verifies the live schema against the destination contract, and advances the marker only on verify-pass (resumable across spaces — see the MongoDB family doc). Ordinary DDL + `dataTransform` flows stay consistent; partial state from failed mid-migration runs is diagnosed with `db verify` / `db schema`, not assumed away.
49
- - **Operation classes.** Every operation declares an `operationClass`: `additive`, `widening`, `data`, or `destructive`. The CLI surfaces these in the plan preview and in JSON output. There is no `long-running` class and the framework does not emit `CREATE INDEX CONCURRENTLY` — operations stay transactional.
50
+ - **Changed foreign key actions and primary keys (Postgres).** A changed `onDelete`/`onUpdate` plans a drop and an add of the foreign key. A moved or removed primary key plans a drop (and an add), and the foreign keys that reference the old key are dropped first and added back after it. These ask no data-loss question.
51
+ - **Policies.** A database records how it may be changed (**Postgres:** in the one row of `prisma.config`; **Mongo** and the other SQL targets: in the application space's marker, under `meta.policies`): its *change policy* (`migrate`, `reconcile` or both; `reconcile` is what `db update` and `db sign` do) and its *data protection policy* (`dataLoss` and `accessWidening`, each `forbidden`, `with-consent` or `permitted`). Every command that changes a database obeys both. A ref declares the policies its database should have in a `policies` field. See *Policies: what a database says about how it may change* below.
52
+ - **Operation classes.** Every operation declares an `operationClass`: `additive`, `widening`, `data`, or `destructive`. `additive` adds structure and leaves existing structure and data as they are. `widening` changes existing structure without losing data; an operation that cannot keep every value fails instead, so a tightened constraint such as `SET NOT NULL` is widening. `destructive` can lose rows or values: dropping a table or column, or a type change that can change values. `data` reads and writes rows as its author wrote them, such as a backfill or a type conversion; a `dataTransform` is always `data`. Each operation factory sets its own class (`this.alterColumnType` is `data` with `using` and `destructive` without it, unless you pass `operationClass`). A `rawSql` step you write takes the class of the factory that would express it, or the class the definitions above give. The CLI surfaces these in the plan preview and in JSON output. There is no `long-running` class and the framework does not emit `CREATE INDEX CONCURRENTLY` — operations stay transactional.
50
53
 
51
54
  ## `migration.ts` is framework-rendered, not hand-authored
52
55
 
53
56
  Files under `migrations/<space-id>/<timestamp>/migration.ts` (for your own app, `<space-id>` is always `app/`) are **rendered for you** by the framework — `prisma migration plan` writes a populated package whenever the contract changes, and `prisma migration new` writes an empty scaffold when you want to author operations directly. You do not write these files from scratch. You edit specific holes the framework leaves behind — chiefly replacing `placeholder("<slot>")` sentinels (Postgres) or filling `dataTransform({ check, run })` pipeline slots (Mongo) — then self-emit.
54
57
 
55
- **Postgres** rendered imports point at `@internal/postgres/migration` (or `@internal/sqlite/migration` for SQLite projects): one line carrying `Migration`, `MigrationCLI`, `col`, `placeholder`, `rawSql`, and any other free helper the operations need.
58
+ **Postgres** rendered imports point at `@prisma/orm-postgres/migration` (or `@prisma/orm-sqlite/migration` for SQLite projects): one line carrying `Migration`, `MigrationCLI`, `col`, `placeholder`, `rawSql`, `sql` when the file writes a `sql` value, and any other free helper the operations need.
56
59
 
57
60
  **Mongo** rendered imports point at one module too, `@prisma/orm-mongo/target/migration`, which carries `Migration`, `MigrationCLI`, `placeholder`, and the operation factories (`createIndex`, `dataTransform`, …). Raw command classes for data transforms come from `@prisma/orm-mongo/query-ast/execution`.
58
61
 
@@ -60,7 +63,7 @@ Treat the rendered import lines as framework-managed on both targets:
60
63
 
61
64
  - Leave them where they are. Don't rewrite them to a different path; the framework's renderer is the authoritative shape and any change you make by hand will be reverted (and may trip `MIGRATION.HASH_MISMATCH`) the next time the package is re-rendered or self-emitted.
62
65
  - If you need an additional helper symbol, **add it to the existing rendered import line** rather than introducing a second import from a different subpath.
63
- - The "user code imports only from `@internal/<target>`" convention applies to *your* own modules (queries, runtime setup, contract authoring). The framework-rendered `migration.ts` scaffold is the framework's surface, not yours; the rule is suspended for that one file.
66
+ - The "user code imports only from `@prisma/orm-<target>`" convention applies to *your* own modules (queries, runtime setup, contract authoring). The framework-rendered `migration.ts` scaffold is the framework's surface, not yours; the rule is suspended for that one file.
64
67
 
65
68
  ## Diagnostic codes you route on
66
69
 
@@ -69,43 +72,56 @@ Treat the rendered import lines as framework-managed on both targets:
69
72
  | `MIGRATION.UNFILLED_PLACEHOLDER` | Throwing `placeholder(...)` at emit time | Open `migration.ts`, replace the `placeholder("<slot>")` call named by `meta.slot` with the real query closure, self-emit. |
70
73
  | `MIGRATION.FILE_MISSING` | Reading a migration package | `migration.ts`, `migration.json`, or `ops.json` is absent. Recover from version control, re-emit via `migration.ts`, or run `prisma migration new` for a fresh one. |
71
74
  | `MIGRATION.INVALID_DEFAULT_EXPORT` | Loading `migration.ts` | The file's default export is not a `Migration` subclass or factory function. Restore the planner-emitted scaffold from version control or re-run `migration plan` for a clean package. |
72
- | `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` | Building a data-transform query plan | The query builder was instantiated with a contract reference different from the `endContract` passed to `this.dataTransform(...)`. Use the `endContract` imported at module scope for both. |
73
- | `MIGRATION.HASH_MISMATCH` *Migration package is corrupt* | `db migrate` (or any read of the package) | `ops.json` / `migration.json` were edited without self-emitting. Run `node migrations/app/<dir>/migration.ts` to re-emit, then re-run `db migrate`. |
74
- | `MIGRATION.DESTRUCTIVE_CHANGES` | `db update` run non-interactively without consent | Re-run with `--confirm <database>` (the database name from the connection), or `--dry-run` to preview. |
75
- | `CONTRACT.MARKER_MISMATCH` | `db verify` (finding, exit 4) | The marker disagrees with the contract hash (**Postgres:** `prisma_contract.marker`; **Mongo:** `_prisma_migrations`). The DB is at a different contract version than the code thinks. Either run a migration forward, or — if the DB is correct and the marker is stale after a manual fix-up — run `db sign`. |
75
+ | `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` | Building a data-transform query plan | The query builder was built over a different contract than the one passed to `this.dataTransform(...)`. Pass the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns to `this.dataTransform`, and build the queries with that client's `sql`. |
76
+ | `MIGRATION.HASH_MISMATCH` *Migration package is corrupt* | `db migrate` (or any read of the package) | `ops.json` / `migration.json` were edited without self-emitting. Run `node <package dir>/migration.ts` to re-emit, then re-run `db migrate`. |
77
+ | `CLI.CONSENT_REQUIRED` | `migration plan` / `db update` run with nobody to answer (`--no-interactive`, CI, `--yes`) | The plan would lose data or (on `db update`) widen access. `meta.unanswered` and `nextActions` list each question with the flags that answer it: `--delete <subject>`, `--rename <subject>:<new name>`, `--allow <Model>`. Re-run with the ones you mean. `--confirm` and `--yes` answer none of them. |
78
+ | `CLI.CONSENT_UNUSED` | `migration plan` / `db update` | Every question was answered, and a `--delete` or `--allow` was left over: a typo, a subject the plan does not touch, or a `--confirm` (which consents to nothing). Fix or drop the flag. A typo next to a question nobody answered is reported as `CLI.CONSENT_REQUIRED` instead, which names the flag that matched nothing. On `db update --dry-run` the same mistake is `MIGRATION.STATEMENT_ANSWERS_NO_QUESTION`. |
79
+ | `MIGRATION.STATEMENT_DID_NOT_RESOLVE_LOSS` | A rename typed at the data-loss prompt | The plan was made again with the rename and still loses the subject's data. Answer with `delete`, or give a rename whose old name is the subject. |
80
+ | `CONTRACT.MARKER_MISMATCH` | `db verify` (finding, exit 4) | The marker disagrees with the contract hash (**Postgres:** `prisma.signatures`; **Mongo:** `_prisma_migrations`). The DB is at a different contract version than the code thinks. Either run a migration forward, or — if the DB is correct and the marker is stale after a manual fix-up — run `db sign`. |
81
+ | `CONTRACT.PRISMA_SPACE_BEHIND` | `db verify`, `migration status`, `migration log`, dry runs; the client's first query (a warning, only when the client is given a `log`) | The records Prisma keeps for itself in the database are not up to date with the installed release, for example a database a release candidate set up, whose tables are in `prisma_contract`. Run the command the project already uses to change its database: `prisma db migrate` with migrations, `prisma db update` with `db update`, or `prisma db sign` if it only signs. Each brings the records up to date before its usual work. Then run the read again. |
82
+ | `MIGRATION.INSTALLED_SPACE_UNREACHABLE` | `db init`, `db update`, `db migrate`, `db sign`, `db verify` | The records Prisma keeps for itself were changed by a release this one cannot follow: `meta.reason` is `laterMajor` when a later major version of Prisma changed them, `unknownContract` otherwise. Use the release that last changed the database, or a newer one. Do not edit them by hand. |
76
83
  | `CONTRACT.MARKER_MISSING` | `db verify` (finding, exit 4), runtime startup (warning) | The DB has no marker yet. Run `prisma db init --db <url>` to baseline an empty database, `db update --db <url>` to apply the current contract directly, or `db sign --db <url>` if the schema already matches the contract. |
84
+ | `MIGRATION.STATEMENT_INVALID` | `migration plan` / `db update` with `--rename` | The statement is malformed, mixes a model and a field, renames something to itself, swaps two names, or repeats a name. The error's next step is the statement to type instead; use it. |
85
+ | `MIGRATION.STATEMENT_UNRESOLVED` | `migration plan` / `db update` with `--rename` | A name is not where a rename needs it. The error lists the names it found and says what to type: the statement the right way round, the order that works, or to leave out a rename that has already happened. |
86
+ | `MIGRATION.CHANGE_POLICY_FORBIDS` | `db update`, `db sign`, `db migrate` | The database's change policy does not include what the command does (`meta.change` lists what it permits). When `db update` or `db sign` is refused, the database changes only through migrations: follow its advice, which says to apply the migrations on disk that already lead to the target with `db migrate`, or to author one (with `migration plan`, or with `migration new` when the database is already at the target and lacks only invariants) and apply it with `db migrate`. Do not look for a way round the policy. |
87
+ | `MIGRATION.POLICY_MISMATCH` | `db migrate --to <ref>`, `db update --to <ref>`, a Composer deploy | The ref declares a policy that differs from the database's (`why` names each setting with both values). Nothing runs while they differ. The error says to report the difference to whoever owns the database: tell the user; do not change the ref's or the database's policies to make them match, and never suggest that anyone does. See *Policies* below. |
88
+ | `MIGRATION.STATEMENT_ORIGIN_UNKNOWN` | `db update --rename` | `db update` has no snapshot of the contract the database is at. Follow the error's steps: emit that contract, run `db update --advance-ref <name> --dry-run` and check it plans no operations, then run it without `--dry-run` to store its snapshot, then emit the new contract and run the rename. Do not drop the statements to get past it: without them the plan drops the renamed table with its rows. |
77
89
 
78
90
  ## Decision — which path do you take?
79
91
 
80
92
  | Situation | Path | Why |
81
93
  |---|---|---|
82
- | Local dev, schema in flux | `db update` | Fast, interactive, no migration files. |
83
- | Shared branch with other developers | `migration plan` + `db migrate` | Replayable, reviewable, content-hashed. |
84
- | Anything reaching production | `migration plan` + `db migrate` | Production must run a reviewed, hashed migration. |
85
- | Adding a column that needs a backfill | `migration plan` (writes `placeholder`), edit `migration.ts`, self-emit, then `db migrate` | `db update` does not author data transforms; the formal path does. |
86
- | Recovering from drift (DB diverged from contract) | `db sign` after manual fix, *or* `migration plan` if PN can plan the fix | Depends on which side is right. See *Recover from drift* below. |
94
+ | Moving a database whose history does not need to be kept (local, development, staging, preview) to the contract | `db update` | Fast, no migration files. Works whether or not the database is shared. |
95
+ | A change other developers or environments will receive | `migration plan` + `db migrate` | Replayable, reviewable, content-hashed. |
96
+ | A database that changes only through migrations, such as production | `migration plan` + `db migrate` | It must run a reviewed, hashed migration. |
97
+ | A deploy says there is no migration path, or `MIGRATION.MARKER_MISMATCH` | See *A database whose marker is not in the migration graph* | Never reset the database. |
98
+ | Adding a column that needs a backfill | `migration plan --backfill Model.field` (writes `placeholder`), edit `migration.ts`, self-emit, then `db migrate` | `db update` does not author data transforms; the formal path does. Without `--backfill`, existing rows get a temporary value. |
99
+ | Changing a field's type so values may not survive | `migration plan --convert Model.field`, fill `using`, self-emit, `db migrate` | Or `--delete Model.field` to let the database cast; the cast may cut or round values (Postgres cuts a longer text to a shorter `varchar`), and a value it cannot cast fails the apply. |
100
+ | Recovering from drift (DB diverged from contract) | `db sign` after manual fix, *or* `migration plan` if Prisma 8 can plan the fix | Depends on which side is right. See *Recover from drift* below. |
87
101
 
88
102
  ## Dev → ship transition (the `db` ref pattern)
89
103
 
90
104
  Example — iterate locally with `db update`, then publish the first real migration:
91
105
 
92
106
  ```bash
93
- pnpm prisma db init --db $DATABASE_URL
94
- pnpm prisma contract emit && pnpm prisma db update --db $DATABASE_URL
107
+ pnpm prisma db init
108
+ pnpm prisma contract emit && pnpm prisma db update
95
109
  pnpm prisma contract emit && pnpm prisma migration plan --name add_feature
96
- pnpm prisma db migrate --db $DATABASE_URL
97
- pnpm prisma db verify --db $DATABASE_URL
110
+ pnpm prisma db migrate
111
+ pnpm prisma db verify
98
112
  ```
99
113
 
114
+ Every command here reaches the database through `db.connection` in `prisma.config.ts`, which is what lets `db init`, `db update` and `db migrate` keep the `db` ref current.
115
+
100
116
  The `db` ref is a named pointer at `migrations/app/refs/db.json` — just `{ hash, invariants }`. It records which contract hash the project's dev database has been brought up to — the offline planner's stand-in for "where is my local DB?" without opening a connection at plan time. The contract it names resolves through the shared content-addressed store at `migrations/snapshots/<hex>/contract.json` by that hash, the same store every migration graph node resolves through.
101
117
 
102
- **What `db init` / `db update` / `db sign` write.** When run against the project's default `--db` URL (no explicit `--db` flag), `db init` and `db update` implicitly advance the `db` ref: they write-if-absent the post-command contract IR into the snapshot store, then write the ref's pointer. Override the ref name with `--advance-ref <name>`. When you pass `--db <non-default-url>`, ref advancement is suppressed unless `--advance-ref` is explicit — reconciling a different database is not the same as checkpointing this project's dev state. `db sign` also advances the `db` ref after a successful signature, writing the signed contract into the snapshot store first; `--advance-ref <name>` overrides the name, and `--db` does **not** suppress it — sign never mutates the schema, and adoption is normally done against the real database via `--db`. The only opt-out is `--no-advance-ref`, which signs without writing any ref or snapshot — what a CI or deployment pipeline, or a dev checkout re-signing a production database, usually wants.
118
+ **What `db init` / `db update` / `db migrate` / `db sign` write.** When run against the project's default `--db` URL (no explicit `--db` flag), `db init` and `db update` implicitly advance the `db` ref: they write-if-absent the post-command contract IR into the snapshot store, then write the ref's pointer. Override the ref name with `--advance-ref <name>`. When you pass `--db <non-default-url>`, ref advancement is suppressed unless `--advance-ref` is explicit — reconciling a different database is not the same as checkpointing this project's dev state. `db migrate` follows the same rule after a successful apply, with one addition: it advances nothing when the CLI detects CI, so pipelines that read their URL through the config write no ref. Unless the `CI` environment variable is `false`, which turns detection off whatever else is set, the CLI detects CI when `CI` is set or when a variable that CI services set is present, such as `BUILD_NUMBER`, `BUILD_ID` or `GITHUB_ACTIONS`, and the run then reports `MIGRATION.REF_NOT_ADVANCED_IN_CI`. On a developer's machine, a variable in the shell, or in a `.env` file that `prisma.config.ts` loads (for example with `import 'dotenv/config'`), can turn advancement off; that notice says so, and a pipeline silences it with `--no-advance-ref`. A run that brings the database to the empty contract leaves `db` unchanged, because a ref cannot name it; when a `db` ref exists and the run passes neither `--db` nor `--no-advance-ref`, it warns with `MIGRATION.REF_NOT_ADVANCED_TO_EMPTY`, naming the hash `db` still holds (with either flag the ref is left unchanged and there is no warning); when that database is your development database, remove the stale ref with `migration ref delete db`. `--advance-ref <name>` advances that ref instead in every case except a run that ends at the empty contract, which it refuses before applying with `MIGRATION.REF_TARGET_EMPTY`, and `--no-advance-ref` advances none. A ref `db migrate` cannot write, for example on a read-only filesystem, is a warning (`MIGRATION.REF_NOT_WRITTEN`) and the command still exits 0, since the migrations have already applied; its next action is the command that writes it later: `migration ref set` when the snapshot store holds the contract for that hash, and otherwise the same `db migrate` with `--advance-ref <name>`, which applies nothing and writes both. `db sign` also advances the `db` ref after a successful signature, writing the signed contract into the snapshot store first; `--advance-ref <name>` overrides the name, and `--db` does **not** suppress it — sign never mutates the schema, and adoption is normally done against the real database via `--db`. The only opt-out is `--no-advance-ref`, which signs without writing any ref or snapshot — what a CI or deployment pipeline, or a dev checkout re-signing a production database, usually wants.
103
119
 
104
120
  The on-disk layout is just the pointer:
105
121
 
106
122
  ```text
107
123
  migrations/app/refs/
108
- └── db.json # { "hash": "<hex>", "invariants": [] }
124
+ └── db.json # { "formatVersion": 1, "hash": "<hex>", "invariants": [] }
109
125
  ```
110
126
 
111
127
  **First `migration plan` after dev iteration.** `migration plan` defaults `--from` to the `db` ref (and, when no `db` ref exists at all, falls back to planning from an empty database only while the migration graph is empty — the human output then adds a muted notice beneath the summary, `No db ref set — planning from an empty database. Run db init, db update, or db sign if a database already exists.`, and the JSON document carries `fromDefaulted: true`; over a non-empty graph there is no fallback: the command refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN`; see `references/migration-model.md` § *The trap*). When the on-disk migration graph is still **empty** and the `db` ref points at a non-null hash with a store entry (typical after one or more `db update` cycles), the planner emits **two** bundles instead of one:
@@ -130,9 +146,9 @@ pnpm prisma migration plan --name my_change
130
146
 
131
147
  If the `db` ref's pointer is itself missing and the hash isn't a graph node either (`MIGRATION.SNAPSHOT_MISSING`), create it with `migration ref set db <hash>` or advance it with `db update --advance-ref db`.
132
148
 
133
- **After plain `db migrate`.** `db migrate` does not implicitly advance the `db` ref (production-shaped commands stay explicit). The live marker advances while the ref may lag. Refresh with `db update` (no-op on DB when already current) or `db migrate --advance-ref db` in the same invocation.
149
+ **After `db migrate` with `--db`, with `--no-advance-ref` or in CI.** The live marker advances and the `db` ref does not. The `db` ref records where development plans start, so move it only for your development database, never for a deployment database. On the development database, run the same `db migrate` again with `--advance-ref db`, without `--no-advance-ref`: it applies nothing and moves the ref to the contract the database is at. If that run ended at the empty contract (`--to @empty`, or a rollback of the first migration with `--to <first-migration-dir>^`), no ref can name it and `--advance-ref db` is refused with `MIGRATION.REF_TARGET_EMPTY`; remove the stale ref with `migration ref delete db` instead.
134
150
 
135
- **When to switch paths.** Use `db update` while the schema is in flux on a solo dev database. Switch to `migration plan` + `db migrate` when the change needs a reviewable, replayable migration — typically before opening a PR or touching any shared environment. The `db` ref bridges the two: it captures dev iteration state on disk so the first formal plan knows where you left off.
151
+ **When to switch paths.** Use `db update` while the schema is in flux, on a database whose migration history does not need to be kept (a local, development, staging or preview database). Switch to `migration plan` + `db migrate` when the change needs a reviewable, replayable migration — typically before opening a PR, and always for a database that changes only through migrations, such as production. The `db` ref bridges the two: it captures dev iteration state on disk so the first formal plan knows where you left off.
136
152
 
137
153
  **Graph-node rule (plan time).** Any hash used as a `from` end — explicit `--from`, default `db` ref, or ref name — must already be a node in the on-disk migration graph once the graph is non-empty. The auto-baseline two-bundle emission is the one exception: it applies only on an **empty** graph with a non-null ref-resolved `from` and an available store entry. If the ref's pointer is missing and the hash isn't a graph node either, plan refuses with `MIGRATION.SNAPSHOT_MISSING` instead.
138
154
 
@@ -144,7 +160,7 @@ Canonical detail: [Migration System § Contract resolution through the snapshot
144
160
 
145
161
  ## Workflow — `db update` (quick path)
146
162
 
147
- The concept: `db update` resolves the destination (`emitted contract`) against the live DB and applies the difference. Preview with `--dry-run`. Destructive ops need consent: interactively the command asks you to type the database name; with `--no-interactive` (CI) it reads `--confirm <database>` instead, and refuses with `MIGRATION.DESTRUCTIVE_CHANGES` if neither is given. `--yes` accepts prompt defaults and never grants this consent. The path excludes operations of the `data` class entirely — if the diff requires a data transform, `db update` fails with a planning error and you switch to `migration plan` to author the transform.
163
+ The concept: `db update` resolves the destination (`emitted contract`) against the live DB and applies the difference. Preview with `--dry-run`, which asks nothing and lists the questions an apply would ask under `dataLoss` and `accessChanges`. An apply that would lose data or change access asks first (see *Answer the data-loss questions*). The path excludes operations of the `data` class entirely — if the diff requires a data transform, `db update` fails with a planning error and you switch to `migration plan` to author the transform.
148
164
 
149
165
  Run after a contract edit:
150
166
 
@@ -164,7 +180,7 @@ Inspect the JSON output to drive the next move:
164
180
  pnpm prisma db update --db $DATABASE_URL --json
165
181
  ```
166
182
 
167
- The JSON contains `plan.operations[]` with each `operationClass`, plus (in apply mode) `execution.operationsExecuted` and the post-apply `marker.storageHash`. If the command failed because of destructive operations, the error envelope's `meta.destructiveOperations[]` lists exactly what would have been dropped.
183
+ The JSON contains `plan.operations[]` with each `operationClass`, plus (in apply mode) `execution.operationsExecuted` and the post-apply `marker.storageHash`. If the command was refused because nobody answered its questions, the error is `CLI.CONSENT_REQUIRED`, and its `meta.unanswered[]` lists each subject with the flags that answer it.
168
184
 
169
185
  ## Workflow — `migration plan` + `db migrate` (formal path)
170
186
 
@@ -206,10 +222,12 @@ pnpm prisma db migrate --show --from <hash-or-ref> --to <hash-or-ref>
206
222
  Fill in any data transforms (see *Fill a placeholder*), self-emit if you edited `migration.ts`, then:
207
223
 
208
224
  ```bash
209
- pnpm prisma db migrate --db $DATABASE_URL
225
+ pnpm prisma db migrate
210
226
  ```
211
227
 
212
- `db migrate` runs without prompting — destructive-op confirmation lives on `db update`, not here. Review destructive ops in the plan output or in `migration show` *before* applying.
228
+ On the database `prisma.config.ts` connects to, when the CLI does not detect CI, `db migrate` also moves the `db` ref to the contract it applied, so the next `migration plan` starts there. Against another database, pass `--db <url>`; that run leaves the `db` ref alone.
229
+
230
+ `db migrate` runs without prompting: the data-loss questions were answered when `migration plan` wrote the package. Review `destructive` and `data` operations in the plan output or in `migration show` *before* applying.
213
231
 
214
232
  ## Workflow — Fill a placeholder
215
233
 
@@ -217,13 +235,13 @@ The concept: the planner can detect *that* a data transform is needed but not *w
217
235
 
218
236
  ### Postgres
219
237
 
220
- The planner can detect *that* a data transform is needed (e.g. backfilling a new `NOT NULL` column with no default) but not *what* it should do. You fill `check` and `run` closures with real query plans built against `endContract`.
238
+ `--backfill` asks the planner for a data transform it cannot write itself, for example to fill a new required column `name` on a table with rows: `pnpm prisma migration plan --name add_user_name --backfill User.name`. Without the flag the rows get a temporary value instead. Each slot is named by the field and the part to fill, `User.name:check` and `User.name:run`. You fill `check` and `run` closures with real query plans built with the SQL query builder over the end contract.
221
239
 
222
240
  The scaffold the planner emits looks like:
223
241
 
224
242
  ```typescript
225
243
  // migrations/app/20260515T1200_add_user_name/migration.ts
226
- import { col, Migration, MigrationCLI, placeholder } from '@internal/postgres/migration';
244
+ import { col, Migration, MigrationCLI, placeholder } from '@prisma/orm-postgres/migration';
227
245
  import type { Contract as End } from '../../snapshots/93f07d1b…c9e1e5a2/contract';
228
246
  import endContract from '../../snapshots/93f07d1b…c9e1e5a2/contract.json' with { type: 'json' };
229
247
  import type { Contract as Start } from '../../snapshots/f62a4154…d07dddc/contract';
@@ -241,8 +259,9 @@ export default class M extends Migration<Start, End> {
241
259
  column: col('name', 'text', { codecRef: { codecId: 'pg/text@1' } }),
242
260
  }),
243
261
  this.dataTransform(endContract, 'backfill-user-name', {
244
- check: () => placeholder('backfill-user-name:check'),
245
- run: () => placeholder('backfill-user-name:run'),
262
+ backfillsColumn: { schema: 'public', table: 'user', column: 'name' },
263
+ check: () => placeholder('User.name:check'),
264
+ run: () => placeholder('User.name:run'),
246
265
  }),
247
266
  this.setNotNull({ schema: 'public', table: 'user', column: 'name' }),
248
267
  ];
@@ -254,19 +273,20 @@ MigrationCLI.run(import.meta.url, M);
254
273
 
255
274
  (`examples/prisma-8-demo/migrations/app/20260810T1108_add_post_engagement_counters/migration.ts` is a committed rendered package to compare against.)
256
275
 
257
- Replace both `placeholder(...)` calls with query-plan closures built from `endContract`. The `check` closure must return a **rowset query whose presence of any row signals "work remains"** — conventionally `<table>.select('id').where(<violation predicate>).limit(1)`. Scalar/aggregate shapes (`count(*)`, `bool_and(...)`) silently break the contract: the runner wraps `check` twice (`EXISTS(...)` for precheck, `NOT EXISTS(...)` for postcheck), and a query that always returns one row makes `EXISTS` always true and `NOT EXISTS` always false.
276
+ Replace both `placeholder(...)` calls with query-plan closures built with the SQL query builder. The `check` closure must return a **rowset query whose presence of any row signals "work remains"** — conventionally `<table>.select('id').where(<violation predicate>).limit(1)`. Scalar/aggregate shapes (`count(*)`, `bool_and(...)`) silently break the contract: the runner wraps `check` twice (`EXISTS(...)` for precheck, `NOT EXISTS(...)` for postcheck), and a query that always returns one row makes `EXISTS` always true and `NOT EXISTS` always false.
258
277
 
259
- Build the query builder against `endContract` so the storage hashes line up — using a different contract reference raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. The cheapest way to get a typed SQL builder over the end contract is the façade itself: `postgres<End>({ contractJson: endContract })` connects lazily, so constructing it inside `migration.ts` opens no connection; its `sql` is the builder and its `contract` is the validated contract to hand to `this.dataTransform`. The filled-in shape is the rendered scaffold above with only the two `placeholder(...)` arrows replaced (the operation list, including the `this.setNotNull({...})` the planner rendered after the transform, stays as rendered):
278
+ Build the query builder over the end contract, and pass the same client's `contract` to `this.dataTransform`; a plan built over a different contract raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. The cheapest way to get a typed SQL builder over the end contract is the database package itself: `postgres({ contract: contractFromJson<End>(endContract) })` connects lazily, so constructing it inside `migration.ts` opens no connection; its `sql` is the builder and its `contract` is the validated contract to hand to `this.dataTransform`. The filled-in shape is the rendered scaffold above with two changes: the two `placeholder(...)` arrows are replaced, and the first argument of `this.dataTransform` is the client's `contract` instead of the imported `endContract`. The planner renders `endContract`, the raw JSON, which is not a validated contract ([prisma/orm#30504](https://github.com/prisma/orm/issues/30504)). The operation list, including the `this.setNotNull({...})` the planner rendered after the transform, stays as rendered:
260
279
 
261
280
  ```typescript
262
- import { col, Migration, MigrationCLI } from '@internal/postgres/migration';
263
- import postgres from '@internal/postgres/runtime';
281
+ import { col, Migration, MigrationCLI } from '@prisma/orm-postgres/migration';
282
+ import postgres from '@prisma/orm-postgres/runtime';
283
+ import { contractFromJson } from '@prisma/orm-postgres/static';
264
284
  import type { Contract as End } from '../../snapshots/93f07d1b…c9e1e5a2/contract';
265
285
  import endContract from '../../snapshots/93f07d1b…c9e1e5a2/contract.json' with { type: 'json' };
266
286
  import type { Contract as Start } from '../../snapshots/f62a4154…d07dddc/contract';
267
287
  import startContract from '../../snapshots/f62a4154…d07dddc/contract.json' with { type: 'json' };
268
288
 
269
- const { sql: db, contract } = postgres<End>({ contractJson: endContract });
289
+ const { sql: db, contract } = postgres({ contract: contractFromJson<End>(endContract) });
270
290
 
271
291
  export default class M extends Migration<Start, End> {
272
292
  override readonly startContractJson = startContract;
@@ -280,6 +300,7 @@ export default class M extends Migration<Start, End> {
280
300
  column: col('name', 'text', { codecRef: { codecId: 'pg/text@1' } }),
281
301
  }),
282
302
  this.dataTransform(contract, 'backfill-user-name', {
303
+ backfillsColumn: { schema: 'public', table: 'user', column: 'name' },
283
304
  check: () => db.public.user.select('id').where((f, fns) => fns.eq(f.name, null)).limit(1),
284
305
  run: () => db.public.user.update({ name: '' }).where((f, fns) => fns.eq(f.name, null)),
285
306
  }),
@@ -291,12 +312,32 @@ export default class M extends Migration<Start, End> {
291
312
  MigrationCLI.run(import.meta.url, M);
292
313
  ```
293
314
 
315
+ `backfillsColumn` names the column the transform fills. Keep it: when `check` still finds rows after `run`, the apply fails, changes nothing, and counts the rows that still hold NULL, as on SQLite: `1 row of "user" still holds NULL in "name" after its backfill step, so it cannot become required.` The advice then says to make `run` fill every row in that `migration.ts` and re-run `db migrate`. Without `backfillsColumn` the same failure reports only that the postcheck failed.
316
+
317
+ `run` takes one closure, or an array of closures, each returning one query: `run: [() => db.public.user.update(…), () => db.public.post.update(…)]`. It does not take one closure that returns an array.
318
+
294
319
  Self-emit:
295
320
 
296
321
  ```bash
297
322
  node migrations/app/20260515T1200_add_user_name/migration.ts
298
323
  ```
299
324
 
325
+ ### SQLite
326
+
327
+ On SQLite, `--backfill User.name` writes a `dataTransform` with one slot, `User.name:run`, and no `check`; the table rebuild after it makes the column required, and fails, changing nothing, if a row still has no value. `run` is a closure that returns the SQL text of one statement:
328
+
329
+ ```typescript
330
+ dataTransform({
331
+ id: 'data_migration.backfill-User-name',
332
+ label: 'Backfill NULLs in "User"."name" before NOT NULL tightening',
333
+ table: 'User',
334
+ description: 'Backfill NULL name values in User',
335
+ run: () => `UPDATE "User" SET name = 'user ' || id WHERE name IS NULL`,
336
+ }),
337
+ ```
338
+
339
+ Write the statement so it fills every row the field has no value in, then self-emit with `node <package dir>/migration.ts` as on Postgres.
340
+
300
341
  Self-emit regenerates `ops.json` and recomputes `migrationHash` in `migration.json`. The next `db migrate` will see a consistent package.
301
342
 
302
343
  ### Mongo
@@ -344,7 +385,48 @@ export default M;
344
385
  MigrationCLI.run(import.meta.url, M);
345
386
  ```
346
387
 
347
- Self-emit the same way: `node migrations/app/<dir>/migration.ts`.
388
+ Self-emit the same way: `node <package dir>/migration.ts`.
389
+
390
+ ## Data changes go in a data transform
391
+
392
+ **The rule.** A statement that inserts, updates or deletes rows, or selects rows to decide what to write, goes in a data transform (`dataTransform`), never in a `rawSql` step. `rawSql` is for DDL that no operation factory expresses. DDL includes statements that convert stored values as part of a schema change, such as `ALTER COLUMN … TYPE … USING` and SQLite's table recreation: use the operation factory (`this.alterColumnType`, `this.recreateTable`). A `rawSql` step you write carries a precheck and a postcheck that test the live schema, and the class *Operation classes* under *Key Concepts* describes.
393
+
394
+ **Why.** Migrations form a graph (`references/migration-model.md`), and a migration is an edge. `db migrate` can run a migration on any database whose marker is at its `from` hash, however that database got there. Those databases share a schema but not their rows: on one the work is already done, on another it was never needed. A data transform stays correct on all of them for two reasons:
395
+
396
+ - **`check` is the guard.** The runner skips the transform when `check` finds no rows (the work is done or was never needed), runs `run` otherwise, and fails the migration if `check` still finds rows afterwards. `check` is optional in the type, but a transform without it runs `run` on every database and can never refuse, so always write it.
397
+ - **On Postgres, the queries are checked against a contract.** Self-emit checks each query plan against the contract passed to `this.dataTransform` and refuses a mismatch with `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`.
398
+
399
+ A `rawSql` step that changes rows has neither: no contract checks its SQL, and its checks are whatever its author wrote.
400
+
401
+ **What each target checks.**
402
+
403
+ - **Postgres.** `this.dataTransform(contract, name, { check, run })` takes query plans built with the SQL query builder; in `migration.ts`, use the `sql` and `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns. Only builder queries count. A query from the client's raw lane (`db.raw.sql`) or one containing `fns.raw` passes the contract check, because the check compares only the plan's storage hash, but nothing checks its SQL against the contract. Treat it as raw SQL.
404
+ - **SQLite.** `dataTransform({ id, label, table, description, run })`, imported on the rendered `@prisma/orm-sqlite/migration` line, takes `run: () => string`, a SQL string. It has no `check`, and nothing checks the SQL against a contract. It is still the place for a data change on SQLite. Write `run` so that it changes nothing on a database where the work is done, for example `UPDATE … WHERE "col" IS NULL`.
405
+ - **Mongo.** `dataTransform(name, { check, run })` takes Mongo commands, such as the raw command classes in the example above. Nothing checks them against a contract. `check` works as on Postgres.
406
+
407
+ ### When the SQL query builder cannot express the transform (Postgres)
408
+
409
+ Stop, and tell the user which part of the transform the builder cannot express. If the gap is one of these open issues, name the issue instead of filing a new one:
410
+
411
+ - An insert whose rows come from a select ([prisma/orm#30488](https://github.com/prisma/orm/issues/30488)).
412
+ - An update that sets a column from a subquery or a joined table ([prisma/orm#30489](https://github.com/prisma/orm/issues/30489)). Setting a column from another column of the same row works: `db.public.ask.update((row) => ({ stateEnteredAt: row.createdAt }))`.
413
+
414
+ For any other gap, offer to report it through `references/feedback.md`. Then let the user decide how to proceed. Never choose on your own to write the change as raw SQL (`rawSql`, `db.raw.sql` or `fns.raw`) or as a script that runs outside the migration. If the user knowingly chooses another route, record the choice and the reason where the next person will see it: a comment beside the step in `migration.ts`, and the pull request description.
415
+
416
+ ### How a transform refuses bad data
417
+
418
+ Write `check` to find the rows the transform must fix. If `run` leaves any of them behind, for example rows whose values have no valid mapping, the postcheck fails and the migration stops with `MIGRATION.POSTCHECK_FAILED`. On Postgres `meta.failedCheck.operationId` names the transform. On Mongo `meta.operationId` and `meta.name` do. On Postgres the whole run rolls back. On Mongo nothing is undone: the documents `run` already changed stay changed, and operations that ran earlier stay applied; only the marker does not advance. So on Mongo, write `run` so it is safe to run again, for example by filtering on the documents that still need the change. A SQLite transform has no `check`, so it cannot refuse this way. Do not add a raw step that raises an error. If the user wants the offending rows named, run a read-only query that selects them before migrating.
419
+
420
+ ## Type changes and new required fields
421
+
422
+ Postgres and SQLite first; MongoDB below. `migration plan` cannot see rows, so these rules are about what you state, not what the table holds.
423
+
424
+ - **A type change that can lose values is a question.** Answer it with `--convert User.age` (the plan has a slot for the conversion: `using: placeholder('User.age:convert')` in `this.alterColumnType(...)` on Postgres, the column's copy expression in `this.recreateTable(...)` on SQLite; write SQL over the column, such as `'"age"::integer'`, self-emit, `db migrate`) or `--delete User.age` (the database's own cast runs; it is listed as `accept lossy type change of field "User.age"`). The cast may cut or round values: on Postgres a longer text is cut to a shorter `VarChar` and a number rounded to fewer digits. A value the cast cannot convert fails the apply, changes nothing, and the error names `--convert`. On SQLite the rebuild checks after its copy that every value took the new type: each column listed in `retypedColumns` is checked, as the conversion when it has a copy expression in `copyExpressions` and as SQLite's own cast when it has none, and a column with a copy expression that is not listed is checked as a conversion too. A hand-written rebuild that converts needs only its copy expression. A widening such as `int4` to `int8` asks nothing.
425
+ - **A new required field** gets a temporary value in the existing rows (`''`, `0`, `false`, …) with no question and no placeholder; the output names the field and the value. On SQLite the rebuild writes it in `temporaryValues: { name: sql`''` }`, apart from the conversions in `copyExpressions`. `--backfill User.name` writes a data transform to fill instead: add nullable, fill (`check` and `run` slots on Postgres, `run` on SQLite), then make it required. A new unique, primary-key or foreign-key field, or one whose values come from a value set, gets no temporary value: on a table with rows, use `--backfill`.
426
+ - **An optional field made required** is tightened directly. If rows hold NULL, the apply fails and counts them (`3 rows of "Item" hold NULL in "note", so it cannot become required.`); set the values and re-run, or plan with `--backfill`.
427
+ - **On MongoDB** the same questions are asked about the documents. A validator change (`collMod(..., { ..., checkDocuments: true })`) checks the documents as its own precheck, after the plan's rewrites, and stops while one does not fit; operations that ran before it stay applied, and a re-run skips them. To apply a validator over documents that do not fit, set `checkDocuments: false` on its `collMod` in `migration.ts`. `--delete User.age` casts with `$convert` (`castField`), only where the result keeps what the values mean: `String` to `Boolean` or `DateTime` to `Int` offer `--convert` only; a cast that keeps every value, such as `Int` to `BigInt`, asks nothing. `--convert User.age` and `--backfill User.plan` write `dataTransform('User.age', { check, run })` with the filter written and the update as `placeholder('User.age:update')`, which you replace with an update document (`{ $set: { … } }`) or an aggregation pipeline (`[{ $set: { age: { $toInt: '$age' } } }]`); the `run` uses `rawUpdateMany(..., { bypassDocumentValidation: true })`, and a hand-written one must skip validation too. A new required field gets a temporary value (`fillField`), unless it has a unique index or its type has none, such as a date, or it is a variant's discriminator, since no temporary value names a variant. A discriminator renamed without `--rename` is refused, and the refusal gives the `--rename` to pass; a model's first discriminator is left to the document check. On a collection with documents, such a field stops the apply: a unique one at its index build, where the documents that lack it all hold `null`, and any other at the validator change's document check. Both errors name `--backfill`, so use it. A required field of a variant new to the collection, such as `Bug.severity` when `Task` gains its first discriminator, has no documents to backfill yet: set it in the update you write for `--backfill Task.type`, or keep it optional until a later change. A field that gains an enum or changes type inside a value object is not a statement: the plan warns, and you add a `dataTransform` before the validator change.
428
+ - **Adopting a Prisma 6 MongoDB database.** A Prisma 6 database has no validator, and the first Prisma 8 plan adds one, which checks the documents first. If documents do not fit, the apply stops and names what the change touches, one `_id`, and the `mongosh` query that finds the rest. The error says why the document it shows does not fit, such as a field the new validator does not name. Fix those documents and run the command again; a plain update works, since the collection has no validator yet. Or, under `db migrate`, apply the validator over them: set `checkDocuments: false` on that `collMod` in `migration.ts`, run the file with `node`, and run `db migrate` again; they then fail their next update until they fit.
429
+ - **Following failure advice under `db migrate`:** the migration is already written, so the error says to copy any code you wrote in its `migration.ts`, delete its directory, and run the printed `migration plan --from <hash> --name <name> …` command, which keeps the migration's name, together with the other statements you planned it with. Paths in the advice are relative to the directory the command ran from, and the commands it prints repeat the `--config` it was given, so each runs as printed from there. A printed command that connects to a database carries `--db <url>` when the run was given `--db`, or when `db.connection` in `prisma.config.ts` has no value (for example, its environment variable is not set): replace `<url>` with the database's URL.
348
430
 
349
431
  ## Workflow — Author a migration by hand
350
432
 
@@ -354,28 +436,29 @@ The concept: the same `Migration` class shape lets you author operations directl
354
436
  pnpm prisma migration new --name <snake_slug>
355
437
  ```
356
438
 
357
- On Postgres the operations are **methods on the `Migration` base class**, each taking one options object (`this.addColumn({ schema, table, column })`); only helpers such as `col(...)` and `rawSql(...)` are imported, on the rendered `@internal/postgres/migration` line. On Mongo the operations are **free factories** imported from `@prisma/orm-mongo/target/migration`. The authoritative list for either target is the base class / module's declaration file in your `node_modules`.
439
+ On Postgres the operations are **methods on the `Migration` base class**, each taking one options object (`this.addColumn({ schema, table, column })`); only helpers such as `col(...)` and `rawSql(...)` are imported, on the rendered `@prisma/orm-postgres/migration` line. On Mongo the operations are **free factories** imported from `@prisma/orm-mongo/target/migration`. The authoritative list for either target is the base class / module's declaration file in your `node_modules`.
358
440
 
359
441
  **Postgres** operations (representative set, all `this.<name>({...})`):
360
442
 
361
- - Tables: `createTable`, `dropTable`.
362
- - Columns: `addColumn` (`column: col(name, nativeType, { codecRef })`), `dropColumn`, `alterColumnType`, `setNotNull`, `dropNotNull`, `setDefault`, `dropDefault`.
363
- - Constraints: `addPrimaryKey`, `addForeignKey`, `addUnique`, `addCheckConstraint`, `renameCheckConstraint`, `dropCheckConstraint`, `dropConstraint`.
443
+ - Tables: `createTable`, `renameTable`, `dropTable`. `renameTable` reads the migration's start and end contracts and returns the table rename plus a rename of every constraint and index named after the old table, so spread it: `...this.renameTable({ table: 'userProfile', to: 'UserProfile' })`.
444
+ - Columns: `addColumn` (`column: col(name, nativeType, { codecRef })`), `renameColumn` (also renames the constraints and indexes named after the column, so spread it: `...this.renameColumn({ table: 'User', column: 'email', to: 'emailAddress' })`), `dropColumn`, `alterColumnType({ schema, table, column, type, using? })` (`type` is the new type as a migration writes it, such as `int8` or `varchar(20)`; `using` is a SQL expression over the column that converts each value, and without it the database casts the column; the class is `'data'` with `using` and `'destructive'` without it; pass `operationClass: 'widening'` only when every value of the old type converts to the new type unchanged, such as `int4` to `int8`; on a column that owns a sequence it also changes the sequence to the new width, and refuses to narrow past the sequence's last value; a column whose `nextval` default uses a sequence it does not own gets only the type change; with `using`, it refuses with `MIGRATION.ALTER_COLUMN_TYPE_USING_WITHOUT_TYPE_CHANGE` when the start contract already gives the column that type, since the runner would skip the conversion: write a `this.dataTransform` instead), `setNotNull`, `dropNotNull`, `setDefault` (`column: col(name, nativeType, { default: lit(value) or fn(…), codecRef })`, where `fn` takes a SQL expression; `fn`, `checkExpression` and the methods that take a SQL fragment accept a ``sql`...` `` value, which generated files write, or a string; a `sql` value's text is canonicalized like a contract's, a string is kept exactly as written, so do not wrap a committed string in `sql`; `fn('autoincrement()')` on a smallint, integer or bigint column reuses any sequence the column already owns (found with `pg_get_serial_sequence`), creates `{table}_{column}_seq` only when it owns none, attaches it, and starts it past the column's largest value; `setDefault` takes no `operationClass`: the class comes from the migration's start contract after earlier renames, `widening` when the column had a default and `additive` otherwise; a literal or function default has no postcheck, so it always runs and the final schema check compares the value), `dropDefault`.
445
+ - Constraints: `addPrimaryKey`, `addForeignKey`, `addUnique`, `addCheckConstraint`, `renameConstraint` (`kind`: `primaryKey`, `unique`, `foreignKey` or `checkConstraint`), `renameCheckConstraint`, `dropCheckConstraint`, `dropConstraint`.
364
446
  - Indexes: `createIndex`, `renameIndex`, `dropIndex`.
365
447
  - Enums: `createNativeEnumType`, `addNativeEnumValue`, `dropNativeEnumType`.
366
448
  - Row-level security: `enableRowLevelSecurity`, `disableRowLevelSecurity`, `createRlsPolicy`, `renameRlsPolicy`, `dropRlsPolicy`.
367
- - Dependencies: `createSchema`, `installExtension`.
368
- - Free helpers on the import line: `col`, `primaryKey`, `unique`, `foreignKey`, `checkExpression`, `lit`, `fn` (column and constraint descriptors), `createExtension`, and the raw escape hatch `rawSql({ id, label, operationClass, target, precheck, execute, postcheck, ... })`.
369
- - Data transforms: `this.dataTransform(endContract, name, { check, run })`.
449
+ - Dependencies: `createSchema`, `createExtension`, `dropExtension`, `setExtensionSchema`, `installExtension`.
450
+ - Free helpers on the import line: `col`, `primaryKey`, `unique`, `foreignKey`, `checkExpression`, `lit`, `fn` (column and constraint descriptors), and `rawSql({ id, label, operationClass, target, precheck, execute, postcheck, ... })` for DDL that no operation factory expresses. Never use `rawSql` for inserts, updates or deletes; see *Data changes go in a data transform*. The runner runs an operation's postchecks first and skips the operation when they all hold, so a `rawSql` postcheck must hold only when the operation's full effect is in place. If you cannot check that, leave `postcheck` empty: the operation then always runs.
451
+ - Data transforms: `this.dataTransform(contract, name, { check, run })`, with the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns.
370
452
 
371
453
  **Mongo** factories (from `@prisma/orm-mongo/target/migration`):
372
454
 
373
- - Collections: `createCollection`, `dropCollection`, `validatedCollection`, `setValidation`.
455
+ - Collections: `createCollection`, `dropCollection`, `renameCollection(from, to)` (keeps the documents, indexes and validator), `validatedCollection`, `setValidation`.
374
456
  - Indexes: `createIndex`, `dropIndex`.
457
+ - Document rewrites: `renameField(collection, from, to, { filter? })` and `unsetField(collection, field, { filter? })`, each one `updateMany` that skips validation; `filter` limits them to one variant's documents, such as `{ filter: { type: 'bug' } }`. Inside a field's value: `renameStoredKey`, `removeStoredKey` and `fillStoredKey`, each taking `{ collection, field, path, filter? }` with `path` a JSONPath such as `'$[*].street'`. Stored values: `replaceStoredValue` and `removeStoredValue`, taking `{ collection, field, path?, … }`. `deleteDocuments({ collection, filter })` deletes documents.
375
458
  - Collection options: `collMod`.
376
459
  - Data transforms: `dataTransform(name, { check, run })` (free factory; `check`/`run` use Mongo query-plan shapes).
377
460
 
378
- Self-emit (`node migrations/app/<dir>/migration.ts`) after each edit.
461
+ Self-emit (`node <package dir>/migration.ts`) after each edit.
379
462
 
380
463
  ## Workflow — Inspect the live schema
381
464
 
@@ -408,7 +491,72 @@ Modes:
408
491
  pnpm prisma db verify --db $DATABASE_URL
409
492
  ```
410
493
 
411
- `db verify` exits `0` when everything matches, `4` when it ran and found something, and `2` only when it could not run. Findings ride the completed envelope as `error` diagnostics: `CONTRACT.MARKER_MISMATCH`, `CONTRACT.MARKER_MISSING`, `CONTRACT.TARGET_MISMATCH`, `CONTRACT.SCHEMA_VERIFICATION_FAILED` (with `meta.issues` naming the drifted paths).
494
+ `db verify` exits `0` when everything matches, `4` when it ran and found something, and `2` only when it could not run. Findings ride the completed envelope as `error` diagnostics: `CONTRACT.MARKER_MISMATCH`, `CONTRACT.MARKER_MISSING`, `CONTRACT.TARGET_MISMATCH`, `CONTRACT.SCHEMA_VERIFICATION_FAILED` (with `meta.schemaIssues` listing the schema diff issues).
495
+
496
+ ## Policies: what a database says about how it may change
497
+
498
+ Every database records two policies, and every command obeys them. On Postgres they are in `prisma.config`; on the other targets they are in the application space's marker. Read them from the error that refuses you, or with `prisma migration status --to <ref> --db <url>`, which reports where the ref's declared policies differ from the database's.
499
+
500
+ **Change policy.** The strategies the database may be changed by:
501
+
502
+ | Strategy | What it means | Commands |
503
+ |---|---|---|
504
+ | `migrate` | Walk the migration graph, running recorded migrations | `db migrate`, a Composer deploy |
505
+ | `reconcile` | Plan and apply the difference to a contract, then sign | `db update`, `db sign` |
506
+
507
+ A database that records nothing permits both. Production records `["migrate"]`, so `db update` and `db sign` refuse it with `MIGRATION.CHANGE_POLICY_FORBIDS`. The off-graph error (`MIGRATION.MARKER_MISMATCH`) reads the policy and gives only the recovery it permits.
508
+
509
+ **Data protection policy.** `dataLoss` and `accessWidening`, each `data-loss-forbidden` / `data-loss-with-consent` / `data-loss-permitted` (and the `access-widening-` forms). `with-consent` is the default and is today's behaviour: `db update` asks, and a migration carries the consent given when it was planned. Every command enforces them before it runs anything:
510
+
511
+ | Level | `db update` | `db migrate`, a Composer deploy | `migration plan --to <ref>` |
512
+ |---|---|---|---|
513
+ | `forbidden` | Refuses the change, even with `--delete` or `--allow` | Refuses a run containing a migration that does it | Refuses to write the migration, when the ref declares the level |
514
+ | `with-consent` | Asks (`--delete`, `--rename`, `--allow`) | Runs | Asks about data loss |
515
+ | `permitted` | Does not ask; an unanswered loss is a delete, and `--rename` still applies; a `--delete` or `--allow` given anyway is accepted | Runs | Asks about data loss |
516
+
517
+ A refusal is `MIGRATION.DATA_PROTECTION_FORBIDS`; `meta.operations` lists each refused operation, and for `db migrate` the migration that contains it. Under `forbidden` the operation cannot run on that database at all, and `--delete` or `--allow` changes nothing. If the subject was only renamed, say so with `--rename`; if a field's type changed, plan it with `migration plan --convert`; otherwise keep the model or field in the contract. When `db migrate` refused a recorded migration, first find out whether another database has applied it. If one has, such as staging under a looser policy, keep the migration as it is: it is the record of what that database ran. Tell the user that the refusing database cannot run it; do not suggest changing the policy that refused it. If none has, recover like this:
518
+
519
+ 1. Decide how the contract keeps what the migration would lose: `--rename` if a model or field was only renamed, `--convert` if a field's type changed, otherwise put back in the contract what the migration removes (a model, field, enum value or access rule) and run `prisma contract emit`, because `migration plan` reads the emitted contract. Never only take the operation out of the migration: the database would keep what the contract no longer describes, so the two disagree, and the next `db update` plans the same change and is refused.
520
+ 2. Find the refused migration and every later migration no database has applied. `prisma migration list` shows the chain; it does not show what other databases have applied, so ask the user when you cannot tell. Save any operations someone wrote by hand in any of them, because planning again does not carry them over.
521
+ 3. Note the `from` hash in the first one's `migration.json`, then delete all of them: left on disk, they are still the ones `db migrate` runs.
522
+ 4. Plan once from that hash: `prisma migration plan --from <hash>`, with the `--rename` or `--convert` from step 1. `--from` can be left out when the `db` ref already names that hash.
523
+ 5. If you put something back in the contract, its hash changed, so a ref that named the end of a deleted migration (such as `production`) no longer names a contract in the graph. Point it at the new migration: `prisma migration ref set <ref> <new migration directory>`. After `--rename` or `--convert` the hash is unchanged and the ref still works.
524
+ 6. If you saved operations, put them into the new migration's `migration.ts` and run it again to re-emit (*Self-emit* above). If step 4 found nothing to plan, there is no new migration to put them into: tell the user, because a saved data operation then needs a migration of its own (*Author a migration by hand*). Then run `db migrate`.
525
+
526
+ Copying the data elsewhere first does not help: the drop is still a drop. Whether the database's own recorded policy or a ref's declared policy refused it (`migration plan --to <ref>`, or a deploy given `--permit-policy-change`), fix the refused work or tell the user. Never change a database's or a ref's policies to get past a refusal, by hand or with `migration ref policy`, and never suggest that anyone, the owner included, does. When `db migrate` or `db update` refuses an operation in an extension's contract space (`migrations/<extension-space-id>/`), the migration belongs to that extension's package: do not edit or delete it, and planning in the application does not replace it. Do not go back to an earlier version of the extension either: a database that already applied the later migration could then no longer be migrated. Ask the extension's author for a version without that operation, and tell the user.
527
+
528
+ A loss is an operation whose class is `destructive`. An access change is disabling row-level security or dropping a row-level-security policy (Postgres only); `access-widening-forbidden` refuses both, though a dropped policy may narrow access as well as widen it. In a recorded migration these are recognised from the operation itself, so an access change written as raw SQL is not seen: `access-widening-forbidden` does not stop a hand-written `DISABLE ROW LEVEL SECURITY`. Adding a policy, or changing a policy's condition, is not counted as an access change by any command.
529
+
530
+ **Declaring policies.** A ref declares the policies its database should have, in the `policies` field of its file. Every key is optional, and a key you leave out declares nothing, which is not the same as declaring the default:
531
+
532
+ ```json
533
+ // migrations/app/refs/production.json
534
+ {
535
+ "formatVersion": 1,
536
+ "hash": "4b1c…e09a",
537
+ "invariants": [],
538
+ "policies": {
539
+ "change": ["migrate"],
540
+ "dataProtection": { "dataLoss": "data-loss-with-consent", "accessWidening": "access-widening-forbidden" }
541
+ }
542
+ }
543
+ ```
544
+
545
+ Write the field by hand, or with the `migration ref policy` commands, which change only the ref file and never connect to a database:
546
+
547
+ | Command | What it does |
548
+ |---|---|
549
+ | `prisma migration ref policy show <ref>` | Prints each setting the ref declares, or "not declared". It is what the ref declares, not what a database has; `migration status --to <ref> --db <url>` compares the two. |
550
+ | `prisma migration ref policy set <ref> --change <strategy> --data-loss <level> --access-widening <level>` | Writes the settings named and leaves the rest. `--change` is repeatable and replaces the declared list. A level is `forbidden`, `with-consent` or `permitted`. An invalid value is refused before the file is touched. |
551
+ | `prisma migration ref policy delete <ref> <setting>...` | Removes settings (`change`, `dataProtection.dataLoss`, `dataProtection.accessWidening`, or `data-loss`, `access-widening`), so the ref declares nothing about them. |
552
+
553
+ `set` and `delete` print each changed setting before and after, labelled `tightens`, `loosens` or `unchanged`, and `--json` returns `{ ok, ref, policies, changes }`. A ref's policies record what the team decided about how that database may change, and a change to them is reviewed like code.
554
+
555
+ No other command changes a ref's policies. Commands that rewrite a ref (`migration ref set`, `db update`, `db sign`, `db migrate`, and the `migration ref policy` commands) keep the `hash`, `invariants` and `policies` they do not change, and write `formatVersion` themselves. A ref file with any other field is refused with `MIGRATION.INVALID_REF_FILE`, and the file is left as it was: remove the field by hand.
556
+
557
+ **Applying a declared policy.** `db migrate --to <ref>` and `db update --to <ref>` compare the ref's declarations with the database before running anything. If they differ, the command fails with `MIGRATION.POLICY_MISMATCH` and nothing runs. The database's policy changes only when the deploy is told it may: `prisma db migrate --to production --permit-policy-change --db <url>`. The run is checked against the ref's policies, runs, and records them in the database (on Postgres in `prisma.config`, elsewhere in the marker) when it succeeds, so a failed run leaves the old policy. With nothing pending, the run writes only the policies. A pipeline that should apply reviewed policy changes passes the flag on every deploy; a cautious team leaves it out and applies policy changes by hand. The flag needs `--to <ref>`: with a hash, `@db`, `@empty` or no `--to`, the command fails with `CLI.INVALID_ARGUMENTS` before it connects. A ref that declares no policies is accepted and changes nothing, so a pipeline can pass the flag on every deploy.
558
+
559
+ The flag is consent, like `--delete`. It is for the person who owns the database and reviewed the ref change. Never add it to make your own deploy pass, and never change a database's or a ref's policies, by hand or with `migration ref policy set` or `delete`, to get a deploy, a plan or `db update` past a refusal or a mismatch: the policy is there to stop exactly that.
412
560
 
413
561
  ## Workflow — Re-sign the marker
414
562
 
@@ -418,11 +566,49 @@ The concept: `db sign` rewrites the marker to the current contract hash and move
418
566
  pnpm prisma db sign --db $DATABASE_URL
419
567
  ```
420
568
 
569
+ ## Workflow — A database whose marker is not in the migration graph
570
+
571
+ **The symptom.** `db migrate` or a deploy fails with `MIGRATION.MARKER_MISMATCH`: the database's marker names a contract that no migration in `migrations/` starts or ends at. (Composer releases older than this skill print it as `MIGRATION_PATH_NOT_FOUND`, "no authored path from the database's current schema".)
572
+
573
+ **The usual cause.** The database applied a migration that was later planned again or deleted. The common case is a branch deployed to a shared environment, then rebased: each new plan of its migration has a new target hash, and the version the database applied is gone. The error's `why` names the last contract in the graph the database applied (`meta.lastGraphHash`) and the applied migrations that are no longer on disk (`meta.missingMigrations`).
574
+
575
+ **Never reset or drop the database.** It can always be moved. The error reads the database's change policy and gives the recovery it permits: the `db update` commands when the policy includes `reconcile`, otherwise the migration route. A database with no recorded policy permits both, and the error then gives the `db update` route; if you know the database changes only through migrations, take the migration route instead and declare that in its ref.
576
+
577
+ When the error names an extension's contract space (`meta.spaceId` is not `app`), that space's migrations come with the extension package: install a version of the extension whose migrations include the database's contract (`prisma migration list --space <space>` lists them), or ask its maintainers. The recoveries below are for the application space.
578
+
579
+ ### When the database's history does not need to be kept (local, development, staging, preview)
580
+
581
+ Reconcile it to the target with `db update`:
582
+
583
+ 1. `prisma db update --db $DATABASE_URL --to <target> --dry-run`, and read every operation, above all every drop.
584
+ 2. `db update` does not run data transforms or seed steps. When the error has no `meta.lastGraphHash`, the ledger cannot say which migrations it would skip: stop and ask a person. Otherwise read the data transforms of the migrations on disk between `meta.lastGraphHash` and the target (`prisma migration list`, then each one's `migration.ts`). The migrations in `meta.missingMigrations` already ran on this database, so never repeat them; read them, in ledger order (`prisma migration log`) from the git commits that held them, only to learn what the database already holds, since a migration on disk may be a new plan of one of them. If a missing migration's source cannot be recovered, stop and ask a person. For each on-disk transform whose data matters and whose work the database does not already hold:
585
+ - if it moves data into a new column or table, create that column or table by hand and copy the data with SQL, the way the transform would;
586
+ - if it inserts rows the application needs, insert them by hand.
587
+
588
+ Run the dry run again to confirm the drops that remain lose nothing you need.
589
+ 3. `prisma db update --db $DATABASE_URL --to <target>`, answering the data-loss questions with `--delete` or `--rename` (see *Answer the data-loss questions*).
590
+ 4. Deploy again. The deploy finds the database at its target.
591
+
592
+ ### When the database changes only through migrations (production)
593
+
594
+ Author migrations that bring it back onto the graph, and deploy them. The marker's contract is `<marker hash>`; the last graph contract is `meta.lastGraphHash`. When the error has no `lastGraphHash`, the ledger shows no contract the database applied that is still in the graph, or could not be read: check with `prisma migration log`, and if no applied contract is in the graph, stop and ask a person.
595
+
596
+ `migration plan --to` accepts only contracts already in the graph, so the database's contract goes through the contract source:
597
+
598
+ 1. Commit or copy aside any uncommitted edits to the contract source; step 4 restores it from `HEAD`. Then put the contract the database is at into the contract source. Prefer the contract source as it was when the deleted migration was planned: find the commit with `git log --all --oneline -- migrations/snapshots/<marker hash>` and check out the contract source file from it. If git no longer has it, infer it from the database into a separate file, `prisma contract infer --db $DATABASE_URL --output ./inferred.prisma` (without `--output` it overwrites the contract source), then copy that file over the contract source.
599
+ 2. `prisma contract emit`, and check that the emitted storage hash is `<marker hash>`. If it is not, stop and ask a person.
600
+ 3. Plan a migration from the last graph contract to the database's contract: `prisma migration plan --from <lastGraphHash> --name rejoin_<database>`. Nothing will run it against this database; it only puts the database's contract in the graph. A fresh database could still run it, so copy the data transforms of every migration in `meta.missingMigrations` into it, in ledger order (`prisma migration log`), from the git commits that held them, and review them.
601
+ 4. Restore the contract source (`git checkout HEAD -- <contract source>`; without `HEAD` git restores the version step 1 staged), run `prisma contract emit`, then plan from the database's contract to the target: `prisma migration plan --from <marker hash> --name <slug>`. A plan that loses data needs `--delete` or `--rename` (see *Answer the data-loss questions*). Review it like any migration, and add data transforms for any data the deleted migration's replacement would have moved.
602
+ 5. Check how a fresh database reaches the target: `prisma migration status --from @empty --to <target>` lists the migrations it would run. Path finding takes the shortest route, so if these two migrations make a shorter route from the last graph contract to the target than the main line, a new database would take it. When they do, ask a person how to proceed.
603
+ 6. Commit both migrations and deploy.
604
+
605
+ Do not `db sign` the database to a contract you inferred: that rewrites its marker without a migration, and a database whose change policy permits only migrations refuses it.
606
+
421
607
  ## Workflow — Recover from drift
422
608
 
423
609
  The concept: drift means `db verify` reports the live DB schema doesn't match what the marker says it should be. Two valid moves, picked by which side is correct:
424
610
 
425
- - **The contract is right; the DB is wrong** → run a migration. Either `db update` (quick path, dev DB only) or `migration plan` + `db migrate` (everywhere else).
611
+ - **The contract is right; the DB is wrong** → run a migration. Either `db update`, on a database whose migration history does not need to be kept (a local, development, staging or preview database), or `migration plan` + `db migrate`, which every database accepts and a database that changes only through migrations, such as production requires.
426
612
  - **The DB is right; the contract or marker is wrong** → edit the contract to match the DB (see `references/contract.md`), emit, then `db sign` to refresh the marker. The sign also moves the `db` ref to the signed hash; when the migration graph is non-empty and that hash is not a graph node, the next default `migration plan` refuses with `MIGRATION.HASH_NOT_IN_GRAPH` (see *The forgot-the-flag pitfall* above for the recovery).
427
613
 
428
614
  The diagnostic that reveals which side is right:
@@ -443,17 +629,19 @@ Failures that *can* leak partial state: Mongo DDL that partially applied before
443
629
  Diagnose:
444
630
 
445
631
  ```bash
446
- pnpm prisma db verify --db $DATABASE_URL --json
447
- pnpm prisma db schema --db $DATABASE_URL --json
632
+ pnpm prisma db verify --json
633
+ pnpm prisma db schema --json
448
634
  ```
449
635
 
450
636
  Fix and re-run `db migrate`:
451
637
 
452
638
  ```bash
453
- node migrations/app/<dir>/migration.ts
454
- pnpm prisma db migrate --db $DATABASE_URL
639
+ node <package dir>/migration.ts
640
+ pnpm prisma db migrate
455
641
  ```
456
642
 
643
+ Every `prisma` command here addresses the database `prisma.config.ts` names, so the diagnosis and the re-run look at the same database; outside CI, the re-run also moves the `db` ref. For another database, add the same `--db <url>` to the diagnose commands and to `db migrate`, which then leaves the `db` ref alone.
644
+
457
645
  If the failure was an out-of-band side-effect that left external systems half-changed, repair those by hand before re-applying.
458
646
 
459
647
  ## Workflow — Recover from `MIGRATION.HASH_MISMATCH`
@@ -461,49 +649,75 @@ If the failure was an out-of-band side-effect that left external systems half-ch
461
649
  The concept: `migrationHash` is content-addressed. A mismatch means `migration.json`'s stored hash disagrees with the hash recomputed from `ops.json` (and metadata). The cause is almost always: someone edited `migration.ts` and forgot to self-emit. The remediation is to self-emit the offending package.
462
650
 
463
651
  ```bash
464
- node migrations/app/<dir>/migration.ts
465
- pnpm prisma db migrate --db $DATABASE_URL
652
+ node <package dir>/migration.ts
653
+ pnpm prisma db migrate
466
654
  ```
467
655
 
468
- If self-emit itself fails (e.g. the contract has moved on and the operations no longer make sense against the migration's end contract), the package is stale. Either restore it from version control or delete it and re-plan with `migration plan`.
469
-
470
- ## Workflow — Resolve a destructive-operation prompt (`db update` only)
656
+ This applies to the database `prisma.config.ts` names and, outside CI, moves the `db` ref with it. For another database, add `--db <url>`.
471
657
 
472
- The concept: when `db update` would drop columns or tables, it stops and asks before applying. The prompt is `db update`-specific — `db migrate` does *not* prompt and runs whatever the migration package contains, so review the plan or call `migration show` before `db migrate`.
473
-
474
- When `db update` reports destructive operations interactively, the warning lists them. The prompt is:
658
+ If self-emit itself fails (e.g. the contract has moved on and the operations no longer make sense against the migration's end contract), the package is stale. Either restore it from version control or delete it and re-plan with `migration plan`.
475
659
 
476
- > Apply destructive changes? This cannot be undone.
660
+ ## Workflow — Answer the data-loss questions (`migration plan` and `db update`)
661
+
662
+ The concept: the planner cannot tell whether a dropped model or field was meant to go, or was renamed. So before `migration plan` writes a package, or `db update` applies, the command asks one question per model, field or storage name an operation would lose data from. `db update` also asks one per model whose rows an operation would open up, such as dropping a row-level-security policy. Each question is answered by a statement:
663
+
664
+ - `--delete <subject>` lets the data go: `--delete Legacy`, `--delete User.nickname`. A subject no model stores is named by its storage name (`public.audit_log` on Postgres, `audit_log` on SQLite, `profiles.nickname` for a MongoDB field when `db update` has no snapshot of the origin contract) and can only be deleted. On MongoDB, removing a field from a model is asked about, and `--delete` removes it from every document that holds it.
665
+ - `--rename <subject>:<new name>` keeps it under a new name: `--rename Profile:User`, or for a field `--rename User.nickname:User.handle` (the new name keeps its model). A field of a renamed model is named through the new name (`--delete User.nickname` after `--rename Profile:User`).
666
+ - On Postgres, namespaces are subjects too. `--rename public.Invoice:billing.Invoice` moves a model to another namespace, creating the schema if needed. `--rename billing:finance` renames a namespace; namespace renames run first, whatever order the flags are in. A namespace removed from the contract is asked about one model at a time, and `--delete billing` answers all of them; a table in it that no contract declares is its own question, `--delete billing.audit_log`. `public` and a schema another contract space declares cannot be renamed. When a name is both a namespace and a model, name the model with its namespace (`app.billing:app.finance`).
667
+ - On Postgres and SQLite, enum values are subjects too. A member removed from an enum is asked about as `Status.ARCHIVED`. `--rename Status.ARCHIVED:Status.RETIRED` replaces the stored value in every row and list that holds it; `--delete Status.ARCHIVED` sets it to NULL in optional columns and takes it out of lists. While rows of a required column hold it, the apply fails with `MIGRATION.PRECHECK_FAILED` and changes nothing; follow its next actions (rename to a new member, or keep the rows by hand). A member renamed with its stored value kept changes nothing. A member that keeps its name but stores a new value (`ARCHIVED = "archived"` to `ARCHIVED = "old"`) needs no statement: the plan replaces the value in every row and list, and asks nothing. Values that shift along (3 to 4 while 4 to 5) work in one run. Values that move in a cycle, such as two members that swap values, are refused, and so is a member that takes the value of another member that keeps it or is removed; each message gives two plans to make the change, each planned and applied before the next. When the first plan removes a member and you answer `--delete`, a required column cannot keep its rows: delete them, or set them to a value the enum keeps, before that plan applies.
668
+ - On Postgres and SQLite, fields of value objects are subjects too, named through their own value object (`GeoPoint.lat`, never a path from a model). Each statement acts on every column that holds the value object, in a list or nested in another value object:
669
+ - `--rename GeoPoint.lat:GeoPoint.latitude` renames the key in every object (`this.renameStoredKey(...)`).
670
+ - `--delete GeoPoint.lng` removes the key from every object (`this.removeStoredKey(...)`).
671
+ - An enum value inside a value object is asked about with the enum value: `--rename Status.ARCHIVED:Status.RETIRED` rewrites it at every path, and `--delete Status.DRAFT` sets an optional member to JSON `null` and takes the value out of a list.
672
+ - `--backfill GeoPoint.country` (`migration plan` only) fills a field that becomes required: the plan writes `this.fillStoredKey({ ..., value: placeholder('GeoPoint.country:value'), field: 'GeoPoint.country' })`; write one JSON value there, self-emit, `db migrate` (which refuses while a placeholder is left). Self-emit fails with `CONTRACT.ARGUMENT_INVALID` when the field does not take the value: a wrong scalar type, an enum value outside its enum, a list element of another type, or an object without a required field. Without it `migration plan` refuses, naming `--backfill`; when the value object also lost a field, the refusal offers `--rename` of the lost field first, since the new field may be it renamed, and says `--delete` of the lost field still needs `--backfill`. `db update` asks about the lost field (`--rename` or `--delete`). `db update` fills a temporary value (`""`, `0`, `false`, `[]`) when the field's type takes it, and refuses a field such as a `DateTime`, which `""` is not.
673
+ - On Postgres and SQLite, a variant whose discriminator value changes, or that the contract removes, is asked about as the model:
674
+ - `--convert Bug` rewrites the old value to the new one in the base table's discriminator column (`this.replaceStoredValue(...)`). It works on `db update` too, and the question offers it first.
675
+ - `--rename Bug:Defect` of a variant whose value also changed rewrites the value the same way.
676
+ - `--delete Bug` deletes the rows that hold the old value (`this.deleteRows(...)`), then drops a removed variant's own table or the columns only it used. On SQLite a deleted row that another table references fails the apply at `PRAGMA foreign_key_check`, except the rows of the variant's own table, which the plan deletes first (`cascade` on `deleteRows`).
677
+ - On MongoDB, the same subjects work on documents, with free factories in `migration.ts`:
678
+ - Fields of value objects and embedded models: `--rename Address.street:Address.line1` writes `renameStoredKey({ collection, field, path: '$[*].street', to: 'line1' })` at every place the documents hold the type, through nesting, lists and embedded models; `--delete Address.street` writes `removeStoredKey(...)`. Renames that trade names or form a chain, a new required field under a name a rename moves away, and a rename onto a name the origin also stores, are refused: make the change as two changes to the contract, each applied before the next. A required field new inside one gets a temporary value (`fillStoredKey`), or `--backfill Address.zip` writes `fillStoredKey` with `value: placeholder('Address.zip:value')`, an aggregation expression (`{ $literal: '$5' }` stores the text `$5`).
679
+ - Enum values: `--rename Status.A:Status.B` writes `replaceStoredValue(...)` in every field and key the enum types; `--delete Status.A` writes `removeStoredValue(...)`, which unsets it in an optional field and takes it out of lists. Where a required field holds it, the apply stops with `MIGRATION.PRECHECK_FAILED`, counts the documents and gives the edit that keeps them. Renames that trade values or form a chain are refused: make them as two changes to the contract, each applied before the next, first to values the enum does not use, then to the final ones. A boolean enum has no third value, so swap its values yourself in one update instead. MongoDB applies operations one at a time, and a re-run after a later operation stops would replace the values twice.
680
+ - Variants: `--convert Bug`, or `--rename Bug:Defect` with a new value, writes `replaceStoredValue(...)` on the discriminator field; `--delete Bug` writes `deleteDocuments({ collection, filter: { type: 'bug' } })`. A plan where one variant takes a value another frees is refused for the same reason; make the change as two changes to the contract, each applied before the next.
681
+ - `--allow <Model>` (`db update` only) lets an operation that changes who can read or write the model's data run: one flag per operation, so on Postgres a policy drop and disabling row-level security on one model take `--allow User --allow User`.
477
682
 
478
- Routing:
683
+ ```bash
684
+ pnpm prisma migration plan --name drop_legacy --delete Legacy
685
+ pnpm prisma db update --db $DATABASE_URL --rename Profile:User --delete Legacy --allow User
686
+ pnpm prisma migration plan --name tidy_points --rename GeoPoint.lat:GeoPoint.latitude --delete GeoPoint.lng
687
+ pnpm prisma db update --db $DATABASE_URL --convert Bug
688
+ ```
479
689
 
480
- - Answer yes if the data is no longer needed.
481
- - Answer no, then either:
482
- - Re-shape the migration via `migration plan` and hand-edit `migration.ts` to preserve the data (e.g. copy-to-new-column, then drop), or
483
- - Skip the destructive operation by reverting the contract change.
690
+ In a terminal the command asks each question in turn; type `delete`, `allow`, or `rename <subject>:<new name>`. Where nobody can answer (CI, `--no-interactive`, `--yes`), it fails with `CLI.CONSENT_REQUIRED`; read `meta.unanswered[]` or the `nextActions`, decide what each subject means, and re-run with those flags. `--confirm` and `--yes` answer none of these questions. Don't reach for `--delete` by reflex: if the model or field was renamed, `--rename` keeps its rows.
484
691
 
485
- Interactively, consent is typing the database name back (the prompt names it). In non-interactive contexts (CI, `--no-interactive`), the destructive-op response is returned as `MIGRATION.DESTRUCTIVE_CHANGES` — `meta.destructiveOperations[]` lists what would have been dropped. Re-run with `--confirm <database>` to grant consent (`--yes` does not), or address each operation individually.
692
+ `db migrate` does *not* ask: whatever the package contains runs, so review the plan or call `migration show` before `db migrate`.
486
693
 
487
694
  ## Common Pitfalls
488
695
 
489
- 1. **Using `db update` against shared or production databases.** Never. The change leaves no migration history. Use `migration plan` + `db migrate`.
696
+ 1. **Using `db update` on a database that changes only through migrations, such as production.** The change leaves no migration history. Use `migration plan` + `db migrate`. A shared development or staging database is fine. A database whose change policy says `["migrate"]` refuses it; do not edit the ref or pass `--permit-policy-change` to get past that.
490
697
  2. **Skipping a data transform.** Leaving `placeholder(...)` in `migration.ts` makes the next `db migrate` throw `MIGRATION.UNFILLED_PLACEHOLDER`. Fill every placeholder slot and self-emit.
491
698
  3. **Editing `ops.json` directly.** It's the canonical artifact, not the authoring source. Edit `migration.ts`, then self-emit.
492
699
  4. **Forgetting to self-emit after editing `migration.ts`.** The next `db migrate` either uses the stale `ops.json` (if you only added comments) or fails with `MIGRATION.HASH_MISMATCH` (if you changed operations). Always self-emit.
493
700
  5. **Routine `db verify` after a successful `db update` or `db migrate`.** Redundant on the happy path — reserve `db verify` for drift diagnosis (manual edits, restore, failed `db migrate`).
494
701
  6. **Aggregate `check` closure in Postgres `this.dataTransform`.** Returning `count(*)` or `bool_and(...)` breaks the precheck/postcheck contract — both sides resolve to constants. Use a rowset shape: `select('id').where(<violation>).limit(1)`.
495
- 7. **Two contract references in one migration.** Building a query plan against a different contract than the one passed to `this.dataTransform(endContract, ...)` raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. Always import `endContract` once at module scope and use the same reference.
702
+ 7. **The wrong contract in `this.dataTransform`.** Pass the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns, and build the queries with that client's `sql`. The planner renders the imported `endContract` JSON there, which is not a validated contract ([prisma/orm#30504](https://github.com/prisma/orm/issues/30504)). A query plan built over a different contract raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`.
496
703
  11. **Calling Postgres operations as free functions.** `addColumn('public', 'user', {...})` does not exist as an import; the operations are `this.addColumn({ schema, table, column })` and friends on the `Migration` base class, with `col(...)` building the column. Only `col`, `rawSql`, `placeholder`, `Migration`, and `MigrationCLI` are imported.
497
- 8. **Renaming and expecting the planner to detect it (Postgres).** Prisma 8 has no in-contract rename hint today; the planner emits a destructive drop+add. Hand-edit `migration.ts` to rewrite the destructive op as a `rawSql({ ... })` that issues `ALTER TABLE ... RENAME COLUMN ...` (or use the two-migration keep / backfill / drop pattern), then self-emit. See `references/contract.md` § *Edit a field — rename*.
704
+ 8. **Renaming a model or field without a statement.** The planner cannot tell a rename from a drop and a create, so without a statement it plans a destructive drop+add. State the rename on the command line: `migration plan --name <slug> --rename User:Person --rename Person.email:Person.emailAddress`, or the same `--rename` flags on `db update`. A field is named through its model as the new contract names it. The planner then renames the table or column and the constraints and indexes named after it; on MongoDB it renames the collection, and the field in every document that holds it (only in that variant's documents for a variant's field). On MongoDB a field is named by its name in the contract, as on SQL: `id @map("_id")` is `User.id`. A statement that keeps the stored name, such as `--rename User.name:User.title` where both are stored as `display_name`, plans nothing; one that changes it renames the field in the documents. A model or field whose name stays and whose `@@map` or `@map` changes needs no statement, on MongoDB as on SQL (see pitfall 16).
498
705
  9. **Planning with no `db` ref and no `--from` in a project that already has migrations.** The origin falls through to the empty database, which would make the plan a full-create migration; `migration plan` refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN` rather than writing it. Pick the exit that matches your intent — the error lists them, and `references/migration-model.md` § *The trap* explains which to choose.
499
- 10. **Hand-authoring `migration.ts` from a blank file, or rewriting the rendered import line.** Migration files are framework-rendered — let `prisma migration plan` (or `migration new`) render the package, then edit only the holes the framework leaves for you. On Postgres leave the rendered `@internal/postgres/migration` (or `@internal/sqlite/migration`) import path alone; on Mongo leave `@prisma/orm-mongo/target/migration` as rendered. Add symbols to the existing import line rather than introducing new import paths.
706
+ 10. **Hand-authoring `migration.ts` from a blank file, or rewriting the rendered import line.** Migration files are framework-rendered — let `prisma migration plan` (or `migration new`) render the package, then edit only the holes the framework leaves for you, and, until [prisma/orm#30504](https://github.com/prisma/orm/issues/30504) is fixed, the first argument of `this.dataTransform` (see pitfall 7). On Postgres leave the rendered `@prisma/orm-postgres/migration` (or `@prisma/orm-sqlite/migration`) import path alone; on Mongo leave `@prisma/orm-mongo/target/migration` as rendered. Add symbols to the existing import line rather than introducing new import paths.
707
+ 12. **Replaying migrations onto a database that is already ahead.** `db migrate` on a database with no marker runs every migration, skipping operations already applied. When the database is already past a migration (it has `x int8` where the migration adds `x int4`), the run stops at that migration's precheck with `MIGRATION.PRECHECK_FAILED`. Adopt such a database with `prisma db sign` (after `contract infer` if needed), not by replaying history.
708
+ 13. **Running Prisma 7 `migrate` commands against Prisma 8.** Each one answers `CLI.V7_COMMAND` with its Prisma 8 command: `migrate dev` is `contract emit`, `migration status` (which prints the `migration plan` that takes the database to the new contract), running that `migration plan`, then `db migrate`; when migrations on disk already lead to the new contract, `migration status` prints no plan, so skip that step and run `db migrate`; `migrate deploy` is `db migrate`; `migrate reset` has no equivalent, because Prisma 8 has no reset: `db update` brings the database to the contract instead, asking before it loses data, but it keeps existing rows and runs no seed steps or data transforms (a database that changes only through migrations is moved with `db migrate`); `migrate status` is `migration status`; `migrate diff` is `db update --dry-run`, or `migration plan` to write a migration package; `migrate resolve` is `db sign <migration>`, which moves the database marker to that migration after checking its schema, but leaves `migration status` without an applied mark. While Prisma 7 still owns the migrations, install Prisma 7's CLI with `npm install --save-dev @prisma/prisma7@7` and run every one of them except `migrate diff`, whose replacement only reads, as `prisma7 migrate <command>` instead; `migrate resolve` runs as `prisma7 migrate resolve --applied <migration>`.
709
+ 14. **Changing rows outside a data transform.** A `rawSql` step that inserts, updates or deletes rows, or a Postgres transform whose query comes from `db.raw.sql` or contains `fns.raw`. Write it in a `dataTransform` (with a `check` on Postgres and Mongo); on Postgres, build its queries with the SQL query builder. *Data changes go in a data transform* explains why. If the builder cannot express it, stop (see *When the SQL query builder cannot express the transform*).
710
+ 15. **A data transform without `check` (Postgres, Mongo).** It runs `run` on every database, including those where the work is already done, and can never refuse bad data. Always write `check`.
711
+ 16. **Passing a statement for a changed `@@map` or `@map`.** A model or field that keeps its name is the same model or field, so when only `@@map` or `@map` changes, `migration plan` and `db update` rename the table or column, and its constraints and indexes, with no question and no statement. This needs a snapshot of the contract the database is at, and a table whose control policy is `managed` in both contracts. Without a snapshot, the change is planned as a drop and a create and asked about, as before, except a table name whose only change is a capital first letter (`users` to `Users`): that is refused with `MIGRATION.TABLE_NAME_CASE_CHANGED`, whose message gives the steps to rename the table; for a table that is not `managed`, nothing is renamed, and the plan is what that control policy allows. `--rename User:User` is refused with `MIGRATION.STATEMENT_INVALID`, and a `--delete User` left in a script from earlier releases fails with `CLI.CONSENT_UNUSED`. To get an empty table under the new name instead, remove the model in one change and add it back in a second. A rename the planner cannot order is refused with `MIGRATION.PLANNING_FAILED`: two models or fields that swap tables or columns, a chain where one moves to a name another frees, a model that takes the table of a removed one, and a rename statement that moves something into the old name. The message gives two plans through a name nothing uses (`prisma_swap_<name>`), or, for a takeover, a first plan that removes the model or field holding the name; follow it. One swap is not refused by `migration plan`: when two tables or columns of the same shape swap names and nothing else changes, the storage does not change, so `migration plan` reports no change and writes nothing, and the rows are then read as the other model's; `db update` refuses it. Make such a swap through a name nothing uses in the same way. The table is renamed only when everything stored in it moves, so a variant that gains or loses a table of its own is still asked about, as a data migration. MySQL plans no renames, so there a changed `@@map` is still a drop and a create. MongoDB does the same with collections, document keys (in every place an embedded model is stored) and enum stored values. Its operations run one at a time with no transaction, so it also refuses enum values that shift along a chain, and `--rename` of a model whose collection another model shares; each message gives its route.
500
712
 
501
713
  ## What Prisma 8 doesn't do yet
502
714
 
503
715
  - **Runtime-apply migrations.** Prisma 8 doesn't apply pending migrations from your app's startup code (the "Drizzle pattern" for serverless / edge). Workaround: run `prisma db migrate` from your deploy pipeline before the app starts. If you need runtime-apply built-in, file a feature request via the `references/feedback.md` skill.
504
716
  - **Seeds-as-first-class.** Prisma 8 doesn't ship a `prisma db seed` equivalent. Workaround: write a TypeScript script that imports your `db` instance and runs your setup queries; invoke it from `package.json`'s scripts. If you need first-class seeding, file a feature request via the `references/feedback.md` skill.
505
717
  - **Migration squashing.** Prisma 8 doesn't squash older migrations into a baseline. They accumulate; for very large histories, manual baseline-and-truncate is the path. If you need built-in squashing, file a feature request via the `references/feedback.md` skill.
506
- - **In-contract rename hints.** The planner cannot detect that a field rename is a rename rather than a drop+add. Workaround: hand-edit `migration.ts` to issue a `RENAME COLUMN` via `rawSql(...)`, or use a keep / backfill / drop pattern across two migrations. If you need a contract-level rename hint, file a feature request via the `references/feedback.md` skill.
718
+ - **Renames beyond models, fields, namespaces, enum values and value object fields.** `--rename` covers models and fields on Postgres, SQLite and MongoDB. On Postgres it also moves a model to another namespace and renames a namespace (not on MongoDB or SQLite). On Postgres, SQLite and MongoDB it also renames enum values, fields of value objects and variants. It does not rename value objects or native Postgres enum values, and MongoDB refuses enum value swaps and chains (make them as two changes to the contract, each applied before the next). Swaps and chains of table and column names, and swaps of enum stored values, are refused on Postgres and SQLite too, with the same two-plan route; chains of enum stored values are planned there. On MongoDB it also refuses `_id`, a field whose stored name contains `.` or starts with `$`, and a time-series collection; each refusal (`MIGRATION.PLANNING_FAILED`) says what to do instead. MongoDB itself accepts such a stored name, but an update reads `.` as a path into embedded documents and `$` as an operator, so the plan cannot rewrite the field: a type change of it is refused the same way, and a removal or a new required value is not written, so the validator change's document check stops the apply while documents do not fit. If you need one of these, file a feature request via the `references/feedback.md` skill.
719
+ - **Some data transforms (Postgres).** The SQL query builder cannot yet insert rows from a select ([prisma/orm#30488](https://github.com/prisma/orm/issues/30488)) or set a column from a subquery or a joined table ([prisma/orm#30489](https://github.com/prisma/orm/issues/30489)). There is no workaround inside a migration: stop and let the user decide (see *When the SQL query builder cannot express the transform*).
720
+ - **Contract checks for SQLite and Mongo data transforms.** SQLite's `dataTransform` takes a SQL string and Mongo's takes commands; nothing checks either against a contract. Workaround: write `run` so it is safe to run again, and review it by hand. If you need a checked form, file a feature request via the `references/feedback.md` skill.
507
721
 
508
722
  ## Graph and history commands
509
723
 
@@ -516,7 +730,7 @@ For the full graph topology: `pnpm prisma migration graph` (also supports `--leg
516
730
 
517
731
  ## `@@control` and DDL scope
518
732
 
519
- Objects whose `@@control` policy excludes them from Prisma 8's managed surface are omitted from planned DDL. The four policies are: `managed` (Prisma plans and applies DDL), `tolerated` (object may exist, no DDL emitted), `external` (object is expected to exist, no DDL), `observed` (Prisma reads but never writes). Declare `@@control(managed|tolerated|external|observed)` in your schema; see `references/contract.md` and [`packages/2-sql/2-authoring/contract-psl/README.md`](https://github.com/prisma/orm/blob/main/packages/2-sql/2-authoring/contract-psl/README.md) for authoring syntax.
733
+ Objects whose `@@control` policy excludes them from Prisma 8's managed surface are omitted from planned DDL. The four policies are: `managed` (Prisma plans and applies DDL), `tolerated` (object may exist, no DDL emitted), `external` (object is expected to exist, no DDL), `observed` (Prisma reads but never writes). Declare `@@control(managed|tolerated|external|observed)` in your schema; see `references/contract.md` and [`packages/2-sql-family/2-authoring/contract-psl/README.md`](https://github.com/prisma/orm/blob/main/packages/2-sql-family/2-authoring/contract-psl/README.md) for authoring syntax.
520
734
 
521
735
  ## Telemetry
522
736
 
@@ -525,14 +739,16 @@ The CLI collects anonymous usage data by default. To opt out, set `PRISMA_DISABL
525
739
  ## Checklist
526
740
 
527
741
  - [ ] Contract emitted (`contract.json` + `contract.d.ts` current).
528
- - [ ] Chose the right path: `db update` (local dev) vs `migration plan` + `db migrate` (anything shared).
742
+ - [ ] Chose the right path: `db update` (a database whose history does not need to be kept) vs `migration plan` + `db migrate` (a change others will receive, or a database that changes only through migrations).
529
743
  - [ ] For `migration plan`: confirmed the output's `from:` line names the intended origin — not `(baseline)` over an existing graph (`references/migration-model.md`).
530
744
  - [ ] For `migration plan`: ran `migration show <dir>` to review before `db migrate`.
531
- - [ ] Filled every `placeholder(...)` in `migration.ts` (if any), built against `endContract`.
745
+ - [ ] Filled every `placeholder(...)` in `migration.ts` (if any). On Postgres: SQL query builder queries over the end contract, and the client's `contract` passed to `this.dataTransform`. On SQLite and Mongo: the forms in *What each target checks*.
532
746
  - [ ] `check` closures are rowset queries, not scalar aggregates.
533
- - [ ] Self-emitted (`node migrations/app/<dir>/migration.ts`) after editing the TS.
747
+ - [ ] Every insert, update and delete is in a `dataTransform`, with a `check` on Postgres and Mongo; on Postgres its queries come from the SQL query builder, not `db.raw.sql` or `fns.raw`.
748
+ - [ ] Every `rawSql` step you wrote is DDL that no operation factory expresses, with a precheck and a postcheck that test the live schema.
749
+ - [ ] Self-emitted (`node <package dir>/migration.ts`) after editing the TS.
534
750
  - [ ] Ran `db migrate` (or `db update`) and saw it complete.
535
751
  - [ ] Used `db verify` only when diagnosing drift — not as a routine post-apply step.
536
- - [ ] Did NOT use `db update` against a shared or production database.
752
+ - [ ] Did NOT use `db update` on a database that changes only through migrations, such as production, and did NOT reset or drop any database to fix a migration problem.
537
753
  - [ ] Did NOT edit `ops.json` directly.
538
- - [ ] Did NOT skip a destructive-op prompt without inspecting `meta.destructiveOperations[]`; granted consent with the database name (or `--confirm <database>`), not `--yes`.
754
+ - [ ] Answered each data-loss question deliberately: `--rename` for a rename, `--delete` only for data that may go, `--allow` only for an access change that is meant.