@prisma/orm-family-sql 8.0.0-rc.24-dev.28 → 8.0.0-rc.24-dev.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/dist/{aggregate-descriptor-registry-DM1hmlq-.mjs → aggregate-descriptor-registry-oSsBuRHQ.mjs} +2 -2
  2. package/dist/{aggregate-descriptor-registry-DM1hmlq-.mjs.map → aggregate-descriptor-registry-oSsBuRHQ.mjs.map} +1 -1
  3. package/dist/{ast-BO3Wgbrl.mjs → ast-BpFfUmb_.mjs} +2 -2
  4. package/dist/{ast-BO3Wgbrl.mjs.map → ast-BpFfUmb_.mjs.map} +1 -1
  5. package/dist/{ast-D0yJ7Yf0.d.mts → ast-DvD53wSW.d.mts} +3 -3
  6. package/dist/{ast-D0yJ7Yf0.d.mts.map → ast-DvD53wSW.d.mts.map} +1 -1
  7. package/dist/{attribute-specs-DL1btx0j.d.mts → attribute-specs-DgYb4op9.d.mts} +3 -3
  8. package/dist/{attribute-specs-DL1btx0j.d.mts.map → attribute-specs-DgYb4op9.d.mts.map} +1 -1
  9. package/dist/{authoring-entity-types-CgKIgWq5-BqNs-56x.d.mts → authoring-entity-types-CgKIgWq5-C3GyB8Hj.d.mts} +2 -2
  10. package/dist/{authoring-entity-types-CgKIgWq5-BqNs-56x.d.mts.map → authoring-entity-types-CgKIgWq5-C3GyB8Hj.d.mts.map} +1 -1
  11. package/dist/builder.d.mts +3 -3
  12. package/dist/builder__runtime.d.mts +7 -7
  13. package/dist/builder__runtime.mjs +26 -12
  14. package/dist/builder__runtime.mjs.map +1 -1
  15. package/dist/builder__types.d.mts +5 -5
  16. package/dist/{collection-methods-CN0GIWWR-BSJvP4Kc.d.mts → collection-methods-As4pXm7B-3xgTSoyU.d.mts} +3 -3
  17. package/dist/{collection-methods-CN0GIWWR-BSJvP4Kc.d.mts.map → collection-methods-As4pXm7B-3xgTSoyU.d.mts.map} +1 -1
  18. package/dist/collection-methods-CS1e16Ij.d.mts +1 -0
  19. package/dist/config-types-BVrGV95W.mjs +147 -0
  20. package/dist/config-types-BVrGV95W.mjs.map +1 -0
  21. package/dist/{config-types-Ce1tAJ0B.d.mts → config-types-DVRid5jV.d.mts} +15 -3
  22. package/dist/config-types-DVRid5jV.d.mts.map +1 -0
  23. package/dist/{contract-builder-BfPC4mQK.d.mts → contract-builder-fyzIdWqX.d.mts} +77 -2
  24. package/dist/{contract-builder-BfPC4mQK.d.mts.map → contract-builder-fyzIdWqX.d.mts.map} +1 -1
  25. package/dist/{contract-builder-Dbo5LeXs.mjs → contract-builder-q2-4IVcW.mjs} +3 -3
  26. package/dist/contract-builder-q2-4IVcW.mjs.map +1 -0
  27. package/dist/contract-emitter.d.mts +3 -2
  28. package/dist/contract-emitter.d.mts.map +1 -1
  29. package/dist/contract-emitter.mjs +1 -1
  30. package/dist/contract-prisma7__provider.mjs +6 -6
  31. package/dist/contract-psl.d.mts +1 -1
  32. package/dist/contract-psl.mjs +1 -1
  33. package/dist/contract-psl__attribute-specs.d.mts +1 -1
  34. package/dist/contract-psl__attribute-specs.mjs +1 -1
  35. package/dist/contract-psl__provider.mjs +22 -19
  36. package/dist/contract-psl__provider.mjs.map +1 -1
  37. package/dist/contract-ts.d.mts +3 -3
  38. package/dist/contract-ts.mjs +4 -4
  39. package/dist/contract-ts__config-types.d.mts +2 -2
  40. package/dist/contract-ts__config-types.mjs +2 -2
  41. package/dist/contract-ts__contract-builder.d.mts +2 -2
  42. package/dist/contract-ts__contract-builder.mjs +3 -3
  43. package/dist/contract.d.mts +2 -2
  44. package/dist/contract.mjs +4 -4
  45. package/dist/contract__foreign-key-materialization.d.mts +2 -2
  46. package/dist/contract__foreign-key-materialization.mjs +3 -3
  47. package/dist/contract__validators.mjs +1 -1
  48. package/dist/{control-Cb6YoQ8j.d.mts → control-L4h4N5uy.d.mts} +158 -42
  49. package/dist/control-L4h4N5uy.d.mts.map +1 -0
  50. package/dist/{control-kHFMtE8A.mjs → control-Mh99W3HI.mjs} +2117 -1315
  51. package/dist/control-Mh99W3HI.mjs.map +1 -0
  52. package/dist/{control-adapter-0z3ce44U-CLj4kqLI.d.mts → control-adapter-0z3ce44U-BQ26ercw.d.mts} +4 -4
  53. package/dist/{control-adapter-0z3ce44U-CLj4kqLI.d.mts.map → control-adapter-0z3ce44U-BQ26ercw.d.mts.map} +1 -1
  54. package/dist/{control-adapter-DIwBUSs6.d.mts → control-adapter-DRLco_j0.d.mts} +2 -2
  55. package/dist/{control-adapter-DIwBUSs6.d.mts.map → control-adapter-DRLco_j0.d.mts.map} +1 -1
  56. package/dist/{db-DfYeGVcu-B99ycjaC.d.mts → db-by-MuHF2-B7uz_0VW.d.mts} +27 -18
  57. package/dist/db-by-MuHF2-B7uz_0VW.d.mts.map +1 -0
  58. package/dist/{ddl-types-D22OYeFy-Be5-W-5z.d.mts → ddl-types-D93zTpm9-DhSkpX0K.d.mts} +3 -3
  59. package/dist/{ddl-types-D22OYeFy-Be5-W-5z.d.mts.map → ddl-types-D93zTpm9-DhSkpX0K.d.mts.map} +1 -1
  60. package/dist/{derived-checks-BWg0DOyz-7O0x1Tgn.mjs → derived-checks-BoHNzt-a-CK4ceMbs.mjs} +228 -10
  61. package/dist/derived-checks-BoHNzt-a-CK4ceMbs.mjs.map +1 -0
  62. package/dist/{diff-DbkXUf4C.d.mts → diff-DZHlisyY.d.mts} +2 -2
  63. package/dist/{diff-DbkXUf4C.d.mts.map → diff-DZHlisyY.d.mts.map} +1 -1
  64. package/dist/{dist-BJjqJT_M.mjs → dist-C-Gi4VUC.mjs} +20 -14
  65. package/dist/dist-C-Gi4VUC.mjs.map +1 -0
  66. package/dist/{exports-BR5ctYYI-C_-aedbr.mjs → exports-kqOXg2OT-D3lo7jnX.mjs} +168 -162
  67. package/dist/exports-kqOXg2OT-D3lo7jnX.mjs.map +1 -0
  68. package/dist/expression-Bz8uEh8W.d.mts +2 -0
  69. package/dist/{expression-D8c3t2Dx-CCHt1OdT.d.mts → expression-DYRYmkMl-BMKxN8Wf.d.mts} +64 -43
  70. package/dist/expression-DYRYmkMl-BMKxN8Wf.d.mts.map +1 -0
  71. package/dist/{expression-DL7L8You-C9BAeM2d.d.mts → expression-VJWwxbUB-BtNDaTCt.d.mts} +5 -5
  72. package/dist/expression-VJWwxbUB-BtNDaTCt.d.mts.map +1 -0
  73. package/dist/{expression-impl-DHdjzqE3-Cd9gP7oC.mjs → expression-impl-C5Ha-fXs-CxXn8gDo.mjs} +7 -5
  74. package/dist/expression-impl-C5Ha-fXs-CxXn8gDo.mjs.map +1 -0
  75. package/dist/family.d.mts +8 -8
  76. package/dist/family.mjs +6 -6
  77. package/dist/family__control-adapter.d.mts +2 -2
  78. package/dist/family__control.d.mts +3 -3
  79. package/dist/family__control.mjs +3 -3
  80. package/dist/family__diff.d.mts +1 -1
  81. package/dist/family__ir.mjs +1 -1
  82. package/dist/family__migration.d.mts +1 -1
  83. package/dist/family__pack.d.mts +1 -1
  84. package/dist/family__pack.mjs +2 -2
  85. package/dist/family__psl-infer.mjs +1 -1
  86. package/dist/{foreign-key-materialization-C53nVQuD.d.mts → foreign-key-materialization-Dntzsl64.d.mts} +8 -2
  87. package/dist/foreign-key-materialization-Dntzsl64.d.mts.map +1 -0
  88. package/dist/{foreign-key-materialization-CCHAR789.mjs → foreign-key-materialization-pYirysH0.mjs} +2 -2
  89. package/dist/foreign-key-materialization-pYirysH0.mjs.map +1 -0
  90. package/dist/{functions-Cl_egJ2w.mjs → functions-DGketpiK.mjs} +3 -3
  91. package/dist/{functions-Cl_egJ2w.mjs.map → functions-DGketpiK.mjs.map} +1 -1
  92. package/dist/functions-gl3PL1so.d.mts +1 -0
  93. package/dist/{generator-functions-Bze9nVHL-Cetbgui3.mjs → generator-functions-Bze9nVHL-q4YmMS5B.mjs} +3 -3
  94. package/dist/{generator-functions-Bze9nVHL-Cetbgui3.mjs.map → generator-functions-Bze9nVHL-q4YmMS5B.mjs.map} +1 -1
  95. package/dist/{index-equivalence-DswCiq5l-9GNm8oG9.mjs → index-equivalence-eC2jGpOp-SkExsiy1.mjs} +3 -3
  96. package/dist/{index-equivalence-DswCiq5l-9GNm8oG9.mjs.map → index-equivalence-eC2jGpOp-SkExsiy1.mjs.map} +1 -1
  97. package/dist/{index-DA1EEz4y.d.mts → index-nW0rAUTr.d.mts} +28 -30
  98. package/dist/index-nW0rAUTr.d.mts.map +1 -0
  99. package/dist/{index-reference-CSrhOgZL-PIYy9LTA.d.mts → index-reference-CjvRzUh1-CG0Ouv6i.d.mts} +3 -3
  100. package/dist/{index-reference-CSrhOgZL-PIYy9LTA.d.mts.map → index-reference-CjvRzUh1-CG0Ouv6i.d.mts.map} +1 -1
  101. package/dist/index-reference-X_kA2mV8.d.mts +1 -0
  102. package/dist/{interpreter-CVd521dx-wWck8W93.mjs → interpreter-DoQwVOyS-DXYLj31g.mjs} +209 -29
  103. package/dist/interpreter-DoQwVOyS-DXYLj31g.mjs.map +1 -0
  104. package/dist/middleware-CcDThETr.d.mts +1 -0
  105. package/dist/{middleware-4P5tDL8a-C1UaoUUN.d.mts → middleware-DzFPUERE-C6RrGmcp.d.mts} +3 -3
  106. package/dist/{middleware-4P5tDL8a-C1UaoUUN.d.mts.map → middleware-DzFPUERE-C6RrGmcp.d.mts.map} +1 -1
  107. package/dist/{migration-DctFInNJ.d.mts → migration-BUWF9_Tx.d.mts} +2 -2
  108. package/dist/{migration-DctFInNJ.d.mts.map → migration-BUWF9_Tx.d.mts.map} +1 -1
  109. package/dist/orm-client.d.mts +113 -69
  110. package/dist/orm-client.d.mts.map +1 -1
  111. package/dist/orm-client.mjs +391 -121
  112. package/dist/orm-client.mjs.map +1 -1
  113. package/dist/{pack-BBsFyTEv.d.mts → pack-CbYm5Bfz.d.mts} +3 -3
  114. package/dist/{pack-BBsFyTEv.d.mts.map → pack-CbYm5Bfz.d.mts.map} +1 -1
  115. package/dist/plan-BjX90QC6.d.mts +2 -0
  116. package/dist/{plan-49sl7WSN-C22ZPSE9.d.mts → plan-Dv6v5_y4-CGWEjfCv.d.mts} +3 -3
  117. package/dist/{plan-49sl7WSN-C22ZPSE9.d.mts.map → plan-Dv6v5_y4-CGWEjfCv.d.mts.map} +1 -1
  118. package/dist/{psl-column-resolution-Bv_-TDHZ-Cuu5X_9o.d.mts → psl-column-resolution-Bv_-TDHZ-C9foRNXV.d.mts} +2 -2
  119. package/dist/{psl-column-resolution-Bv_-TDHZ-Cuu5X_9o.d.mts.map → psl-column-resolution-Bv_-TDHZ-C9foRNXV.d.mts.map} +1 -1
  120. package/dist/{psl-field-resolution-GN4iup8d-DjlZymdL.mjs → psl-field-resolution-CpxUePg1-COJnJkDs.mjs} +9 -5
  121. package/dist/psl-field-resolution-CpxUePg1-COJnJkDs.mjs.map +1 -0
  122. package/dist/{psl-infer-C9kVS9ma.mjs → psl-infer-Ckg3t4Kr.mjs} +2 -2
  123. package/dist/{psl-infer-C9kVS9ma.mjs.map → psl-infer-Ckg3t4Kr.mjs.map} +1 -1
  124. package/dist/{query-lane-context-DIJU7Owj-CAZQq4AD.d.mts → query-lane-context-BetHj4j--D3S5nucp.d.mts} +5 -5
  125. package/dist/{query-lane-context-DIJU7Owj-CAZQq4AD.d.mts.map → query-lane-context-BetHj4j--D3S5nucp.d.mts.map} +1 -1
  126. package/dist/query-lane-context-DgxWaKr-.d.mts +1 -0
  127. package/dist/relational-core.d.mts +13 -13
  128. package/dist/relational-core.mjs +3 -3
  129. package/dist/relational-core__aggregate-descriptor-registry.d.mts +1 -1
  130. package/dist/relational-core__aggregate-descriptor-registry.mjs +1 -1
  131. package/dist/relational-core__ast.d.mts +3 -3
  132. package/dist/relational-core__ast.mjs +2 -2
  133. package/dist/relational-core__codec-descriptor-registry.d.mts +2 -2
  134. package/dist/relational-core__collection-methods.d.mts +2 -2
  135. package/dist/relational-core__contract-free.d.mts +2 -2
  136. package/dist/relational-core__contract-free.mjs +1 -1
  137. package/dist/relational-core__contract-free.mjs.map +1 -1
  138. package/dist/relational-core__expression.d.mts +4 -4
  139. package/dist/relational-core__expression.mjs +1 -1
  140. package/dist/relational-core__functions.d.mts +2 -2
  141. package/dist/relational-core__functions.mjs +1 -1
  142. package/dist/relational-core__index-reference.d.mts +2 -2
  143. package/dist/relational-core__middleware.d.mts +2 -2
  144. package/dist/relational-core__plan.d.mts +3 -3
  145. package/dist/relational-core__query-lane-context.d.mts +2 -2
  146. package/dist/relational-core__types.d.mts +2 -2
  147. package/dist/runtime.d.mts +4 -4
  148. package/dist/runtime.mjs +1 -1
  149. package/dist/runtime__internal__prepared-query.d.mts +1 -1
  150. package/dist/{sql-contract-serializer-sMY3prTx-D_K7uFJk.mjs → sql-contract-serializer-sMY3prTx-CIDal1t1.mjs} +2 -2
  151. package/dist/{sql-contract-serializer-sMY3prTx-D_K7uFJk.mjs.map → sql-contract-serializer-sMY3prTx-CIDal1t1.mjs.map} +1 -1
  152. package/dist/{sql-execution-plan-BeuM3CeD-DIzyMDsA.d.mts → sql-execution-plan-4OFBeONp-CLkDqMdz.d.mts} +3 -3
  153. package/dist/sql-execution-plan-4OFBeONp-CLkDqMdz.d.mts.map +1 -0
  154. package/dist/{transaction-state-CEe4TlC1-C8vX6Ror.d.mts → transaction-state-B4FVsvO7-DpvKYHSB.d.mts} +12 -10
  155. package/dist/{transaction-state-CEe4TlC1-C8vX6Ror.d.mts.map → transaction-state-B4FVsvO7-DpvKYHSB.d.mts.map} +1 -1
  156. package/dist/types-BFCrGkhG.d.mts +1 -0
  157. package/dist/{types-C6r7Myrr-3WL0WDKF.d.mts → types-CGr02DOy-CQsUdKCe.d.mts} +6 -6
  158. package/dist/{types-C6r7Myrr-3WL0WDKF.d.mts.map → types-CGr02DOy-CQsUdKCe.d.mts.map} +1 -1
  159. package/dist/{types-CWvmfrfd-DLQYhSUx.d.mts → types-CWvmfrfd-HPIh55bi.d.mts} +2 -2
  160. package/dist/{types-CWvmfrfd-DLQYhSUx.d.mts.map → types-CWvmfrfd-HPIh55bi.d.mts.map} +1 -1
  161. package/dist/{types-DeimCJiI-CVQS7KCu.d.mts → types-DEbNJhyS-CY7Ye2vN.d.mts} +5 -5
  162. package/dist/{types-DeimCJiI-CVQS7KCu.d.mts.map → types-DEbNJhyS-CY7Ye2vN.d.mts.map} +1 -1
  163. package/dist/{types-wn1bXh0b-CJPAJi22.mjs → types-DzQmUrUm-ColHE4Av.mjs} +18 -5
  164. package/dist/types-DzQmUrUm-ColHE4Av.mjs.map +1 -0
  165. package/dist/{validators-CWcdf_jZ.mjs → validators-DbCIebZb.mjs} +2 -2
  166. package/dist/{validators-CWcdf_jZ.mjs.map → validators-DbCIebZb.mjs.map} +1 -1
  167. package/package.json +18 -18
  168. package/dist/collection-methods-B-md3Mu9.d.mts +0 -1
  169. package/dist/config-types-BVAADwjp.mjs +0 -68
  170. package/dist/config-types-BVAADwjp.mjs.map +0 -1
  171. package/dist/config-types-Ce1tAJ0B.d.mts.map +0 -1
  172. package/dist/contract-builder-Dbo5LeXs.mjs.map +0 -1
  173. package/dist/control-Cb6YoQ8j.d.mts.map +0 -1
  174. package/dist/control-kHFMtE8A.mjs.map +0 -1
  175. package/dist/db-DfYeGVcu-B99ycjaC.d.mts.map +0 -1
  176. package/dist/derived-checks-BWg0DOyz-7O0x1Tgn.mjs.map +0 -1
  177. package/dist/dist-BJjqJT_M.mjs.map +0 -1
  178. package/dist/exports-BR5ctYYI-C_-aedbr.mjs.map +0 -1
  179. package/dist/expression-D8c3t2Dx-CCHt1OdT.d.mts.map +0 -1
  180. package/dist/expression-DL7L8You-C9BAeM2d.d.mts.map +0 -1
  181. package/dist/expression-Voyb-zN0.d.mts +0 -2
  182. package/dist/expression-impl-DHdjzqE3-Cd9gP7oC.mjs.map +0 -1
  183. package/dist/foreign-key-materialization-C53nVQuD.d.mts.map +0 -1
  184. package/dist/foreign-key-materialization-CCHAR789.mjs.map +0 -1
  185. package/dist/functions-zPzQYOjW.d.mts +0 -1
  186. package/dist/index-DA1EEz4y.d.mts.map +0 -1
  187. package/dist/index-reference-DuQ-0Da9.d.mts +0 -1
  188. package/dist/interpreter-CVd521dx-wWck8W93.mjs.map +0 -1
  189. package/dist/middleware-DDOdMwm4.d.mts +0 -1
  190. package/dist/plan-BEnXVtn1.d.mts +0 -2
  191. package/dist/psl-field-resolution-GN4iup8d-DjlZymdL.mjs.map +0 -1
  192. package/dist/query-lane-context-Dm5f9VAQ.d.mts +0 -1
  193. package/dist/sql-execution-plan-BeuM3CeD-DIzyMDsA.d.mts.map +0 -1
  194. package/dist/types-ChjF67Fc.d.mts +0 -1
  195. package/dist/types-wn1bXh0b-CJPAJi22.mjs.map +0 -1
@@ -9,14 +9,14 @@ import { s as StorageTable } from "./storage-table-B_MrLtQX-eWx6BgGT.mjs";
9
9
  import { c as SqlSchemaIR, n as RelationalSchemaNodeKind, u as SqlTableIR } from "./types-1ZKE0deC-Dou4ugcz.mjs";
10
10
  import { f as sqlExpressionRegistration, m as sqlTextsReadBack, o as printSqlExpressionLiteral } from "./sql-expression-CKgKznXS.mjs";
11
11
  import { d as nonEmptyTypeParams, u as isStorageTypeInstance } from "./types-CISwoRED.mjs";
12
- import { g as valueObjectStorageTypeMissingMessage } from "./validators-CWcdf_jZ.mjs";
13
- import { a as describeUnsupportedSqlAttribute, b as sqlAttributeSpecs } from "./psl-field-resolution-GN4iup8d-DjlZymdL.mjs";
12
+ import { g as valueObjectStorageTypeMissingMessage } from "./validators-DbCIebZb.mjs";
13
+ import { S as sqlAttributeSpecs, s as describeUnsupportedSqlAttribute } from "./psl-field-resolution-CpxUePg1-COJnJkDs.mjs";
14
14
  import { t as describeUnresolvedSqlType } from "./diagnostics-H1-1Eb14.mjs";
15
- import { t as sqlEmission } from "./dist-BJjqJT_M.mjs";
16
- import { a as sqlFamilyGeneratorFunctions, i as sqlFamilyGeneratorDescriptors, n as sqlFamilyAuthoringTypes, o as sqlFamilyPslBlockDescriptors, r as sqlFamilyEntityTypes } from "./generator-functions-Bze9nVHL-Cetbgui3.mjs";
15
+ import { t as sqlEmission } from "./dist-C-Gi4VUC.mjs";
16
+ import { a as sqlFamilyGeneratorFunctions, i as sqlFamilyGeneratorDescriptors, n as sqlFamilyAuthoringTypes, o as sqlFamilyPslBlockDescriptors, r as sqlFamilyEntityTypes } from "./generator-functions-Bze9nVHL-q4YmMS5B.mjs";
17
17
  import { c as verifySqlSchemaByDiff, n as classifyDiffSubjectGranularity, o as enforceSqlDataTypeInvariants, t as classifyDiffEntityKind } from "./schema-verify-C3wbdviw-nQ4tG9N7.mjs";
18
18
  import { t as sqlFamilyError } from "./errors-B5g0xWro-C8plbqga.mjs";
19
- import { t as SqlContractSerializer } from "./sql-contract-serializer-sMY3prTx-D_K7uFJk.mjs";
19
+ import { t as SqlContractSerializer } from "./sql-contract-serializer-sMY3prTx-CIDal1t1.mjs";
20
20
  import { t as collectSupportedCodecTypeIds } from "./verify-BVk5bjdH-DhKm6hB3.mjs";
21
21
  import { isStructuredError, structuredError } from "@prisma/orm-framework/utils/structured-error";
22
22
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
@@ -428,6 +428,7 @@ function createSqlFamilyInstance(stack) {
428
428
  const diffSchema = blindCast(target).diffSchema;
429
429
  const targetGranularityOf = blindCast(target).classifySubjectGranularity;
430
430
  const targetEntityKindOf = blindCast(target).classifyEntityKind;
431
+ const targetAccessChangesOf = blindCast(target).accessChangesOf;
431
432
  const describedContracts = extensions.flatMap((extension) => extension.contractSpace ? [{
432
433
  spaceId: extension.id,
433
434
  contract: extension.contractSpace.contractJson
@@ -733,6 +734,10 @@ function createSqlFamilyInstance(stack) {
733
734
  storageNameOf(operation) {
734
735
  return storageNameOfOperation(operation);
735
736
  },
737
+ accessChangesOf(operations) {
738
+ if (targetAccessChangesOf === void 0) throw missingDescriptorOperationError(target.targetId, "accessChangesOf");
739
+ return targetAccessChangesOf(operations);
740
+ },
736
741
  toSchemaView(schema) {
737
742
  const root = blindCast(schema);
738
743
  const namespaceEntries = root.namespaces !== void 0 ? Object.entries(root.namespaces).map(([namespaceKey, namespace]) => [namespaceKey, namespace.tables]) : [[void 0, root.tables ?? {}]];
@@ -1421,13 +1426,6 @@ async function checkDatabasePoliciesHeld(family, driver, checked) {
1421
1426
  });
1422
1427
  }
1423
1428
  }
1424
- /**
1425
- * The way out of a refusal that no statement or second plan can lift: a migration the user writes
1426
- * by hand, which rewrites `what` with the other operations of the change.
1427
- */
1428
- function handWrittenMigrationAdvice(what) {
1429
- return `Write this change as a hand-written migration instead: run prisma migration new, and in the operations of the migration.ts it writes, rewrite ${what} yourself, with the other operations of the change. Then run that migration.ts to emit its ops.json.`;
1430
- }
1431
1429
  const BLANK = /* @__PURE__ */ new Set([
1432
1430
  " ",
1433
1431
  " ",
@@ -1580,150 +1578,6 @@ function jsonPathText(steps) {
1580
1578
  return /^[A-Za-z_][A-Za-z0-9_]*$/.test(step.name) ? `.${step.name}` : `[${JSON.stringify(step.name)}]`;
1581
1579
  }).join("")}`;
1582
1580
  }
1583
- const COLUMN_RENAME_UNMATCHED_CODE = "MIGRATION.COLUMN_RENAME_UNMATCHED";
1584
- function tableLabel$1(namespaceId, table) {
1585
- return namespaceId === void 0 || namespaceId === UNBOUND_NAMESPACE_ID ? table : `${namespaceId}.${table}`;
1586
- }
1587
- function columnLabel(namespaceId, table, column) {
1588
- return `"${tableLabel$1(namespaceId, table)}"."${column}"`;
1589
- }
1590
- function declaresColumn(contract, namespaceId, table, column) {
1591
- const columns = contract.storage.namespaces[namespaceId]?.entries.table?.[table]?.columns;
1592
- return columns !== void 0 && Object.hasOwn(columns, column);
1593
- }
1594
- /**
1595
- * Refuses a `renameColumn` call that does not match the migration's contracts, with
1596
- * `MIGRATION.COLUMN_RENAME_UNMATCHED`.
1597
- */
1598
- function unmatchedColumnRename(rename, reason) {
1599
- return sqlFamilyError(COLUMN_RENAME_UNMATCHED_CODE, `renameColumn ${columnLabel(rename.namespaceId, rename.table, rename.from)} to "${rename.to}" does not match the migration's contracts: ${reason}.`, {
1600
- why: "renameColumn must name a table and a column as the migration's earlier rename operations leave them, and a new column name that the end contract has on that table and that the table does not have yet. Order the rename calls in the sequence the renames happen, and check the names of the table, the column and the namespace.",
1601
- meta: {
1602
- table: rename.table,
1603
- from: rename.from,
1604
- to: rename.to
1605
- }
1606
- });
1607
- }
1608
- /**
1609
- * Checks a column rename: the table must exist in `previous` (in exactly one namespace when the
1610
- * namespace is not given) with the old column and without the new one, and the end contract must
1611
- * have the new column on that table.
1612
- */
1613
- function checkColumnRename(previous, endContract, rename) {
1614
- const namespaceIds = rename.namespaceId === void 0 ? previous.namespacesWithTable(rename.table) : previous.hasTable(rename.namespaceId, rename.table) ? [rename.namespaceId] : [];
1615
- const [namespaceId, ...others] = namespaceIds;
1616
- if (namespaceId === void 0) return notOk({ kind: "tableMissing" });
1617
- if (others.length > 0) return notOk({
1618
- kind: "tableInManyNamespaces",
1619
- namespaceIds
1620
- });
1621
- if (!previous.hasColumn(namespaceId, rename.table, rename.from)) return notOk({
1622
- kind: "columnMissing",
1623
- namespaceId
1624
- });
1625
- const [taken] = previous.columnsNamed(namespaceId, rename.table, rename.to).filter((column) => column !== rename.from);
1626
- if (taken !== void 0) return notOk({
1627
- kind: "nameTaken",
1628
- namespaceId,
1629
- taken
1630
- });
1631
- if (!declaresColumn(endContract, namespaceId, rename.table, rename.to)) return notOk({
1632
- kind: "notInEndContract",
1633
- namespaceId
1634
- });
1635
- return ok({
1636
- namespaceId,
1637
- table: rename.table,
1638
- from: rename.from,
1639
- to: rename.to
1640
- });
1641
- }
1642
- /** The reason `MIGRATION.COLUMN_RENAME_UNMATCHED` gives for a mismatch. */
1643
- function columnRenameMismatchReason(rename, mismatch) {
1644
- switch (mismatch.kind) {
1645
- case "tableMissing": return `table "${tableLabel$1(rename.namespaceId, rename.table)}" does not exist at this point of the migration`;
1646
- case "tableInManyNamespaces": return `table "${rename.table}" is declared in more than one namespace (${mismatch.namespaceIds.join(", ")}); name its namespace`;
1647
- case "columnMissing": return `column ${columnLabel(mismatch.namespaceId, rename.table, rename.from)} does not exist at this point of the migration`;
1648
- case "nameTaken": return `column ${columnLabel(mismatch.namespaceId, rename.table, rename.to)} already exists at this point of the migration${mismatch.taken === rename.to ? "" : ` as "${mismatch.taken}"`}`;
1649
- case "notInEndContract": return `column ${columnLabel(mismatch.namespaceId, rename.table, rename.to)} does not exist in the end contract`;
1650
- }
1651
- }
1652
- /**
1653
- * Resolves a column a migration renames with {@link checkColumnRename}, refusing a mismatch with
1654
- * `MIGRATION.COLUMN_RENAME_UNMATCHED`.
1655
- */
1656
- function resolveColumnRenameAgainst(previous, endContract, rename) {
1657
- const checked = checkColumnRename(previous, endContract, rename);
1658
- if (!checked.ok) return notOk(unmatchedColumnRename(rename, columnRenameMismatchReason(rename, checked.failure)));
1659
- return ok(checked.value);
1660
- }
1661
- const TABLE_RENAME_UNMATCHED_CODE = "MIGRATION.TABLE_RENAME_UNMATCHED";
1662
- function tableLabel(namespaceId, tableName) {
1663
- return namespaceId === void 0 || namespaceId === UNBOUND_NAMESPACE_ID ? tableName : `${namespaceId}.${tableName}`;
1664
- }
1665
- function declares(contract, namespaceId, tableName) {
1666
- return Object.hasOwn(contract.storage.namespaces[namespaceId]?.entries.table ?? {}, tableName);
1667
- }
1668
- /**
1669
- * Refuses a `renameTable` call that does not match the migration's contracts, with
1670
- * `MIGRATION.TABLE_RENAME_UNMATCHED`.
1671
- */
1672
- function unmatchedTableRename(rename, reason) {
1673
- return sqlFamilyError(TABLE_RENAME_UNMATCHED_CODE, `renameTable "${tableLabel(rename.namespaceId, rename.from)}" to "${rename.to}" does not match the migration's contracts: ${reason}.`, {
1674
- why: "renameTable must name a table as the migration's earlier rename operations leave it, and a new name that the end contract has and that no earlier rename operation has already produced. Order the renameTable calls in the sequence the renames happen, make the rename its own schema change, and check the spelling, the table and the namespace.",
1675
- meta: {
1676
- from: rename.from,
1677
- to: rename.to
1678
- }
1679
- });
1680
- }
1681
- /**
1682
- * Checks a table rename: the table must exist in `previous` (in exactly one namespace when the
1683
- * namespace is not given), and the new name must exist in the end contract and not in `previous`.
1684
- */
1685
- function checkTableRename(previous, endContract, rename) {
1686
- const namespaceIds = rename.namespaceId === void 0 ? previous.namespacesWithTable(rename.from) : previous.hasTable(rename.namespaceId, rename.from) ? [rename.namespaceId] : [];
1687
- const [namespaceId, ...others] = namespaceIds;
1688
- if (namespaceId === void 0) return notOk({ kind: "tableMissing" });
1689
- if (others.length > 0) return notOk({
1690
- kind: "tableInManyNamespaces",
1691
- namespaceIds
1692
- });
1693
- const [taken] = previous.tablesNamed(namespaceId, rename.to).filter((table) => table !== rename.from);
1694
- if (taken !== void 0) return notOk({
1695
- kind: "nameTaken",
1696
- namespaceId,
1697
- taken
1698
- });
1699
- if (!declares(endContract, namespaceId, rename.to)) return notOk({
1700
- kind: "notInEndContract",
1701
- namespaceId
1702
- });
1703
- return ok({
1704
- namespaceId,
1705
- from: rename.from,
1706
- to: rename.to
1707
- });
1708
- }
1709
- /** The reason `MIGRATION.TABLE_RENAME_UNMATCHED` gives for a mismatch. */
1710
- function tableRenameMismatchReason(rename, mismatch) {
1711
- switch (mismatch.kind) {
1712
- case "tableMissing": return `table "${tableLabel(rename.namespaceId, rename.from)}" does not exist at this point of the migration`;
1713
- case "tableInManyNamespaces": return `table "${rename.from}" is declared in more than one namespace (${mismatch.namespaceIds.join(", ")}); name its namespace`;
1714
- case "nameTaken": return `table "${tableLabel(mismatch.namespaceId, rename.to)}" already exists at this point of the migration${mismatch.taken === rename.to ? "" : ` as "${mismatch.taken}"`}`;
1715
- case "notInEndContract": return `table "${tableLabel(mismatch.namespaceId, rename.to)}" does not exist in the end contract`;
1716
- }
1717
- }
1718
- /**
1719
- * Resolves a table a migration renames with {@link checkTableRename}, refusing a mismatch with
1720
- * `MIGRATION.TABLE_RENAME_UNMATCHED`.
1721
- */
1722
- function resolveTableRenameAgainst(previous, endContract, rename) {
1723
- const checked = checkTableRename(previous, endContract, rename);
1724
- if (!checked.ok) return notOk(unmatchedTableRename(rename, tableRenameMismatchReason(rename, checked.failure)));
1725
- return ok(checked.value);
1726
- }
1727
1581
  /** Whether a model's storage names a table, as a model a SQL contract stores in a table does. */
1728
1582
  function isSqlModelStorage(storage) {
1729
1583
  return typeof storage["table"] === "string" && typeof storage["namespaceId"] === "string" && typeof storage["fields"] === "object" && storage["fields"] !== null;
@@ -1740,1084 +1594,685 @@ function modelTable(contract, coordinate) {
1740
1594
  table: storage.table
1741
1595
  };
1742
1596
  }
1743
- /**
1744
- * The storage effect of a model rename: the origin model's table compared with the destination
1745
- * model's. Equal tables mean the rename needs no storage change.
1746
- */
1747
- function modelRenameStorageEffect(statement, fromContract, contract) {
1748
- const from = modelTable(fromContract, statement.from);
1749
- if (from === void 0) return notOk({
1750
- kind: "noTable",
1751
- model: statement.from
1752
- });
1753
- const to = modelTable(contract, statement.to);
1754
- if (to === void 0) return notOk({
1755
- kind: "noTable",
1756
- model: statement.to
1757
- });
1758
- if (from.namespaceId !== to.namespaceId) return ok({
1759
- kind: "moveNamespace",
1760
- from,
1761
- to
1762
- });
1763
- if (from.table === to.table) return ok({ kind: "unchanged" });
1764
- return ok({
1765
- kind: "renameTable",
1766
- rename: {
1767
- namespaceId: from.namespaceId,
1768
- from: from.table,
1769
- to: to.table
1770
- }
1771
- });
1772
- }
1773
1597
  function fieldColumn(contract, coordinate) {
1774
1598
  const fields = sqlModelStorage(contract, coordinate)?.fields;
1775
1599
  return fields !== void 0 && Object.hasOwn(fields, coordinate.field) ? fields[coordinate.field]?.column : void 0;
1776
1600
  }
1601
+ function sameTable(left, right) {
1602
+ return left.namespaceId === right.namespaceId && left.table === right.table;
1603
+ }
1604
+ const exactName = (left, right) => left === right;
1777
1605
  /**
1778
- * The storage effect of a field rename: the origin field's column compared with the destination
1779
- * field's. A relation field has no column on either side, and equal columns need no change.
1606
+ * The models of `contract` stored in `table`, or in a table of its namespace that `sameName` takes
1607
+ * for it: a model and its single-table variants share one.
1780
1608
  */
1781
- function fieldRenameStorageEffect(statement, fromContract, contract) {
1782
- const table = modelTable(fromContract, statement.from);
1783
- if (table === void 0) return notOk({
1784
- kind: "noTable",
1785
- model: statement.from
1786
- });
1787
- const from = fieldColumn(fromContract, statement.from);
1788
- const to = fieldColumn(contract, statement.to);
1789
- if (from === void 0 && to === void 0) return ok({ kind: "unchanged" });
1790
- if (from === void 0 || to === void 0) return notOk({ kind: "columnOnOneSide" });
1791
- if (from === to) return ok({ kind: "unchanged" });
1792
- return ok({
1793
- kind: "renameColumn",
1794
- table,
1795
- from,
1796
- to
1797
- });
1798
- }
1799
- function operationsOf(call) {
1800
- return [call, ...call.companions];
1801
- }
1802
- /** The origins of a plan whose statements renamed and moved nothing. */
1803
- const NO_RENAMED_ORIGINS = {
1804
- originTable: (current) => current,
1805
- originColumn: (_origin, column) => column
1806
- };
1807
- const PLANNED_WITH_DIFF = { kind: "plannedWithDiff" };
1808
- function plannedAt(operationIndexes) {
1809
- return {
1810
- kind: "planned",
1811
- operationIndexes
1812
- };
1609
+ function modelsStoring(contract, table, sameName) {
1610
+ return Object.entries(contract.domain.namespaces).flatMap(([namespaceId, namespace]) => Object.entries(namespace.models).flatMap(([model, definition]) => {
1611
+ const { storage } = definition;
1612
+ return isSqlModelStorage(storage) && storage.namespaceId === table.namespaceId && sameName(storage.table, table.table) ? [{
1613
+ coordinate: {
1614
+ namespaceId: asNamespaceId(namespaceId),
1615
+ model
1616
+ },
1617
+ isRoot: definition.base === void 0,
1618
+ fields: storage.fields
1619
+ }] : [];
1620
+ }));
1813
1621
  }
1814
- const DRIFTED = "so the database has drifted from that contract. Inspect it with prisma db schema, or leave out this statement.";
1815
- const UNMATCHED = "A statement plans the rename a hand-written rename call makes, and that call does not match the contracts. Leave out this statement.";
1816
- function statementRefused(statement, summary, why, location, refusedOperationClass) {
1817
- return {
1818
- kind: "statementRefused",
1819
- summary,
1820
- why,
1821
- refusedStatement: statement,
1822
- ...refusedOperationClass === void 0 ? {} : { refusedOperationClass },
1823
- ...location === void 0 ? {} : { location: {
1824
- namespaceId: location.namespaceId,
1825
- entityKind: "table",
1826
- entityName: location.table,
1827
- ...location.column === void 0 ? {} : { column: location.column }
1828
- } }
1829
- };
1622
+ /**
1623
+ * The fields of `contract` stored in `column` of `table`, or in a column `sameName` takes for it:
1624
+ * variant fields may share one.
1625
+ */
1626
+ function fieldsStoring(contract, table, column, sameName) {
1627
+ return modelsStoring(contract, table, sameName).flatMap(({ coordinate, fields }) => Object.entries(fields).filter(([, stored]) => sameName(stored.column, column)).map(([field]) => ({
1628
+ ...coordinate,
1629
+ field
1630
+ })));
1830
1631
  }
1831
1632
  function tableControlPolicy(contract, table) {
1832
1633
  const node = contract.storage.namespaces[table.namespaceId]?.entries.table?.[table.table];
1833
1634
  return governingControlPolicy({ explicitNodeControlPolicy: StorageTable.is(node) ? node.control : void 0 }, contract.defaultControlPolicy);
1834
1635
  }
1835
- function tableKey(table) {
1836
- return JSON.stringify([table.namespaceId, table.table]);
1636
+ /** Joins items into text: "a", "a and b", "a, b and c". */
1637
+ function joinedList(items) {
1638
+ return items.length === 1 ? items[0] ?? "" : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
1837
1639
  }
1838
- /** A contract space other than the one planned that declares the namespace, if any. */
1839
- function otherSpaceDeclaring(ownership, namespaceId) {
1840
- return (ownership.oracle?.namespaceDeclaringSpaces(namespaceId) ?? []).find((spaceId) => spaceId !== ownership.spaceId);
1640
+ function fieldDisplayName(field) {
1641
+ return `${modelDisplayName(field)}.${field.field}`;
1841
1642
  }
1842
- function withoutNamespacesRefused(statement, label) {
1843
- return statementRefused(statement, `${label}: the database target keeps every table in one namespace`, "This database target has no namespaces, so a statement cannot rename a namespace or move a model to another one. Leave out this statement.", void 0);
1643
+ function namedList(noun, names) {
1644
+ return `${noun}${names.length === 1 ? "" : "s"} ${joinedList(names.map((name) => `"${name}"`))}`;
1844
1645
  }
1845
- function namespaceText(namespaceId) {
1846
- return namespaceId === UNBOUND_NAMESPACE_ID ? "the unbound namespace" : `namespace "${namespaceId}"`;
1646
+ function modelsText(models) {
1647
+ return namedList("model", models.map(modelDisplayName));
1847
1648
  }
1848
- function qualifiedTable(table) {
1849
- return table.namespaceId === UNBOUND_NAMESPACE_ID ? table.table : `${table.namespaceId}.${table.table}`;
1649
+ function fieldsText(fields) {
1650
+ return namedList("field", fields.map(fieldDisplayName));
1850
1651
  }
1851
- function tableRenameRefused(statement, label, rename, mismatch) {
1852
- switch (mismatch.kind) {
1853
- case "tableMissing": return statementRefused(statement, `${label}: the schema being planned from has no table "${rename.from}"`, `The database has no table "${rename.from}", although the contract it was last updated to names it, ${DRIFTED}`, {
1854
- namespaceId: rename.namespaceId,
1855
- table: rename.from
1856
- });
1857
- case "nameTaken": return statementRefused(statement, `${label}: the schema being planned from already has a table "${rename.to}"${mismatch.taken === rename.to ? "" : `, as "${mismatch.taken}"`}`, `A rename cannot replace a table that already exists. Rename or drop table "${mismatch.taken}" first, or leave out this statement.`, {
1858
- namespaceId: rename.namespaceId,
1859
- table: rename.to
1860
- });
1861
- case "tableInManyNamespaces":
1862
- case "notInEndContract": return statementRefused(statement, `${label}: ${tableRenameMismatchReason(rename, mismatch)}`, UNMATCHED, {
1863
- namespaceId: rename.namespaceId,
1864
- table: rename.from
1865
- });
1866
- }
1652
+ function capitalized(text) {
1653
+ return `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
1867
1654
  }
1868
- function columnRenameRefused(statement, label, rename, mismatch) {
1869
- const table = {
1870
- namespaceId: rename.namespaceId,
1871
- table: rename.table
1655
+ /** The steps of a migration the user writes by hand, which rewrites `what` with the other operations of the change. */
1656
+ function handWrittenMigrationSteps(what) {
1657
+ return `run prisma migration new, and in the operations of the migration.ts it writes, rewrite ${what} yourself, with the other operations of the change. Then run that migration.ts to emit its ops.json.`;
1658
+ }
1659
+ /**
1660
+ * The way out of a refusal that no statement or second plan can lift: a migration the user writes
1661
+ * by hand, which rewrites `what` with the other operations of the change.
1662
+ */
1663
+ function handWrittenMigrationAdvice(what) {
1664
+ return `Write this change as a hand-written migration instead: ${handWrittenMigrationSteps(what)}`;
1665
+ }
1666
+ const WILDCARD = { kind: "wildcard" };
1667
+ function isMany$2(many) {
1668
+ return many !== void 0 && many !== false;
1669
+ }
1670
+ function requiredValueObject(storage, reference) {
1671
+ const valueObject = valueObjectAt(storage, reference);
1672
+ invariant(valueObject !== void 0, `value object "${reference.entityName}" in namespace "${reference.namespaceId}" is not in storage; the contract validators refuse a reference to a missing value object`);
1673
+ return valueObject;
1674
+ }
1675
+ function nestedReferences(valueObject) {
1676
+ return Object.values(valueObject.fields).flatMap(({ type }) => type.kind === "valueObject" ? [type] : []);
1677
+ }
1678
+ function containsItself(storage, from) {
1679
+ const own = /* @__PURE__ */ new Set([referenceKey(from)]);
1680
+ return nestedReferences(requiredValueObject(storage, from)).some((nested) => reachesAny(storage, nested, own));
1681
+ }
1682
+ /** The paths from `steps` to each object of `target` inside an object of `from`. */
1683
+ function pathsWithin(storage, from, steps, target) {
1684
+ const targets = /* @__PURE__ */ new Set([referenceKey(target)]);
1685
+ if (containsItself(storage, from)) return reachesAny(storage, from, targets) ? {
1686
+ kind: "containsItself",
1687
+ valueObject: from.entityName
1688
+ } : {
1689
+ kind: "paths",
1690
+ paths: []
1872
1691
  };
1873
- switch (mismatch.kind) {
1874
- case "tableMissing": return statementRefused(statement, `${label}: the schema being planned from has no table "${rename.table}"`, `The database has no table "${rename.table}", although the contract it was last updated to names it, ${DRIFTED}`, table);
1875
- case "columnMissing": return statementRefused(statement, `${label}: the schema being planned from has no column "${rename.from}" on table "${rename.table}"`, `The database has no column "${rename.from}" on table "${rename.table}", although the contract it was last updated to names it, ${DRIFTED}`, {
1876
- ...table,
1877
- column: rename.from
1878
- });
1879
- case "nameTaken": return statementRefused(statement, `${label}: the schema being planned from already has a column "${mismatch.taken}" on table "${rename.table}"`, `A rename cannot replace a column that already exists. Rename or drop column "${mismatch.taken}" of table "${rename.table}" first, or leave out this statement.`, {
1880
- ...table,
1881
- column: rename.to
1882
- });
1883
- case "tableInManyNamespaces":
1884
- case "notInEndContract": return statementRefused(statement, `${label}: ${columnRenameMismatchReason(rename, mismatch)}`, UNMATCHED, {
1885
- ...table,
1886
- column: rename.from
1887
- });
1692
+ const paths = referenceKey(from) === referenceKey(target) ? [steps] : [];
1693
+ for (const [name, field] of Object.entries(requiredValueObject(storage, from).fields)) {
1694
+ if (field.type.kind !== "valueObject") continue;
1695
+ const nested = pathsWithin(storage, field.type, [
1696
+ ...steps,
1697
+ {
1698
+ kind: "member",
1699
+ name
1700
+ },
1701
+ ...isMany$2(field.many) ? [WILDCARD] : []
1702
+ ], target);
1703
+ if (nested.kind !== "paths") return nested;
1704
+ paths.push(...nested.paths);
1888
1705
  }
1706
+ return {
1707
+ kind: "paths",
1708
+ paths
1709
+ };
1889
1710
  }
1890
- function planned(operationIndexes) {
1891
- return operationIndexes.ok ? ok(plannedAt(operationIndexes.value)) : operationIndexes;
1711
+ function reachOf(storage, field, target) {
1712
+ const targets = /* @__PURE__ */ new Set([referenceKey(target)]);
1713
+ const { type } = field;
1714
+ if (type.kind === "union") return type.members.some((member) => member.kind === "valueObject" && reachesAny(storage, member, targets)) ? { kind: "union" } : {
1715
+ kind: "paths",
1716
+ paths: []
1717
+ };
1718
+ if (type.kind !== "valueObject") return {
1719
+ kind: "paths",
1720
+ paths: []
1721
+ };
1722
+ if (field.dict === true) return reachesAny(storage, type, targets) ? { kind: "dictionary" } : {
1723
+ kind: "paths",
1724
+ paths: []
1725
+ };
1726
+ return pathsWithin(storage, type, isMany$2(field.many) ? [WILDCARD] : [], target);
1892
1727
  }
1893
- var StatementPlanner = class {
1894
- #fromContract;
1895
- #contract;
1896
- #policy;
1897
- #target;
1898
- /** Where each table renamed or moved so far is in the working schema, keyed by its origin place. */
1899
- #renamedTables = /* @__PURE__ */ new Map();
1900
- /** The origin place of each table renamed or moved so far, keyed as `#renamedTables`. */
1901
- #originTables = /* @__PURE__ */ new Map();
1902
- /** Each column renamed so far: its origin table, and its name before and after. */
1903
- #renamedColumns = [];
1904
- /** The name each namespace renamed so far has in the working schema, keyed by its origin name. */
1905
- #renamedNamespaces = /* @__PURE__ */ new Map();
1906
- #ownership;
1907
- calls = [];
1908
- /** How many operations the calls planned so far lower to. */
1909
- #operationCount = 0;
1910
- tableRenames = [];
1911
- columnRenames = [];
1912
- constructor(input) {
1913
- this.#fromContract = input.fromContract;
1914
- this.#contract = input.contract;
1915
- this.#policy = input.policy;
1916
- this.#target = input.target;
1917
- this.#ownership = input.ownership;
1918
- }
1919
- /** Plans one statement; the result is the operations it accounts for. */
1920
- plan(statement) {
1921
- switch (statement.entity) {
1922
- case "namespace": return planned(this.#planNamespace(statement));
1923
- case "model": return planned(this.#planModel(statement));
1924
- case "field": return planned(this.#planField(statement));
1925
- case "enumValue":
1926
- case "valueObjectField": return ok(PLANNED_WITH_DIFF);
1927
- }
1928
- }
1929
- /** Where a table of the origin is in the working schema, after the renames planned so far. */
1930
- #current(origin) {
1931
- const table = this.#renamedTables.get(tableKey(origin)) ?? origin;
1932
- return {
1933
- namespaceId: this.#renamedNamespaces.get(table.namespaceId) ?? table.namespaceId,
1934
- table: table.table
1935
- };
1936
- }
1937
- #planNamespace(statement) {
1938
- const rename = {
1939
- from: statement.from,
1940
- to: statement.to
1728
+ /** The columns of the destination, in managed tables the working schema has, that hold a model field. */
1729
+ function storedColumns(contract, tables) {
1730
+ const found = /* @__PURE__ */ new Map();
1731
+ for (const namespace of Object.values(contract.domain.namespaces)) for (const model of Object.values(namespace.models)) {
1732
+ const { storage } = model;
1733
+ if (!isSqlModelStorage(storage)) continue;
1734
+ const location = {
1735
+ namespaceId: storage.namespaceId,
1736
+ table: storage.table
1941
1737
  };
1942
- const label = `Cannot rename namespace "${rename.from}" to "${rename.to}"`;
1943
- const namespaces = this.#target.namespaces;
1944
- if (namespaces === void 0) return notOk(withoutNamespacesRefused(statement, label));
1945
- const movePerModel = `--rename ${rename.from}.<Model>:${rename.to}.<Model>`;
1946
- const refusal = namespaces.namespaceRenameRefusal(rename);
1947
- if (refusal !== void 0) return notOk(statementRefused(statement, `${label}: ${refusal.reason}`, refusal.fix, void 0));
1948
- const otherSpace = this.#ownership === void 0 ? void 0 : otherSpaceDeclaring(this.#ownership, rename.from);
1949
- if (otherSpace !== void 0) return notOk(statementRefused(statement, `${label}: contract space "${otherSpace}" also declares it`, `Renaming the namespace would rename it under contract space "${otherSpace}" too, whose contract still names it "${rename.from}". Leave out this statement, or move each model with ${movePerModel} instead.`, void 0));
1950
- const tables = Object.keys(this.#contract.storage.namespaces[rename.to]?.entries.table ?? {});
1951
- for (const table of tables) {
1952
- const controlPolicy = tableControlPolicy(this.#contract, {
1953
- namespaceId: rename.to,
1954
- table
1738
+ if (tableControlPolicy(contract, location) !== "managed") continue;
1739
+ for (const [fieldName, field] of Object.entries(model.fields)) {
1740
+ const column = storage.fields[fieldName]?.column;
1741
+ if (column === void 0) continue;
1742
+ if (!tables.hasColumn(storage.namespaceId, storage.table, column)) continue;
1743
+ found.set(JSON.stringify([
1744
+ storage.namespaceId,
1745
+ storage.table,
1746
+ column
1747
+ ]), {
1748
+ ...location,
1749
+ column,
1750
+ field
1955
1751
  });
1956
- if (controlPolicy === "managed") continue;
1957
- return notOk(statementRefused(statement, `${label}: table "${table}" has control policy "${controlPolicy}"`, `Statements rename only namespaces whose tables all have control policy "managed"; table "${table}" is "${controlPolicy}". Make the change in the database yourself and leave out this statement.`, {
1958
- namespaceId: rename.to,
1959
- table
1960
- }));
1961
1752
  }
1962
- const schemaTables = this.#target.tables();
1963
- if (!schemaTables.hasNamespace(rename.from)) return notOk(statementRefused(statement, `${label}: the schema being planned from has no namespace "${rename.from}"`, `The database has no namespace "${rename.from}", although the contract it was last updated to names it, ${DRIFTED}`, void 0));
1964
- if (schemaTables.hasNamespace(rename.to)) return notOk(statementRefused(statement, `${label}: the database already has a namespace "${rename.to}"`, `The database already has a namespace "${rename.to}", which the contract it was last updated to does not declare. If it holds nothing, drop or rename it in the database yourself; otherwise move each model with ${movePerModel} instead of this statement.`, void 0));
1965
- const planned = this.#emit(statement, label, void 0, namespaces.renameNamespaceCall(rename));
1966
- if (planned.ok) this.#renamedNamespaces.set(rename.from, rename.to);
1967
- return planned;
1968
- }
1969
- #controlPolicyRefusal(statement, label, destinationTable) {
1970
- const controlPolicy = tableControlPolicy(this.#contract, destinationTable);
1971
- if (controlPolicy === "managed") return void 0;
1972
- return statementRefused(statement, `${label}: the table's control policy is "${controlPolicy}"`, `Statements rename only tables, and columns of tables, whose control policy is "managed"; table "${destinationTable.table}" is "${controlPolicy}". Make the change in the database yourself and leave out this statement.`, destinationTable);
1973
- }
1974
- #emit(statement, label, location, call) {
1975
- const refused = operationsOf(call).map((operation) => operation.operationClass).find((operationClass) => !this.#policy.allowedOperationClasses.includes(operationClass));
1976
- if (refused !== void 0) return notOk(statementRefused(statement, `${label}: the plan does not allow "${refused}" operations`, `The rename produces a "${refused}" operation, and this command plans only ${this.#policy.allowedOperationClasses.map((c) => `"${c}"`).join(", ")} operations. Leave out this statement, or make the change with a command that allows "${refused}" operations, such as migration plan.`, location, refused));
1977
- this.#target.apply(call);
1978
- this.calls.push(call);
1979
- const first = this.#operationCount;
1980
- this.#operationCount += operationsOf(call).length;
1981
- return ok(operationsOf(call).map((_, offset) => first + offset));
1982
1753
  }
1983
- #planModel(statement) {
1984
- const worked = modelRenameStorageEffect(statement, this.#fromContract, this.#contract);
1985
- if (!worked.ok) return notOk(statementRefused(statement, `Model "${modelDisplayName(worked.failure.model)}" has no table in its contract`, `A model rename renames the model's table, and model "${modelDisplayName(worked.failure.model)}" has none in its contract. Leave out this statement.`, void 0));
1986
- const effect = worked.value;
1987
- if (effect.kind === "unchanged") return ok([]);
1988
- const [origin, destination] = effect.kind === "moveNamespace" ? [effect.from, effect.to] : [{
1989
- namespaceId: effect.rename.namespaceId,
1990
- table: effect.rename.from
1991
- }, {
1992
- namespaceId: effect.rename.namespaceId,
1993
- table: effect.rename.to
1994
- }];
1995
- const current = this.#current(origin);
1996
- if (current.namespaceId === destination.namespaceId) {
1997
- if (current.table === destination.table) return ok([]);
1998
- return this.#planTableRename(statement, origin, {
1999
- namespaceId: destination.namespaceId,
2000
- from: current.table,
2001
- to: destination.table
1754
+ return [...found.values()];
1755
+ }
1756
+ /**
1757
+ * Finds every place the destination stores a value object: each column of the working schema, in a
1758
+ * managed table, whose field holds it, at every path to its objects, nested or in lists. The paths
1759
+ * are written with the destination's names. A column whose paths cannot be listed, because it holds
1760
+ * the value object through a value object that contains itself, a union or a dictionary, is the
1761
+ * failure.
1762
+ */
1763
+ function valueObjectPlaces(contract, tables) {
1764
+ const columns = storedColumns(contract, tables);
1765
+ return (target) => {
1766
+ const places = [];
1767
+ for (const column of columns) {
1768
+ const reach = reachOf(contract.storage, column.field, target);
1769
+ if (reach.kind !== "paths") return notOk({
1770
+ column,
1771
+ reach
1772
+ });
1773
+ for (const steps of reach.paths) places.push({
1774
+ namespaceId: column.namespaceId,
1775
+ table: column.table,
1776
+ column: column.column,
1777
+ steps
2002
1778
  });
2003
1779
  }
2004
- return this.#planMove(statement, origin, current, destination);
1780
+ return ok(places);
1781
+ };
1782
+ }
1783
+ function fieldChanges(fromContract, contract, statements) {
1784
+ const renamedNamespaces = /* @__PURE__ */ new Map();
1785
+ const renames = [];
1786
+ for (const statement of statements) {
1787
+ if (statement.kind !== "rename") continue;
1788
+ if (statement.entity === "namespace") renamedNamespaces.set(statement.from, statement.to);
1789
+ if (statement.entity === "valueObjectField") renames.push(statement);
2005
1790
  }
2006
- #planTableRename(statement, origin, rename) {
2007
- const destinationTable = {
2008
- namespaceId: rename.namespaceId,
2009
- table: rename.to
1791
+ const changes = [];
1792
+ for (const { coordinate, valueObject } of valueObjectsWithCoordinates(fromContract.storage)) {
1793
+ const target = {
1794
+ ...coordinate,
1795
+ namespaceId: renamedNamespaces.get(coordinate.namespaceId) ?? coordinate.namespaceId
2010
1796
  };
2011
- const label = `Cannot rename table "${rename.from}" to "${rename.to}"`;
2012
- const policyRefusal = this.#controlPolicyRefusal(statement, label, destinationTable);
2013
- if (policyRefusal !== void 0) return notOk(policyRefusal);
2014
- const checked = checkTableRename(this.#target.tables(), this.#contract, rename);
2015
- if (!checked.ok) return notOk(tableRenameRefused(statement, label, rename, checked.failure));
2016
- const planned = this.#emit(statement, label, destinationTable, this.#target.renameTableCall(rename));
2017
- if (planned.ok) {
2018
- this.tableRenames.push(rename);
2019
- this.#renamedTables.set(tableKey(origin), destinationTable);
2020
- this.#originTables.set(tableKey(origin), origin);
1797
+ const destination = valueObjectAt(contract.storage, target);
1798
+ if (destination === void 0) continue;
1799
+ for (const from of Object.keys(valueObject.fields)) {
1800
+ const valueObjectField = {
1801
+ namespaceId: asNamespaceId(coordinate.namespaceId),
1802
+ valueObject: coordinate.entityName,
1803
+ field: from
1804
+ };
1805
+ const statement = renames.find((rename) => rename.from.namespaceId === valueObjectField.namespaceId && rename.from.valueObject === valueObjectField.valueObject && rename.from.field === from);
1806
+ if (statement !== void 0) changes.push({
1807
+ valueObjectField,
1808
+ target,
1809
+ from,
1810
+ to: statement.to.field,
1811
+ statement
1812
+ });
1813
+ else if (!Object.hasOwn(destination.fields, from)) changes.push({
1814
+ valueObjectField,
1815
+ target,
1816
+ from,
1817
+ to: void 0,
1818
+ statement: void 0
1819
+ });
2021
1820
  }
2022
- return planned;
2023
1821
  }
2024
- /**
2025
- * Moves the table to the destination namespace under its own name, creating the namespace first
2026
- * when the working schema lacks it, then renames it there when the destination names it
2027
- * differently. The statement accounts for the move and the rename, not the namespace's creation.
2028
- */
2029
- #planMove(statement, origin, from, to) {
2030
- const label = `Cannot move table "${from.table}" from ${namespaceText(from.namespaceId)} to ${namespaceText(to.namespaceId)}`;
2031
- const namespaces = this.#target.namespaces;
2032
- if (namespaces === void 0) return notOk(withoutNamespacesRefused(statement, label));
2033
- if (to.namespaceId === UNBOUND_NAMESPACE_ID) return notOk(statementRefused(statement, `Cannot move table "${from.table}" from ${namespaceText(from.namespaceId)} to the unbound namespace: the unbound namespace has no fixed place in the database`, `A table of the unbound namespace lives wherever the connection that uses it looks, so a migration cannot move a table there. Move the table yourself and leave out this statement, or keep the model in ${namespaceText(from.namespaceId)}.`, from));
2034
- const moved = {
2035
- namespaceId: to.namespaceId,
2036
- table: from.table
2037
- };
2038
- const policyRefusal = this.#controlPolicyRefusal(statement, label, to);
2039
- if (policyRefusal !== void 0) return notOk(policyRefusal);
2040
- const tables = this.#target.tables();
2041
- if (!tables.hasTable(from.namespaceId, from.table)) return notOk(statementRefused(statement, `${label}: the schema being planned from has no table "${qualifiedTable(from)}"`, `The database has no table "${qualifiedTable(from)}", although the contract it was last updated to names it, ${DRIFTED}`, from));
2042
- const [taken] = [...tables.tablesNamed(to.namespaceId, from.table), ...tables.tablesNamed(to.namespaceId, to.table)];
2043
- if (taken !== void 0) {
2044
- const takenTable = qualifiedTable({
2045
- namespaceId: to.namespaceId,
2046
- table: taken
2047
- });
2048
- return notOk(statementRefused(statement, `${label}: the schema being planned from already has a table "${takenTable}"`, `A move cannot replace a table that already exists. Rename, move or drop table "${takenTable}" first, or leave out this statement.`, {
2049
- namespaceId: to.namespaceId,
2050
- table: taken
1822
+ return changes;
1823
+ }
1824
+ function columnText(column) {
1825
+ return `column "${column.column}" of "${column.table}"`;
1826
+ }
1827
+ function refused(change, fromContract, contract, column, reason, why) {
1828
+ const from = valueObjectFieldStatementText(fromContract, change.valueObjectField);
1829
+ if (change.statement === void 0) return {
1830
+ kind: "unsupportedOperation",
1831
+ summary: `Cannot remove value object field "${from}": ${reason}`,
1832
+ why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${columnText(column)}`)}`
1833
+ };
1834
+ return {
1835
+ kind: "statementRefused",
1836
+ summary: `Cannot rename value object field "${from}" to "${valueObjectFieldStatementText(contract, change.statement.to)}": ${reason}`,
1837
+ why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${columnText(column)}`)}`,
1838
+ refusedStatement: change.statement
1839
+ };
1840
+ }
1841
+ function reachRefusal(reach, column, change, contracts) {
1842
+ if (reach.kind === "containsItself") return refused(change, contracts.fromContract, contracts.contract, column, `${columnText(column)} holds it inside value object "${reach.valueObject}", which contains itself, so the JSON can hold it at any depth`, "The plan rewrites a key at every path from a column to its value object, and a value object that contains itself has no last path.");
1843
+ return refused(change, contracts.fromContract, contracts.contract, column, `${columnText(column)} holds a ${reach.kind} of value objects`, "The plan rewrites a key only in a column that holds a value object or a list of them.");
1844
+ }
1845
+ /**
1846
+ * The key rewrites of value object fields a plan makes. A value object of the origin is compared,
1847
+ * field by field, with the value object of the same name in the destination: a rename statement
1848
+ * renames a field's key, and a field the destination lacks that no statement renames is removed,
1849
+ * which the plan asks about. Each rewrite acts on every column of the working schema whose field
1850
+ * holds the value object, at every path to its objects, nested or in lists. The paths are written
1851
+ * with the destination's names, so an outer rename runs before an inner one: the rewrites come out
1852
+ * ordered by the depth of their paths. A path through a value object that contains itself, or a
1853
+ * column that holds a union or a dictionary of value objects, is refused. With no origin contract,
1854
+ * nothing is known to have changed.
1855
+ */
1856
+ function planValueObjectFieldRewrites(input) {
1857
+ const { fromContract, contract } = input;
1858
+ if (fromContract === null) return ok([]);
1859
+ const changes = fieldChanges(fromContract, contract, input.statements);
1860
+ if (changes.length === 0) return ok([]);
1861
+ const placesOf = valueObjectPlaces(contract, input.tables);
1862
+ const rewrites = [];
1863
+ for (const change of changes) {
1864
+ const places = placesOf(change.target);
1865
+ if (!places.ok) {
1866
+ const { reach, column } = places.failure;
1867
+ return notOk(reachRefusal(reach, column, change, {
1868
+ fromContract,
1869
+ contract
2051
1870
  }));
2052
1871
  }
2053
- for (const call of namespaces.createNamespaceCalls(to.namespaceId)) {
2054
- const created = this.#emit(statement, label, moved, call);
2055
- if (!created.ok) return created;
2056
- }
2057
- const planned = this.#emit(statement, label, moved, namespaces.moveTableCall({
2058
- table: from.table,
2059
- from: from.namespaceId,
2060
- to: to.namespaceId
2061
- }));
2062
- if (!planned.ok) return planned;
2063
- this.#renamedTables.set(tableKey(origin), moved);
2064
- this.#originTables.set(tableKey(origin), origin);
2065
- if (to.table === from.table) return planned;
2066
- const renamed = this.#planTableRename(statement, origin, {
2067
- namespaceId: to.namespaceId,
2068
- from: from.table,
2069
- to: to.table
1872
+ for (const { steps, ...place } of places.value) rewrites.push({
1873
+ depth: steps.length,
1874
+ rewrite: {
1875
+ valueObjectField: change.valueObjectField,
1876
+ ...place,
1877
+ path: jsonPathText([...steps, {
1878
+ kind: "member",
1879
+ name: change.from
1880
+ }]),
1881
+ to: change.to,
1882
+ statement: change.statement
1883
+ }
2070
1884
  });
2071
- if (!renamed.ok) return renamed;
2072
- return ok([...planned.value, ...renamed.value]);
2073
1885
  }
2074
- #planField(statement) {
2075
- const worked = fieldRenameStorageEffect(statement, this.#fromContract, this.#contract);
2076
- if (!worked.ok && worked.failure.kind === "noTable") return notOk(statementRefused(statement, `Model "${modelDisplayName(worked.failure.model)}" has no table in its contract`, `A field rename renames the field's column, and model "${modelDisplayName(worked.failure.model)}" has no table in its contract. Leave out this statement.`, void 0));
2077
- if (!worked.ok) return notOk(statementRefused(statement, `Field "${modelDisplayName(statement.from)}.${statement.from.field}" has a column on one side only of ${describeMigrationStatement(statement, this.#fromContract, this.#contract)}`, "A field rename renames a column or changes nothing in storage, and this field gains or loses its column. Leave out this statement and plan the change without it.", void 0));
2078
- const effect = worked.value;
2079
- if (effect.kind === "unchanged") return ok([]);
2080
- const current = this.#current(effect.table);
2081
- const table = current.table;
2082
- const destinationTable = modelTable(this.#contract, statement.to);
2083
- if (destinationTable !== void 0 && (destinationTable.namespaceId !== current.namespaceId || destinationTable.table !== table)) {
2084
- const tableRename = {
2085
- namespaceId: current.namespaceId,
2086
- from: table,
2087
- to: destinationTable.table
1886
+ return ok([...rewrites].sort((left, right) => left.depth - right.depth).map(({ rewrite }) => rewrite));
1887
+ }
1888
+ function sameValue(left, right) {
1889
+ return JSON.stringify(left) === JSON.stringify(right);
1890
+ }
1891
+ function enumOf(contract, namespaceId, name) {
1892
+ return contract.domain.namespaces[namespaceId]?.enum?.[name];
1893
+ }
1894
+ /** The columns of the destination whose fields the enum types, in managed tables. */
1895
+ function columnsTypedBy(contract, namespaceId, enumName) {
1896
+ const found = /* @__PURE__ */ new Map();
1897
+ for (const namespace of Object.values(contract.domain.namespaces)) for (const model of Object.values(namespace.models)) {
1898
+ const { storage } = model;
1899
+ if (!isSqlModelStorage(storage)) continue;
1900
+ for (const [fieldName, field] of Object.entries(model.fields)) {
1901
+ const ref = field.valueSet;
1902
+ if (ref === void 0 || ref.plane !== "domain" || ref.entityKind !== "enum" || ref.spaceId !== void 0 || ref.namespaceId !== namespaceId || ref.entityName !== enumName) continue;
1903
+ const column = storage.fields[fieldName]?.column;
1904
+ if (column === void 0) continue;
1905
+ const stored = contract.storage.namespaces[storage.namespaceId]?.entries.table?.[storage.table]?.columns[column];
1906
+ if (stored === void 0) continue;
1907
+ const location = {
1908
+ namespaceId: storage.namespaceId,
1909
+ table: storage.table
2088
1910
  };
2089
- const model = modelDisplayName(statement.to);
2090
- const fieldText = `${model}.${statement.from.field}:${model}.${statement.to.field}`;
2091
- return notOk(statementRefused(statement, `Cannot rename column "${table}"."${effect.from}": the model's table changes from "${table}" to "${destinationTable.table}", and no statement renames the table`, `The column would be renamed on a table the plan then drops and creates under the new name, and a migration that only changes the table name is planned the same way. With migration plan, rename the table by hand in its own migration first. Change the contract so that only the table name changes, and run prisma contract emit. Run prisma migration new --name <name> --from <hash of the migration the database is at>, add ${this.#target.renderTableRename(tableRename)} to the operations of its migration.ts, and run node on that migration.ts to write its ops.json. Then change the contract to its final form, emit it, and plan the field rename with --from that migration. With db update, change the contract so that only the table name changes, and run prisma contract emit. Rename the table in the database yourself with ${this.#target.tableRenameByHand(tableRename).join("; ")}, check that prisma db update --dry-run plans no drop of a table or column, and run prisma db update to store that contract. Then emit the final contract and run prisma db update --rename ${fieldText}.`, {
2092
- namespaceId: current.namespaceId,
2093
- table,
2094
- column: effect.from
2095
- }));
2096
- }
2097
- const rename = {
2098
- namespaceId: current.namespaceId,
2099
- table,
2100
- from: effect.from,
2101
- to: effect.to
2102
- };
2103
- const tableLocation = {
2104
- namespaceId: rename.namespaceId,
2105
- table
2106
- };
2107
- const label = `Cannot rename column "${table}"."${rename.from}" to "${rename.to}"`;
2108
- const policyRefusal = this.#controlPolicyRefusal(statement, label, tableLocation);
2109
- if (policyRefusal !== void 0) return notOk(policyRefusal);
2110
- const checked = checkColumnRename(this.#target.tables(), this.#contract, rename);
2111
- if (!checked.ok) return notOk(columnRenameRefused(statement, label, rename, checked.failure));
2112
- const planned = this.#emit(statement, label, {
2113
- ...tableLocation,
2114
- column: rename.from
2115
- }, this.#target.renameColumnCall(rename));
2116
- if (planned.ok) {
2117
- this.columnRenames.push(rename);
2118
- this.#renamedColumns.push({
2119
- origin: effect.table,
2120
- from: effect.from,
2121
- to: effect.to
1911
+ if (tableControlPolicy(contract, location) !== "managed") continue;
1912
+ found.set(JSON.stringify([
1913
+ storage.namespaceId,
1914
+ storage.table,
1915
+ column
1916
+ ]), {
1917
+ ...location,
1918
+ column,
1919
+ codecRef: buildColumnCodecRef(stored, void 0),
1920
+ many: stored.many !== false && stored.many !== void 0,
1921
+ member: void 0
2122
1922
  });
2123
1923
  }
2124
- return planned;
2125
- }
2126
- /** The origins of the working schema's tables and columns, as the statements left them. */
2127
- origins() {
2128
- const sameTable = (left, right) => left.namespaceId === right.namespaceId && left.table === right.table;
2129
- return {
2130
- originTable: (current) => {
2131
- for (const origin of this.#originTables.values()) if (sameTable(this.#current(origin), current)) return origin;
2132
- for (const [origin, renamed] of this.#renamedNamespaces) if (renamed === current.namespaceId) return {
2133
- namespaceId: origin,
2134
- table: current.table
2135
- };
2136
- return current;
2137
- },
2138
- originColumn: (origin, column) => this.#renamedColumns.find((renamed) => sameTable(renamed.origin, origin) && renamed.to === column)?.from ?? column
2139
- };
2140
1924
  }
2141
- };
1925
+ return [...found.values()];
1926
+ }
1927
+ function isMany$1(many) {
1928
+ return many !== void 0 && many !== false;
1929
+ }
2142
1930
  /**
2143
- * Plans the statements against a target's working schema, namespace renames first and the rest in
2144
- * the order given: model and field statements name the origin and destination contracts, so the
2145
- * namespace renames' place among them does not matter. Each model rename becomes a table rename
2146
- * and each field rename a column rename, computed against the schema earlier statements left, then
2147
- * applied to it. The first statement that cannot be planned fails the whole
2148
- * plan with a `statementRefused` conflict that carries the statement.
1931
+ * The members of value objects, in the destination's columns, that the enum's storage value set
1932
+ * types: each column and path where the destination stores the value object.
2149
1933
  */
2150
- function planStatements(input) {
2151
- const { fromContract } = input;
2152
- const [first] = input.statements;
2153
- if (first === void 0) return ok({
2154
- calls: [],
2155
- tableRenames: [],
2156
- columnRenames: [],
2157
- plannedStatements: [],
2158
- origins: NO_RENAMED_ORIGINS
2159
- });
2160
- if (fromContract === null) return notOk(statementRefused(first, "Statements need an origin contract, and this plan has none", "A statement names models and fields of the origin contract, and this plan has none. Plan from a contract that has the old names, or leave out the statement.", void 0));
2161
- const planner = new StatementPlanner({
2162
- ...input,
2163
- fromContract,
2164
- ownership: input.ownership
2165
- });
2166
- const plannedStatements = [];
2167
- const namespacesFirst = [...input.statements.filter((statement) => statement.entity === "namespace"), ...input.statements.filter((statement) => statement.entity !== "namespace")];
2168
- for (const statement of namespacesFirst) {
2169
- const operations = planner.plan(statement);
2170
- if (!operations.ok) return operations;
2171
- plannedStatements.push({
2172
- statement,
2173
- operations: operations.value
1934
+ function membersTypedBy(contract, placesOf, namespaceId, enumName) {
1935
+ const found = [];
1936
+ for (const { coordinate, valueObject } of valueObjectsWithCoordinates(contract.storage)) {
1937
+ const typed = Object.entries(valueObject.fields).filter(([, field]) => field.valueSet !== void 0 && field.valueSet.spaceId === void 0 && field.valueSet.namespaceId === namespaceId && field.valueSet.entityName === enumName);
1938
+ if (typed.length === 0) continue;
1939
+ const places = placesOf(coordinate);
1940
+ if (!places.ok) return places;
1941
+ for (const [name, field] of typed) for (const { steps, ...place } of places.value) found.push({
1942
+ ...place,
1943
+ codecRef: void 0,
1944
+ many: false,
1945
+ member: {
1946
+ path: jsonPathText([
1947
+ ...steps,
1948
+ {
1949
+ kind: "member",
1950
+ name
1951
+ },
1952
+ ...isMany$1(field.many) ? [{ kind: "wildcard" }] : []
1953
+ ]),
1954
+ nullable: field.nullable
1955
+ }
2174
1956
  });
2175
1957
  }
2176
- return ok({
2177
- calls: planner.calls,
2178
- tableRenames: planner.tableRenames,
2179
- columnRenames: planner.columnRenames,
2180
- plannedStatements,
2181
- origins: planner.origins()
1958
+ return ok(found);
1959
+ }
1960
+ function enumText(enums, value) {
1961
+ return modelStatementText(enums.fromContract, {
1962
+ namespaceId: value.namespaceId,
1963
+ model: value.enum
2182
1964
  });
2183
1965
  }
2184
- /**
2185
- * The column of each field a convert or backfill statement names, as the destination contract
2186
- * stores it. These statements rename nothing, so the strategies that plan a field's change read
2187
- * them instead of the working schema. A field with no column has none to list.
2188
- */
2189
- function fieldStatementColumns(statements, contract) {
2190
- const columnsOf = (kind) => statements.flatMap((statement) => {
2191
- if (statement.kind !== kind || statement.entity !== "field") return [];
2192
- const table = modelTable(contract, statement.field);
2193
- const column = fieldColumn(contract, statement.field);
2194
- return table === void 0 || column === void 0 ? [] : [{
2195
- ...table,
2196
- column,
2197
- field: statement.field,
2198
- text: fieldStatementText(contract, statement.field)
2199
- }];
2200
- });
1966
+ /** How a refusal names a change that no statement asks for: the removal of a value, or a member's new stored value. */
1967
+ function changeText(enums, change) {
1968
+ const member = enumValueStatementText(enums.fromContract, change.enumValue);
1969
+ return change.to === void 0 ? `Cannot remove enum value "${member}"` : `Cannot change the stored value of enum value "${member}" from ${enums.text(change.from)} to ${enums.text(change.to)}`;
1970
+ }
1971
+ function unlistedRefusal(contract, enums, changes, { column, reach }) {
1972
+ const where = `column "${column.column}" of "${column.table}"`;
1973
+ const reason = reach.kind === "containsItself" ? `${where} holds it inside value object "${reach.valueObject}", which contains itself, so the JSON can hold it at any depth` : `${where} holds a ${reach.kind} of value objects`;
1974
+ const why = reach.kind === "containsItself" ? "The plan rewrites an enum value inside JSON at every path from a column to its member, and a value object that contains itself has no last path." : "The plan rewrites an enum value inside JSON only in a column that holds a value object or a list of them.";
1975
+ const [first] = changes;
1976
+ invariant(first !== void 0, "an enum with no changed value plans no rewrite to refuse");
1977
+ const advice = `This change cannot be planned yet. Until it can, keep the members and stored values of enum "${enumText(enums, first.enumValue)}" as the origin contract has them, and plan again.`;
1978
+ const statement = changes.find((change) => change.statement !== void 0)?.statement;
1979
+ if (statement === void 0) return {
1980
+ kind: "unsupportedOperation",
1981
+ summary: `${changeText(enums, first)}: ${reason}`,
1982
+ why: `${why} ${advice}`
1983
+ };
2201
1984
  return {
2202
- convert: columnsOf("convert"),
2203
- backfill: columnsOf("backfill")
1985
+ kind: "statementRefused",
1986
+ summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(contract, statement.to)}": ${reason}`,
1987
+ why: `${why} ${advice}`,
1988
+ refusedStatement: statement
2204
1989
  };
2205
1990
  }
2206
- /**
2207
- * A conflict for the first backfill statement that names a field the origin model does not have and
2208
- * whose column has a default: the default fills the existing rows when the column is added, so the
2209
- * statement has nothing to fill. A field already in the origin keeps its backfill, since a default
2210
- * does not fill the rows that hold NULL when the column becomes required.
2211
- */
2212
- function backfillOfDefaultedField(statements, fromContract, contract) {
2213
- for (const statement of statements) {
2214
- if (statement.kind !== "backfill" || statement.entity !== "field" || fromContract === null) continue;
2215
- const originModel = sqlModelStorage(fromContract, statement.field);
2216
- if (originModel === void 0 || Object.hasOwn(originModel.fields, statement.field.field)) continue;
2217
- const table = modelTable(contract, statement.field);
2218
- const column = fieldColumn(contract, statement.field);
2219
- if (table === void 0 || column === void 0) continue;
2220
- if ((contract.storage.namespaces[table.namespaceId]?.entries.table?.[table.table]?.columns[column])?.default === void 0) continue;
2221
- return statementRefused(statement, `${describeMigrationStatement(statement, fromContract, contract)}: the field is new and has a default`, "The default fills the existing rows when the column is added, so there is nothing to backfill. Leave out the --backfill statement.", {
2222
- namespaceId: table.namespaceId,
2223
- table: table.table,
2224
- column
2225
- });
2226
- }
1991
+ function isStoredEnumValue(value) {
1992
+ return typeof value === "string" || typeof value === "number";
2227
1993
  }
2228
- /**
2229
- * The operations of a statement the statement planner does not take: a value object field backfill
2230
- * and a variant convert are planned with the diff; a field convert or backfill accounts for none.
2231
- */
2232
- function operationsOutsideStatementPlanner(statement) {
2233
- if (statement.kind === "rename") return plannedAt([]);
2234
- switch (statement.entity) {
2235
- case "field": return plannedAt([]);
2236
- case "valueObjectField":
2237
- case "model": return PLANNED_WITH_DIFF;
1994
+ /** A stored value as messages write it: a number without quotes, as the enum's codec reads it. */
1995
+ function valueText(value, codec) {
1996
+ const built = codecForRef(codec.codecs, codec.codecRef);
1997
+ if (built === void 0) return JSON.stringify(value);
1998
+ try {
1999
+ const read = readContractValue(built, value, codec.codecRef.typeParams);
2000
+ return typeof read === "number" || typeof read === "bigint" ? String(read) : JSON.stringify(value);
2001
+ } catch {
2002
+ return JSON.stringify(value);
2238
2003
  }
2239
2004
  }
2240
- /**
2241
- * Every statement of a plan in the order given, with the operations it accounts for: a planned
2242
- * statement's from `planned`, and a statement planned with the diff's from
2243
- * `operationIndexesPlannedWithDiff`, which finds them among the target's whole plan. A model rename
2244
- * takes both, since renaming a variant whose discriminator value changed also rewrites the value.
2245
- */
2246
- function appliedStatementsInOrder(statements, planned, operationIndexesPlannedWithDiff) {
2247
- return statements.map((statement) => {
2248
- const operations = planned.find((entry) => entry.statement === statement)?.operations ?? operationsOutsideStatementPlanner(statement);
2249
- if (operations.kind === "plannedWithDiff") return {
2250
- statement,
2251
- operationIndexes: operationIndexesPlannedWithDiff(statement)
2252
- };
2253
- return {
2254
- statement,
2255
- operationIndexes: statement.kind === "rename" && statement.entity === "model" ? [...operations.operationIndexes, ...operationIndexesPlannedWithDiff(statement)].sort((left, right) => left - right) : operations.operationIndexes
2256
- };
2257
- });
2005
+ function unsupportedValue(contract, value, stored) {
2006
+ const text = enumValueStatementText(contract, value);
2007
+ return {
2008
+ kind: "unsupportedOperation",
2009
+ summary: `Cannot rewrite enum value "${text}": its stored value ${JSON.stringify(stored)} is not a string or a number`,
2010
+ why: `The plan rewrites the rows that hold a removed, renamed or changed enum value, and it compares only string and number values. Rewrite the rows that hold enum value "${text}" yourself, then plan again.`
2011
+ };
2258
2012
  }
2259
- const WILDCARD = { kind: "wildcard" };
2260
- function isMany$2(many) {
2261
- return many !== void 0 && many !== false;
2013
+ function stillStoredRefusal(statement, enums, stored, holder) {
2014
+ const holderText = enumValueStatementText(enums.contract, {
2015
+ ...statement.to,
2016
+ member: holder
2017
+ });
2018
+ const value = enums.text(stored);
2019
+ return {
2020
+ kind: "statementRefused",
2021
+ summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(enums.contract, statement.to)}": the destination enum still stores ${value}, as enum value "${holderText}"`,
2022
+ why: `A rename changes the stored value in every row that holds it, so the rows that hold ${value} for "${holderText}" would change too. Leave out this statement.`,
2023
+ refusedStatement: statement
2024
+ };
2262
2025
  }
2263
- function requiredValueObject(storage, reference) {
2264
- const valueObject = valueObjectAt(storage, reference);
2265
- invariant(valueObject !== void 0, `value object "${reference.entityName}" in namespace "${reference.namespaceId}" is not in storage; the contract validators refuse a reference to a missing value object`);
2266
- return valueObject;
2026
+ function mergingRefusal(statement, enums, from, to, holder) {
2027
+ const holderText = enumValueStatementText(enums.fromContract, {
2028
+ ...statement.from,
2029
+ member: holder
2030
+ });
2031
+ return {
2032
+ kind: "statementRefused",
2033
+ summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(enums.contract, statement.to)}": the origin enum already stores ${enums.text(to)}, as enum value "${holderText}"`,
2034
+ why: `A rename changes ${enums.text(from)} to ${enums.text(to)} in every row that holds it, which merges its data with the data of "${holderText}". Leave out this statement. To merge them on purpose, plan the change with migration plan and write this.replaceStoredValue(...) in the migration.ts it writes.`,
2035
+ refusedStatement: statement
2036
+ };
2267
2037
  }
2268
- function nestedReferences(valueObject) {
2269
- return Object.values(valueObject.fields).flatMap(({ type }) => type.kind === "valueObject" ? [type] : []);
2038
+ function cycleMoves(cycle) {
2039
+ const [first, ...rest] = cycle.map((change) => {
2040
+ const { to } = change;
2041
+ invariant(to !== void 0, "a cycle of stored values moves each value to another");
2042
+ return {
2043
+ ...change,
2044
+ to
2045
+ };
2046
+ });
2047
+ invariant(first !== void 0, "a cycle has a change");
2048
+ return [first, ...rest];
2270
2049
  }
2271
- function containsItself(storage, from) {
2272
- const own = /* @__PURE__ */ new Set([referenceKey(from)]);
2273
- return nestedReferences(requiredValueObject(storage, from)).some((nested) => reachesAny(storage, nested, own));
2050
+ /** The enum value a change gives its new stored value, as the destination contract names it. */
2051
+ function destinationMemberText(enums, change) {
2052
+ return change.statement === void 0 ? enumValueStatementText(enums.fromContract, change.enumValue) : enumValueStatementText(enums.contract, change.statement.to);
2274
2053
  }
2275
- /** The paths from `steps` to each object of `target` inside an object of `from`. */
2276
- function pathsWithin(storage, from, steps, target) {
2277
- const targets = /* @__PURE__ */ new Set([referenceKey(target)]);
2278
- if (containsItself(storage, from)) return reachesAny(storage, from, targets) ? {
2279
- kind: "containsItself",
2280
- valueObject: from.entityName
2281
- } : {
2282
- kind: "paths",
2283
- paths: []
2284
- };
2285
- const paths = referenceKey(from) === referenceKey(target) ? [steps] : [];
2286
- for (const [name, field] of Object.entries(requiredValueObject(storage, from).fields)) {
2287
- if (field.type.kind !== "valueObject") continue;
2288
- const nested = pathsWithin(storage, field.type, [
2289
- ...steps,
2290
- {
2291
- kind: "member",
2292
- name
2293
- },
2294
- ...isMany$2(field.many) ? [WILDCARD] : []
2295
- ], target);
2296
- if (nested.kind !== "paths") return nested;
2297
- paths.push(...nested.paths);
2298
- }
2054
+ const CYCLE_WHY = "The plan rewrites a changed stored value in every row that holds it, one value after another, and no order of the rewrites moves values in a cycle.";
2055
+ /**
2056
+ * The route through a stored value no member stores, which works on both commands: a plan that
2057
+ * gives the first enum value of the cycle that value and the others their new ones, so their
2058
+ * rewrites form a chain, then a plan that gives the first its new value.
2059
+ */
2060
+ function cycleTwoPlans(moves, enums, swap) {
2061
+ const [first, ...rest] = moves;
2062
+ const withStatements = moves.some(({ statement }) => statement !== void 0);
2063
+ const others = joinedList(rest.map((move) => `"${destinationMemberText(enums, move)}" the stored value ${enums.text(move.to)}`));
2064
+ const member = `"${destinationMemberText(enums, first)}"`;
2065
+ return `Make the change in two plans: first give ${member} a stored value no member stores, such as ${enums.text(swap)}, and give ${others}, and plan and apply that${withStatements ? " with the same statements" : ""}; then give ${member} the stored value ${enums.text(first.to)}, and plan again${withStatements ? " without them" : ""}.`;
2066
+ }
2067
+ function cycleRefusal(statement, cycle, enums, taken) {
2068
+ const moves = cycleMoves(cycle);
2069
+ const swap = temporaryValue(moves[0].from, taken);
2070
+ const listed = joinedList(moves.map(({ from, to }) => `${enums.text(from)} to ${enums.text(to)}`));
2299
2071
  return {
2300
- kind: "paths",
2301
- paths
2072
+ kind: "statementRefused",
2073
+ summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(enums.contract, statement.to)}": the renames move stored values in a cycle, ${listed}, and a rewrite of one would overwrite the other before it is read`,
2074
+ why: `${CYCLE_WHY} ${cycleTwoPlans(moves, enums, swap)}`,
2075
+ refusedStatement: statement
2302
2076
  };
2303
2077
  }
2304
- function reachOf(storage, field, target) {
2305
- const targets = /* @__PURE__ */ new Set([referenceKey(target)]);
2306
- const { type } = field;
2307
- if (type.kind === "union") return type.members.some((member) => member.kind === "valueObject" && reachesAny(storage, member, targets)) ? { kind: "union" } : {
2308
- kind: "paths",
2309
- paths: []
2310
- };
2311
- if (type.kind !== "valueObject") return {
2312
- kind: "paths",
2313
- paths: []
2078
+ /** A member that keeps its name and takes the stored value `to`, which `holder` keeps in the origin enum, so their data would merge. */
2079
+ function changeMergingRefusal(change, to, holder, enums) {
2080
+ const member = enumValueStatementText(enums.fromContract, change.enumValue);
2081
+ const holderText = enumValueStatementText(enums.fromContract, {
2082
+ ...change.enumValue,
2083
+ member: holder
2084
+ });
2085
+ const fromText = enums.text(change.from);
2086
+ const toText = enums.text(to);
2087
+ return {
2088
+ kind: "unsupportedOperation",
2089
+ summary: `${changeText(enums, change)}: the origin enum stores ${toText} as enum value "${holderText}"`,
2090
+ why: `A changed stored value is rewritten in every row that holds it, so the rows of "${member}" would hold ${toText} as the rows of "${holderText}" do, and their data would merge. Make the change in two plans: first remove enum value "${holderText}", and plan and apply that; then give "${member}" the stored value ${toText}, and plan again. The first plan asks about the rows that hold ${toText}. If you answer it with --delete ${holderText}, a column that takes no NULL cannot keep those rows: before that plan applies, delete them in the database, or set them to ${fromText} there to merge their data with the data of "${member}" on purpose.`
2314
2091
  };
2315
- if (field.dict === true) return reachesAny(storage, type, targets) ? { kind: "dictionary" } : {
2316
- kind: "paths",
2317
- paths: []
2092
+ }
2093
+ /** Members that keep their names and move stored values in a cycle. */
2094
+ function changeCycleRefusal(cycle, enums, taken) {
2095
+ const moves = cycleMoves(cycle);
2096
+ const [first] = moves;
2097
+ const swap = temporaryValue(first.from, taken);
2098
+ const members = moves.map(({ enumValue }) => `"${enumValueStatementText(enums.fromContract, enumValue)}"`);
2099
+ return {
2100
+ kind: "unsupportedOperation",
2101
+ summary: `Cannot change the stored values of enum "${enumText(enums, first.enumValue)}": enum values ${joinedList(members)} move stored values in a cycle, ${joinedList(moves.map(({ from, to }) => `${enums.text(from)} to ${enums.text(to)}`))}, and a rewrite of one would overwrite the other before it is read`,
2102
+ why: `${CYCLE_WHY} ${cycleTwoPlans(moves, enums, swap)}`
2318
2103
  };
2319
- return pathsWithin(storage, type, isMany$2(field.many) ? [WILDCARD] : [], target);
2320
2104
  }
2321
- /** The columns of the destination, in managed tables the working schema has, that hold a model field. */
2322
- function storedColumns(contract, tables) {
2323
- const found = /* @__PURE__ */ new Map();
2324
- for (const namespace of Object.values(contract.domain.namespaces)) for (const model of Object.values(namespace.models)) {
2325
- const { storage } = model;
2326
- if (!isSqlModelStorage(storage)) continue;
2327
- const location = {
2328
- namespaceId: storage.namespaceId,
2329
- table: storage.table
2330
- };
2331
- if (tableControlPolicy(contract, location) !== "managed") continue;
2332
- for (const [fieldName, field] of Object.entries(model.fields)) {
2333
- const column = storage.fields[fieldName]?.column;
2334
- if (column === void 0) continue;
2335
- if (!tables.hasColumn(storage.namespaceId, storage.table, column)) continue;
2336
- found.set(JSON.stringify([
2337
- storage.namespaceId,
2338
- storage.table,
2339
- column
2340
- ]), {
2341
- ...location,
2342
- column,
2343
- field
2105
+ /**
2106
+ * What changes for each member of the origin enum. A rename statement gives a member the stored
2107
+ * value of the member it names. A member the destination has under the same name takes that
2108
+ * member's stored value, even when another member had it before. A member the destination lacks is
2109
+ * kept when the destination still stores its value, under another name; otherwise its value is
2110
+ * removed.
2111
+ */
2112
+ function valueChanges(enums, enumValueOf, statementOf) {
2113
+ const changes = [];
2114
+ for (const member of enums.originEnum.members) {
2115
+ const enumValue = enumValueOf(member.name);
2116
+ const statement = statementOf(member.name);
2117
+ const named = statement?.to.member ?? member.name;
2118
+ const target = enums.destinationEnum.members.find(({ name }) => name === named);
2119
+ if (target !== void 0) {
2120
+ if (!sameValue(target.value, member.value)) changes.push({
2121
+ enumValue,
2122
+ from: member.value,
2123
+ to: target.value,
2124
+ statement
2344
2125
  });
2126
+ continue;
2345
2127
  }
2128
+ if (statement !== void 0) continue;
2129
+ if (enums.destinationEnum.members.some(({ value }) => sameValue(value, member.value))) continue;
2130
+ changes.push({
2131
+ enumValue,
2132
+ from: member.value,
2133
+ to: void 0,
2134
+ statement: void 0
2135
+ });
2346
2136
  }
2347
- return [...found.values()];
2137
+ return changes;
2348
2138
  }
2349
2139
  /**
2350
- * Finds every place the destination stores a value object: each column of the working schema, in a
2351
- * managed table, whose field holds it, at every path to its objects, nested or in lists. The paths
2352
- * are written with the destination's names. A column whose paths cannot be listed, because it holds
2353
- * the value object through a value object that contains itself, a union or a dictionary, is the
2354
- * failure.
2140
+ * Orders the changes so each runs before the change that writes its old value: in a chain, the
2141
+ * last value moves first. A cycle has no such order; it comes out as the changes in it, from the
2142
+ * first change of the origin enum's order around.
2355
2143
  */
2356
- function valueObjectPlaces(contract, tables) {
2357
- const columns = storedColumns(contract, tables);
2358
- return (target) => {
2359
- const places = [];
2360
- for (const column of columns) {
2361
- const reach = reachOf(contract.storage, column.field, target);
2362
- if (reach.kind !== "paths") return notOk({
2363
- column,
2364
- reach
2365
- });
2366
- for (const steps of reach.paths) places.push({
2367
- namespaceId: column.namespaceId,
2368
- table: column.table,
2369
- column: column.column,
2370
- steps
2371
- });
2372
- }
2373
- return ok(places);
2374
- };
2375
- }
2376
- function fieldChanges(fromContract, contract, statements) {
2377
- const renamedNamespaces = /* @__PURE__ */ new Map();
2378
- const renames = [];
2379
- for (const statement of statements) {
2380
- if (statement.kind !== "rename") continue;
2381
- if (statement.entity === "namespace") renamedNamespaces.set(statement.from, statement.to);
2382
- if (statement.entity === "valueObjectField") renames.push(statement);
2383
- }
2384
- const changes = [];
2385
- for (const { coordinate, valueObject } of valueObjectsWithCoordinates(fromContract.storage)) {
2386
- const target = {
2387
- ...coordinate,
2388
- namespaceId: renamedNamespaces.get(coordinate.namespaceId) ?? coordinate.namespaceId
2389
- };
2390
- const destination = valueObjectAt(contract.storage, target);
2391
- if (destination === void 0) continue;
2392
- for (const from of Object.keys(valueObject.fields)) {
2393
- const valueObjectField = {
2394
- namespaceId: asNamespaceId(coordinate.namespaceId),
2395
- valueObject: coordinate.entityName,
2396
- field: from
2397
- };
2398
- const statement = renames.find((rename) => rename.from.namespaceId === valueObjectField.namespaceId && rename.from.valueObject === valueObjectField.valueObject && rename.from.field === from);
2399
- if (statement !== void 0) changes.push({
2400
- valueObjectField,
2401
- target,
2402
- from,
2403
- to: statement.to.field,
2404
- statement
2405
- });
2406
- else if (!Object.hasOwn(destination.fields, from)) changes.push({
2407
- valueObjectField,
2408
- target,
2409
- from,
2410
- to: void 0,
2411
- statement: void 0
2412
- });
2144
+ function orderChanges(changes) {
2145
+ const bySource = new Map(changes.map((change) => [JSON.stringify(change.from), change]));
2146
+ const placed = /* @__PURE__ */ new Set();
2147
+ const groups = [];
2148
+ for (const start of changes) {
2149
+ if (placed.has(start)) continue;
2150
+ const path = [];
2151
+ let cycle = false;
2152
+ for (let change = start; change !== void 0 && !placed.has(change); change = change.to === void 0 ? void 0 : bySource.get(JSON.stringify(change.to))) {
2153
+ if (path.includes(change)) {
2154
+ cycle = true;
2155
+ break;
2156
+ }
2157
+ path.push(change);
2413
2158
  }
2159
+ for (const change of path) placed.add(change);
2160
+ groups.push(cycle ? {
2161
+ changes: path,
2162
+ cycle
2163
+ } : {
2164
+ changes: [...path].reverse(),
2165
+ cycle
2166
+ });
2414
2167
  }
2415
- return changes;
2416
- }
2417
- function columnText(column) {
2418
- return `column "${column.column}" of "${column.table}"`;
2419
- }
2420
- function refused(change, fromContract, contract, column, reason, why) {
2421
- const from = valueObjectFieldStatementText(fromContract, change.valueObjectField);
2422
- if (change.statement === void 0) return {
2423
- kind: "unsupportedOperation",
2424
- summary: `Cannot remove value object field "${from}": ${reason}`,
2425
- why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${columnText(column)}`)}`
2426
- };
2427
- return {
2428
- kind: "statementRefused",
2429
- summary: `Cannot rename value object field "${from}" to "${valueObjectFieldStatementText(contract, change.statement.to)}": ${reason}`,
2430
- why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${columnText(column)}`)}`,
2431
- refusedStatement: change.statement
2432
- };
2168
+ return groups;
2433
2169
  }
2434
- function reachRefusal(reach, column, change, contracts) {
2435
- if (reach.kind === "containsItself") return refused(change, contracts.fromContract, contracts.contract, column, `${columnText(column)} holds it inside value object "${reach.valueObject}", which contains itself, so the JSON can hold it at any depth`, "The plan rewrites a key at every path from a column to its value object, and a value object that contains itself has no last path.");
2436
- return refused(change, contracts.fromContract, contracts.contract, column, `${columnText(column)} holds a ${reach.kind} of value objects`, "The plan rewrites a key only in a column that holds a value object or a list of them.");
2170
+ /** A value no member of either enum stores, of the kind of `value`: the next whole number, or a marked string. */
2171
+ function temporaryValue(value, taken) {
2172
+ const numbers = taken.flatMap((stored) => {
2173
+ const number = typeof stored === "string" ? Number(stored) : stored;
2174
+ return typeof number === "number" && Number.isFinite(number) ? [number] : [];
2175
+ });
2176
+ const nextWholeNumber = numbers.length === 0 ? 0 : Math.floor(Math.max(...numbers)) + 1;
2177
+ if (typeof value === "number") return nextWholeNumber;
2178
+ if (/^-?\d+$/.test(value)) return String(nextWholeNumber);
2179
+ let candidate = "prisma_swap";
2180
+ while (taken.some((stored) => sameValue(stored, candidate))) candidate = `${candidate}_`;
2181
+ return candidate;
2437
2182
  }
2438
2183
  /**
2439
- * The key rewrites of value object fields a plan makes. A value object of the origin is compared,
2440
- * field by field, with the value object of the same name in the destination: a rename statement
2441
- * renames a field's key, and a field the destination lacks that no statement renames is removed,
2442
- * which the plan asks about. Each rewrite acts on every column of the working schema whose field
2443
- * holds the value object, at every path to its objects, nested or in lists. The paths are written
2444
- * with the destination's names, so an outer rename runs before an inner one: the rewrites come out
2445
- * ordered by the depth of their paths. A path through a value object that contains itself, or a
2446
- * column that holds a union or a dictionary of value objects, is refused. With no origin contract,
2447
- * nothing is known to have changed.
2184
+ * The rewrites of stored enum values a plan makes. Enums are compared by the stored value of each
2185
+ * member (see `valueChanges`). A changed value is rewritten in every column, in the working schema,
2186
+ * whose field the destination enum types: a rename statement, or a member that keeps its name,
2187
+ * replaces it, and a removed member's value is removed, which the plan asks about. Changes that
2188
+ * shift values along are ordered so none overwrites a value another still has to read. Changes that
2189
+ * move values in a cycle, or into a value another member of the origin enum keeps, are refused.
2190
+ * With no origin contract, nothing is known to have changed.
2448
2191
  */
2449
- function planValueObjectFieldRewrites(input) {
2192
+ function planEnumValueRewrites(input) {
2450
2193
  const { fromContract, contract } = input;
2451
2194
  if (fromContract === null) return ok([]);
2452
- const changes = fieldChanges(fromContract, contract, input.statements);
2453
- if (changes.length === 0) return ok([]);
2195
+ const renamedNamespaces = /* @__PURE__ */ new Map();
2196
+ const valueRenames = [];
2197
+ for (const statement of input.statements) {
2198
+ if (statement.kind !== "rename") continue;
2199
+ if (statement.entity === "namespace") renamedNamespaces.set(statement.from, statement.to);
2200
+ if (statement.entity === "enumValue") valueRenames.push(statement);
2201
+ }
2454
2202
  const placesOf = valueObjectPlaces(contract, input.tables);
2455
2203
  const rewrites = [];
2456
- for (const change of changes) {
2457
- const places = placesOf(change.target);
2458
- if (!places.ok) {
2459
- const { reach, column } = places.failure;
2460
- return notOk(reachRefusal(reach, column, change, {
2461
- fromContract,
2462
- contract
2463
- }));
2204
+ for (const [originNamespace, namespace] of Object.entries(fromContract.domain.namespaces)) for (const [enumName, originEnum] of Object.entries(namespace.enum ?? {})) {
2205
+ const namespaceId = renamedNamespaces.get(originNamespace) ?? originNamespace;
2206
+ const destinationEnum = enumOf(contract, namespaceId, enumName);
2207
+ if (destinationEnum === void 0) continue;
2208
+ const codec = {
2209
+ codecRef: { codecId: destinationEnum.codecId },
2210
+ codecs: input.codecs
2211
+ };
2212
+ const enums = {
2213
+ fromContract,
2214
+ contract,
2215
+ originEnum,
2216
+ destinationEnum,
2217
+ text: (value) => valueText(value, codec)
2218
+ };
2219
+ const changes = valueChanges(enums, (member) => ({
2220
+ namespaceId: asNamespaceId(originNamespace),
2221
+ enum: enumName,
2222
+ member
2223
+ }), (member) => valueRenames.find((rename) => rename.from.namespaceId === originNamespace && rename.from.enum === enumName && rename.from.member === member));
2224
+ const checked = [];
2225
+ for (const change of changes) {
2226
+ const { from, to } = change;
2227
+ if (!isStoredEnumValue(from)) return notOk(unsupportedValue(fromContract, change.enumValue, from));
2228
+ if (to !== void 0 && !isStoredEnumValue(to)) return notOk(unsupportedValue(fromContract, change.enumValue, to));
2229
+ checked.push({
2230
+ ...change,
2231
+ from,
2232
+ to
2233
+ });
2464
2234
  }
2465
- for (const { steps, ...place } of places.value) rewrites.push({
2466
- depth: steps.length,
2467
- rewrite: {
2468
- valueObjectField: change.valueObjectField,
2469
- ...place,
2470
- path: jsonPathText([...steps, {
2471
- kind: "member",
2472
- name: change.from
2473
- }]),
2235
+ const changedFrom = (value) => checked.some(({ from }) => sameValue(from, value));
2236
+ const changedTo = (value) => checked.some(({ to }) => to !== void 0 && sameValue(to, value));
2237
+ const merging = (to) => originEnum.members.find(({ value }) => sameValue(value, to) && !changedFrom(value));
2238
+ for (const { statement, from, to } of checked) {
2239
+ if (statement === void 0 || to === void 0) continue;
2240
+ const holder = destinationEnum.members.find(({ value }) => sameValue(value, from));
2241
+ if (holder !== void 0 && !changedTo(from)) return notOk(stillStoredRefusal(statement, enums, from, holder.name));
2242
+ const merged = merging(to);
2243
+ if (merged !== void 0) return notOk(mergingRefusal(statement, enums, from, to, merged.name));
2244
+ }
2245
+ if (checked.length === 0) continue;
2246
+ const members = membersTypedBy(contract, placesOf, namespaceId, enumName);
2247
+ if (!members.ok) return notOk(unlistedRefusal(contract, enums, checked, members.failure));
2248
+ const columns = [...columnsTypedBy(contract, namespaceId, enumName).filter((column) => input.tables.hasColumn(column.namespaceId, column.table, column.column)), ...members.value];
2249
+ if (columns.length === 0) continue;
2250
+ const taken = [...originEnum.members.map(({ value }) => value), ...destinationEnum.members.map(({ value }) => value)];
2251
+ for (const change of checked) {
2252
+ if (change.statement !== void 0 || change.to === void 0) continue;
2253
+ const merged = merging(change.to);
2254
+ if (merged !== void 0) return notOk(changeMergingRefusal(change, change.to, merged.name, enums));
2255
+ }
2256
+ for (const group of orderChanges(checked)) {
2257
+ if (group.cycle) {
2258
+ const refused = group.changes.find(({ statement }) => statement !== void 0)?.statement;
2259
+ return notOk(refused === void 0 ? changeCycleRefusal(group.changes, enums, taken) : cycleRefusal(refused, group.changes, enums, taken));
2260
+ }
2261
+ for (const change of group.changes) for (const column of columns) rewrites.push({
2262
+ enumValue: change.enumValue,
2263
+ ...column,
2264
+ from: change.from,
2474
2265
  to: change.to,
2475
2266
  statement: change.statement
2476
- }
2477
- });
2478
- }
2479
- return ok([...rewrites].sort((left, right) => left.depth - right.depth).map(({ rewrite }) => rewrite));
2480
- }
2481
- function sameValue(left, right) {
2482
- return JSON.stringify(left) === JSON.stringify(right);
2483
- }
2484
- function enumOf(contract, namespaceId, name) {
2485
- return contract.domain.namespaces[namespaceId]?.enum?.[name];
2486
- }
2487
- /** The columns of the destination whose fields the enum types, in managed tables. */
2488
- function columnsTypedBy(contract, namespaceId, enumName) {
2489
- const found = /* @__PURE__ */ new Map();
2490
- for (const namespace of Object.values(contract.domain.namespaces)) for (const model of Object.values(namespace.models)) {
2491
- const { storage } = model;
2492
- if (!isSqlModelStorage(storage)) continue;
2493
- for (const [fieldName, field] of Object.entries(model.fields)) {
2494
- const ref = field.valueSet;
2495
- if (ref === void 0 || ref.plane !== "domain" || ref.entityKind !== "enum" || ref.spaceId !== void 0 || ref.namespaceId !== namespaceId || ref.entityName !== enumName) continue;
2496
- const column = storage.fields[fieldName]?.column;
2497
- if (column === void 0) continue;
2498
- const stored = contract.storage.namespaces[storage.namespaceId]?.entries.table?.[storage.table]?.columns[column];
2499
- if (stored === void 0) continue;
2500
- const location = {
2501
- namespaceId: storage.namespaceId,
2502
- table: storage.table
2503
- };
2504
- if (tableControlPolicy(contract, location) !== "managed") continue;
2505
- found.set(JSON.stringify([
2506
- storage.namespaceId,
2507
- storage.table,
2508
- column
2509
- ]), {
2510
- ...location,
2511
- column,
2512
- codecRef: buildColumnCodecRef(stored, void 0),
2513
- many: stored.many !== false && stored.many !== void 0,
2514
- member: void 0
2515
2267
  });
2516
2268
  }
2517
2269
  }
2518
- return [...found.values()];
2519
- }
2520
- function isMany$1(many) {
2521
- return many !== void 0 && many !== false;
2270
+ return ok(rewrites);
2522
2271
  }
2523
2272
  /**
2524
- * The members of value objects, in the destination's columns, that the enum's storage value set
2525
- * types: each column and path where the destination stores the value object.
2526
- */
2527
- function membersTypedBy(contract, placesOf, namespaceId, enumName) {
2528
- const found = [];
2529
- for (const { coordinate, valueObject } of valueObjectsWithCoordinates(contract.storage)) {
2530
- const typed = Object.entries(valueObject.fields).filter(([, field]) => field.valueSet !== void 0 && field.valueSet.spaceId === void 0 && field.valueSet.namespaceId === namespaceId && field.valueSet.entityName === enumName);
2531
- if (typed.length === 0) continue;
2532
- const places = placesOf(coordinate);
2533
- if (!places.ok) return places;
2534
- for (const [name, field] of typed) for (const { steps, ...place } of places.value) found.push({
2535
- ...place,
2536
- codecRef: void 0,
2537
- many: false,
2538
- member: {
2539
- path: jsonPathText([
2540
- ...steps,
2541
- {
2542
- kind: "member",
2543
- name
2544
- },
2545
- ...isMany$1(field.many) ? [{ kind: "wildcard" }] : []
2546
- ]),
2547
- nullable: field.nullable
2548
- }
2549
- });
2550
- }
2551
- return ok(found);
2552
- }
2553
- function unlistedRefusal(contract, enums, changes, { column, reach }) {
2554
- const where = `column "${column.column}" of "${column.table}"`;
2555
- const reason = reach.kind === "containsItself" ? `${where} holds it inside value object "${reach.valueObject}", which contains itself, so the JSON can hold it at any depth` : `${where} holds a ${reach.kind} of value objects`;
2556
- const why = reach.kind === "containsItself" ? "The plan rewrites an enum value inside JSON at every path from a column to its member, and a value object that contains itself has no last path." : "The plan rewrites an enum value inside JSON only in a column that holds a value object or a list of them.";
2557
- const statement = changes.find((change) => change.statement !== void 0)?.statement;
2558
- if (statement === void 0) {
2559
- const [first] = changes;
2560
- invariant(first !== void 0, "an enum with no changed value plans no rewrite to refuse");
2561
- return {
2562
- kind: "unsupportedOperation",
2563
- summary: `Cannot remove enum value "${enumValueStatementText(enums.fromContract, first.enumValue)}": ${reason}`,
2564
- why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${where}`)}`
2565
- };
2566
- }
2567
- return {
2568
- kind: "statementRefused",
2569
- summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(contract, statement.to)}": ${reason}`,
2570
- why: `${why} ${handWrittenMigrationAdvice(`the JSON of ${where}`)}`,
2571
- refusedStatement: statement
2572
- };
2573
- }
2574
- function isStoredEnumValue(value) {
2575
- return typeof value === "string" || typeof value === "number";
2576
- }
2577
- /** A stored value as messages write it: a number without quotes, as the enum's codec reads it. */
2578
- function valueText(value, codec) {
2579
- const built = codecForRef(codec.codecs, codec.codecRef);
2580
- if (built === void 0) return JSON.stringify(value);
2581
- try {
2582
- const read = readContractValue(built, value, codec.codecRef.typeParams);
2583
- return typeof read === "number" || typeof read === "bigint" ? String(read) : JSON.stringify(value);
2584
- } catch {
2585
- return JSON.stringify(value);
2586
- }
2587
- }
2588
- function unsupportedValue(contract, value, stored) {
2589
- const text = enumValueStatementText(contract, value);
2590
- return {
2591
- kind: "unsupportedOperation",
2592
- summary: `Cannot rewrite enum value "${text}": its stored value ${JSON.stringify(stored)} is not a string or a number`,
2593
- why: `The plan rewrites the rows that hold a removed or renamed enum value, and it compares only string and number values. Rewrite the rows that hold enum value "${text}" yourself, then plan again.`
2594
- };
2595
- }
2596
- function stillStoredRefusal(statement, enums, stored, holder) {
2597
- const holderText = enumValueStatementText(enums.contract, {
2598
- ...statement.to,
2599
- member: holder
2600
- });
2601
- const value = enums.text(stored);
2602
- return {
2603
- kind: "statementRefused",
2604
- summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(enums.contract, statement.to)}": the destination enum still stores ${value}, as enum value "${holderText}"`,
2605
- why: `A rename changes the stored value in every row that holds it, so the rows that hold ${value} for "${holderText}" would change too. Leave out this statement.`,
2606
- refusedStatement: statement
2607
- };
2608
- }
2609
- function mergingRefusal(statement, enums, from, to, holder) {
2610
- const holderText = enumValueStatementText(enums.fromContract, {
2611
- ...statement.from,
2612
- member: holder
2613
- });
2614
- return {
2615
- kind: "statementRefused",
2616
- summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(enums.contract, statement.to)}": the origin enum already stores ${enums.text(to)}, as enum value "${holderText}"`,
2617
- why: `A rename changes ${enums.text(from)} to ${enums.text(to)} in every row that holds it, which merges its data with the data of "${holderText}". Leave out this statement. To merge them on purpose, plan the change with migration plan and write this.replaceStoredValue(...) in the migration.ts it writes.`,
2618
- refusedStatement: statement
2619
- };
2620
- }
2621
- function cycleRefusal(statement, cycle, enums) {
2622
- const moves = cycle.map(({ from, to }) => `${enums.text(from)} to ${enums.text(to ?? null)}`);
2623
- const listed = `${moves.slice(0, -1).join(", ")} and ${moves.at(-1)}`;
2624
- return {
2625
- kind: "statementRefused",
2626
- summary: `Cannot rename enum value "${enumValueStatementText(enums.fromContract, statement.from)}" to "${enumValueStatementText(enums.contract, statement.to)}": the renames move stored values in a cycle, ${listed}, and a rewrite of one would overwrite the other before it is read`,
2627
- why: "Leave out the renames in the cycle, and write the rewrites by hand in the migration.ts a plan without them writes: rewrite the first value to a value no member stores, then each other value, then that value to its new value, with this.replaceStoredValue({ table, column, from, to }) for each.",
2628
- refusedStatement: statement,
2629
- leaveOut: cycle.flatMap((change) => change.statement === void 0 ? [] : [change.statement])
2630
- };
2631
- }
2632
- /**
2633
- * What changes for each member of the origin enum. A rename statement gives a member the stored
2634
- * value of the member it names. A member the destination has under the same name takes that
2635
- * member's stored value, even when another member had it before. A member the destination lacks is
2636
- * kept when the destination still stores its value, under another name; otherwise its value is
2637
- * removed.
2638
- */
2639
- function valueChanges(enums, enumValueOf, statementOf) {
2640
- const changes = [];
2641
- for (const member of enums.originEnum.members) {
2642
- const enumValue = enumValueOf(member.name);
2643
- const statement = statementOf(member.name);
2644
- const named = statement?.to.member ?? member.name;
2645
- const target = enums.destinationEnum.members.find(({ name }) => name === named);
2646
- if (target !== void 0) {
2647
- if (!sameValue(target.value, member.value)) changes.push({
2648
- enumValue,
2649
- from: member.value,
2650
- to: target.value,
2651
- statement
2652
- });
2653
- continue;
2654
- }
2655
- if (statement !== void 0) continue;
2656
- if (enums.destinationEnum.members.some(({ value }) => sameValue(value, member.value))) continue;
2657
- changes.push({
2658
- enumValue,
2659
- from: member.value,
2660
- to: void 0,
2661
- statement: void 0
2662
- });
2663
- }
2664
- return changes;
2665
- }
2666
- /**
2667
- * Orders the changes so each runs before the change that writes its old value: in a chain, the
2668
- * last value moves first. A cycle has no such order; it comes out as the changes in it, from the
2669
- * first change of the origin enum's order around.
2670
- */
2671
- function orderChanges(changes) {
2672
- const bySource = new Map(changes.map((change) => [JSON.stringify(change.from), change]));
2673
- const placed = /* @__PURE__ */ new Set();
2674
- const groups = [];
2675
- for (const start of changes) {
2676
- if (placed.has(start)) continue;
2677
- const path = [];
2678
- let cycle = false;
2679
- for (let change = start; change !== void 0 && !placed.has(change); change = change.to === void 0 ? void 0 : bySource.get(JSON.stringify(change.to))) {
2680
- if (path.includes(change)) {
2681
- cycle = true;
2682
- break;
2683
- }
2684
- path.push(change);
2685
- }
2686
- for (const change of path) placed.add(change);
2687
- groups.push(cycle ? {
2688
- changes: path,
2689
- cycle
2690
- } : {
2691
- changes: [...path].reverse(),
2692
- cycle
2693
- });
2694
- }
2695
- return groups;
2696
- }
2697
- /** A value no member of either enum stores, of the kind of `value`: the next whole number, or a marked string. */
2698
- function temporaryValue(value, taken) {
2699
- const numbers = taken.flatMap((stored) => {
2700
- const number = typeof stored === "string" ? Number(stored) : stored;
2701
- return typeof number === "number" && Number.isFinite(number) ? [number] : [];
2702
- });
2703
- const nextWholeNumber = numbers.length === 0 ? 0 : Math.floor(Math.max(...numbers)) + 1;
2704
- if (typeof value === "number") return nextWholeNumber;
2705
- if (/^-?\d+$/.test(value)) return String(nextWholeNumber);
2706
- let candidate = "prisma_swap";
2707
- while (taken.some((stored) => sameValue(stored, candidate))) candidate = `${candidate}_`;
2708
- return candidate;
2709
- }
2710
- /**
2711
- * The rewrites of stored enum values a plan makes. Enums are compared by the stored value of each
2712
- * member (see `valueChanges`). A changed value is rewritten in every column, in the working schema,
2713
- * whose field the destination enum types: a rename statement replaces it, and any other change
2714
- * removes it, which the plan asks about, with the replacements that would keep its data. Changes
2715
- * that shift values along are ordered so none overwrites a value another still has to read; rename
2716
- * statements that move values in a cycle are refused, and other changes in a cycle keep their data
2717
- * through a temporary value. With no origin contract, nothing is known to have changed.
2718
- */
2719
- function planEnumValueRewrites(input) {
2720
- const { fromContract, contract } = input;
2721
- if (fromContract === null) return ok([]);
2722
- const renamedNamespaces = /* @__PURE__ */ new Map();
2723
- const valueRenames = [];
2724
- for (const statement of input.statements) {
2725
- if (statement.kind !== "rename") continue;
2726
- if (statement.entity === "namespace") renamedNamespaces.set(statement.from, statement.to);
2727
- if (statement.entity === "enumValue") valueRenames.push(statement);
2728
- }
2729
- const placesOf = valueObjectPlaces(contract, input.tables);
2730
- const rewrites = [];
2731
- for (const [originNamespace, namespace] of Object.entries(fromContract.domain.namespaces)) for (const [enumName, originEnum] of Object.entries(namespace.enum ?? {})) {
2732
- const namespaceId = renamedNamespaces.get(originNamespace) ?? originNamespace;
2733
- const destinationEnum = enumOf(contract, namespaceId, enumName);
2734
- if (destinationEnum === void 0) continue;
2735
- const codec = {
2736
- codecRef: { codecId: destinationEnum.codecId },
2737
- codecs: input.codecs
2738
- };
2739
- const enums = {
2740
- fromContract,
2741
- contract,
2742
- originEnum,
2743
- destinationEnum,
2744
- text: (value) => valueText(value, codec)
2745
- };
2746
- const changes = valueChanges(enums, (member) => ({
2747
- namespaceId: asNamespaceId(originNamespace),
2748
- enum: enumName,
2749
- member
2750
- }), (member) => valueRenames.find((rename) => rename.from.namespaceId === originNamespace && rename.from.enum === enumName && rename.from.member === member));
2751
- const checked = [];
2752
- for (const change of changes) {
2753
- const { from, to } = change;
2754
- if (!isStoredEnumValue(from)) return notOk(unsupportedValue(fromContract, change.enumValue, from));
2755
- if (to !== void 0 && !isStoredEnumValue(to)) return notOk(unsupportedValue(fromContract, change.enumValue, to));
2756
- checked.push({
2757
- ...change,
2758
- from,
2759
- to
2760
- });
2761
- }
2762
- const changedFrom = (value) => checked.some(({ from }) => sameValue(from, value));
2763
- const changedTo = (value) => checked.some(({ to }) => to !== void 0 && sameValue(to, value));
2764
- const merging = (to) => originEnum.members.find(({ value }) => sameValue(value, to) && !changedFrom(value));
2765
- for (const { statement, from, to } of checked) {
2766
- if (statement === void 0 || to === void 0) continue;
2767
- const holder = destinationEnum.members.find(({ value }) => sameValue(value, from));
2768
- if (holder !== void 0 && !changedTo(from)) return notOk(stillStoredRefusal(statement, enums, from, holder.name));
2769
- const merged = merging(to);
2770
- if (merged !== void 0) return notOk(mergingRefusal(statement, enums, from, to, merged.name));
2771
- }
2772
- if (checked.length === 0) continue;
2773
- const members = membersTypedBy(contract, placesOf, namespaceId, enumName);
2774
- if (!members.ok) return notOk(unlistedRefusal(contract, enums, checked, members.failure));
2775
- const columns = [...columnsTypedBy(contract, namespaceId, enumName).filter((column) => input.tables.hasColumn(column.namespaceId, column.table, column.column)), ...members.value];
2776
- if (columns.length === 0) continue;
2777
- const taken = [...originEnum.members.map(({ value }) => value), ...destinationEnum.members.map(({ value }) => value)];
2778
- for (const group of orderChanges(checked)) {
2779
- const refused = group.cycle ? group.changes.find(({ statement }) => statement !== void 0)?.statement : void 0;
2780
- if (refused !== void 0) return notOk(cycleRefusal(refused, group.changes, enums));
2781
- for (const [change, keepData] of keptData(group, taken, merging)) for (const column of columns) rewrites.push({
2782
- enumValue: change.enumValue,
2783
- ...column,
2784
- from: change.from,
2785
- to: change.statement === void 0 ? void 0 : change.to,
2786
- statement: change.statement,
2787
- keepData,
2788
- swapsValues: group.cycle
2789
- });
2790
- }
2791
- }
2792
- return ok(rewrites);
2793
- }
2794
- /**
2795
- * Each change of a group, in the order it runs, with the replacements that keep the data of a
2796
- * change the plan removes: its value replaced by its new value, unless another member of the
2797
- * origin enum keeps that value, which would merge their data. In a cycle, the first value moves to
2798
- * a temporary value, the rest move around, and the temporary value moves last.
2799
- */
2800
- function keptData(group, taken, merging) {
2801
- const moved = ({ from, to }) => to === void 0 ? [] : [{
2802
- from,
2803
- to
2804
- }];
2805
- const [first, ...rest] = group.changes;
2806
- if (!group.cycle || first === void 0) return group.changes.map((change) => [change, change.statement === void 0 && change.to !== void 0 && merging(change.to) === void 0 ? moved(change) : void 0]);
2807
- const swap = temporaryValue(first.from, taken);
2808
- const reversed = [...rest].reverse();
2809
- return [[first, [{
2810
- from: first.from,
2811
- to: swap
2812
- }]], ...reversed.map((change, index) => [change, index === reversed.length - 1 ? [...moved(change), ...moved({
2813
- ...first,
2814
- from: swap
2815
- })] : moved(change)])];
2816
- }
2817
- /**
2818
- * The value the database stores for `value`, a stored value as the contract writes it: the column's
2819
- * codec reads it as a value of its data type and writes it with `toWire`, as a literal default is
2820
- * written. With no codec, or one the stack does not have, the value is used as written.
2273
+ * The value the database stores for `value`, a stored value as the contract writes it: the column's
2274
+ * codec reads it as a value of its data type and writes it with `toWire`, as a literal default is
2275
+ * written. With no codec, or one the stack does not have, the value is used as written.
2821
2276
  */
2822
2277
  async function encodeStoredValue(value, codec) {
2823
2278
  if (codec === void 0) return value;
@@ -3149,22 +2604,6 @@ function unknownCallNames(calls) {
3149
2604
  return [call, (counts.get(call.factoryName) ?? 0) > 1 ? `${call.factoryName}#${ordinal}` : call.factoryName];
3150
2605
  }));
3151
2606
  }
3152
- /** The models of `contract` that store `table`: a model and its variants share one. */
3153
- function modelsStoring(contract, namespaceId, table) {
3154
- return Object.entries(contract.domain.namespaces).flatMap(([modelNamespace, namespace]) => Object.entries(namespace.models).flatMap(([model, definition]) => {
3155
- const { storage } = definition;
3156
- if (!isSqlModelStorage(storage)) return [];
3157
- if (storage.namespaceId !== namespaceId || storage.table !== table) return [];
3158
- return [{
3159
- coordinate: {
3160
- namespaceId: asNamespaceId(modelNamespace),
3161
- model
3162
- },
3163
- isRoot: definition.base === void 0,
3164
- fields: storage.fields
3165
- }];
3166
- }));
3167
- }
3168
2607
  function isRemovedVariant(model, context) {
3169
2608
  return context.removedVariants.some((variant) => variant.namespaceId === model.namespaceId && variant.model === model.model);
3170
2609
  }
@@ -3191,7 +2630,7 @@ function subjectOf(target, context) {
3191
2630
  namespaceId: target.table.namespaceId,
3192
2631
  table: target.table.table
3193
2632
  });
3194
- const models = modelsStoring(fromContract, origin.namespaceId, origin.table);
2633
+ const models = modelsStoring(fromContract, origin, exactName);
3195
2634
  if (target.table.column === void 0) {
3196
2635
  const model = models.find(({ isRoot }) => isRoot) ?? models[0];
3197
2636
  return model === void 0 ? storage : {
@@ -3216,25 +2655,60 @@ function subjectOf(target, context) {
3216
2655
  }
3217
2656
  /**
3218
2657
  * How to keep the rows of a dropped table whose model the destination keeps under the same name in
3219
- * another table of the same namespace: no statement can rename that table, so the user renames it
3220
- * by hand. None when the origin contract already stores a model in that table.
2658
+ * another table of the same namespace, when the plan does not rename it: the user renames it by
2659
+ * hand. None when the origin contract already stores a model in that table.
3221
2660
  */
3222
2661
  function keepTableAdvice(target, subject, context) {
3223
- if (subject.kind !== "model" || target.table === void 0 || context.fromContract === null) return;
2662
+ const { storageRenames } = context;
2663
+ if (subject.kind !== "model" || target.table === void 0 || storageRenames === void 0) return;
3224
2664
  const storage = context.contract.domain.namespaces[subject.namespaceId]?.models[subject.model]?.storage;
3225
2665
  if (storage === void 0 || !isSqlModelStorage(storage)) return void 0;
3226
2666
  const { namespaceId, table: from } = target.table;
3227
2667
  if (storage.namespaceId !== namespaceId || storage.table === from) return void 0;
3228
- if (modelsStoring(context.fromContract, namespaceId, storage.table).length > 0) return void 0;
3229
- const rename = {
2668
+ if (storageRenames.originModelsIn({
3230
2669
  namespaceId,
3231
- from,
3232
- to: storage.table
3233
- };
3234
- return `To keep its rows, rename table "${from}" to "${storage.table}" instead; a statement cannot rename the table of a model that keeps its name. With db update, rename the table in the database yourself with ${context.byHand.tableRenameByHand(rename).join("; ")}, then run prisma db update. With migration plan, write the rename as a migration of its own instead: run prisma migration new --name <name> --from <hash of the migration the database is at>, add ${context.byHand.renderTableRename(rename)} to the operations of its migration.ts, run node on that migration.ts so it writes ops.json, then run prisma db migrate.`;
3235
- }
3236
- /**
3237
- * The subject of each operation that loses data and each that changes access, at its position in
2670
+ table: storage.table
2671
+ }).length > 0) return void 0;
2672
+ const sharing = sharedStorageAdvice(storageRenames, {
2673
+ origin: {
2674
+ namespaceId,
2675
+ table: from
2676
+ },
2677
+ destination: {
2678
+ namespaceId,
2679
+ table: storage.table
2680
+ }
2681
+ });
2682
+ if (sharing !== void 0) return sharing;
2683
+ const rename = {
2684
+ namespaceId,
2685
+ from,
2686
+ to: storage.table
2687
+ };
2688
+ return `To keep its rows, rename table "${from}" to "${storage.table}" instead. The plan does not rename it: a plan renames the table of a model that keeps its name only on a target that plans table renames, when the control policy of the table is "managed" in both contracts, every model stored in it moves to the new table, and no model moves there from another table. With db update, rename the table in the database yourself with ${context.byHand.tableRenameByHand(rename).join("; ")}, then run prisma db update. With migration plan, write the rename as a migration of its own instead. That migration leads to the contract as it is when you write it, so first undo every other change to the contract, keep only the new table name, and run prisma contract emit. Then run prisma migration new --name <name> --from <hash of the migration the database is at>, add ${context.byHand.renderTableRename(rename)} to the operations of its migration.ts, run node on that migration.ts so it writes ops.json, and run prisma db migrate. Then make the rest of the change again and plan it with prisma migration plan.`;
2689
+ }
2690
+ function byName(left, right) {
2691
+ return `${left.namespaceId}.${left.model}`.localeCompare(`${right.namespaceId}.${right.model}`);
2692
+ }
2693
+ /**
2694
+ * Why the rows of table `origin` cannot be kept by renaming it to `destination`, as the planner
2695
+ * decides it: their storage is being split or merged. Keeping their rows is then a data migration.
2696
+ */
2697
+ function sharedStorageAdvice(storageRenames, tables) {
2698
+ const shared = storageRenames.sharedTable(tables);
2699
+ if (shared === void 0) return void 0;
2700
+ const split = shared.kind === "split";
2701
+ const models = [...split ? storageRenames.originModelsIn(tables.origin) : storageRenames.destinationModelsIn(tables.destination).filter((model) => storageRenames.originTableOf(model) !== void 0)].sort(byName);
2702
+ const into = /* @__PURE__ */ new Map();
2703
+ for (const model of models) {
2704
+ const moved = split ? storageRenames.destinationTableOf(model) : tables.destination;
2705
+ if (moved !== void 0) into.set(moved.table, [...into.get(moved.table) ?? [], model]);
2706
+ }
2707
+ const moves = [...into].map(([table, moved]) => `the rows of ${modelsText(moved)} into table "${table}"`).join(" and ");
2708
+ return `${split ? `The origin stores ${modelsText(models)} in table "${tables.origin.table}", and the destination stores them in different tables, so their storage is being split.` : `The destination stores ${modelsText(models)} in table "${tables.destination.table}", and the origin stores them in different tables, so their storage is being merged.`} Keeping their rows is a data migration, which a plan does not write. With migration plan, write this change as a hand-written migration instead: ${handWrittenMigrationSteps(moves)}`;
2709
+ }
2710
+ /**
2711
+ * The subject of each operation that loses data and each that changes access, at its position in
3238
2712
  * the plan. A subject is a model or a field of the origin contract when one stores it, found under
3239
2713
  * its origin name when a rename statement renamed its table or column earlier in the plan.
3240
2714
  */
@@ -3262,8 +2736,7 @@ function subjectsOfCalls(calls, context) {
3262
2736
  subject,
3263
2737
  loss: target.loss,
3264
2738
  label: call.label,
3265
- ...ifDefined("keepDataAdvice", target.keepDataAdvice ?? keepTableAdvice(target, subject, context)),
3266
- ...ifDefined("keepDataEdit", target.keepDataEdit)
2739
+ ...ifDefined("keepDataAdvice", target.keepDataAdvice ?? keepTableAdvice(target, subject, context))
3267
2740
  });
3268
2741
  }
3269
2742
  for (const target of call.accessChanges) accessChanges.push({
@@ -3496,6 +2969,150 @@ async function rowsWithoutValueFailure(input) {
3496
2969
  };
3497
2970
  }
3498
2971
  }
2972
+ const COLUMN_RENAME_UNMATCHED_CODE = "MIGRATION.COLUMN_RENAME_UNMATCHED";
2973
+ function tableLabel$1(namespaceId, table) {
2974
+ return namespaceId === void 0 || namespaceId === UNBOUND_NAMESPACE_ID ? table : `${namespaceId}.${table}`;
2975
+ }
2976
+ function columnLabel(namespaceId, table, column) {
2977
+ return `"${tableLabel$1(namespaceId, table)}"."${column}"`;
2978
+ }
2979
+ function declaresColumn(contract, namespaceId, table, column) {
2980
+ const columns = contract.storage.namespaces[namespaceId]?.entries.table?.[table]?.columns;
2981
+ return columns !== void 0 && Object.hasOwn(columns, column);
2982
+ }
2983
+ /**
2984
+ * Refuses a `renameColumn` call that does not match the migration's contracts, with
2985
+ * `MIGRATION.COLUMN_RENAME_UNMATCHED`.
2986
+ */
2987
+ function unmatchedColumnRename(rename, reason) {
2988
+ return sqlFamilyError(COLUMN_RENAME_UNMATCHED_CODE, `renameColumn ${columnLabel(rename.namespaceId, rename.table, rename.from)} to "${rename.to}" does not match the migration's contracts: ${reason}.`, {
2989
+ why: "renameColumn must name a table and a column as the migration's earlier rename operations leave them, and a new column name that the end contract has on that table and that the table does not have yet. Order the rename calls in the sequence the renames happen, and check the names of the table, the column and the namespace.",
2990
+ meta: {
2991
+ table: rename.table,
2992
+ from: rename.from,
2993
+ to: rename.to
2994
+ }
2995
+ });
2996
+ }
2997
+ /**
2998
+ * Checks a column rename: the table must exist in `previous` (in exactly one namespace when the
2999
+ * namespace is not given) with the old column and without the new one, and the end contract must
3000
+ * have the new column on that table.
3001
+ */
3002
+ function checkColumnRename(previous, endContract, rename) {
3003
+ const namespaceIds = rename.namespaceId === void 0 ? previous.namespacesWithTable(rename.table) : previous.hasTable(rename.namespaceId, rename.table) ? [rename.namespaceId] : [];
3004
+ const [namespaceId, ...others] = namespaceIds;
3005
+ if (namespaceId === void 0) return notOk({ kind: "tableMissing" });
3006
+ if (others.length > 0) return notOk({
3007
+ kind: "tableInManyNamespaces",
3008
+ namespaceIds
3009
+ });
3010
+ if (!previous.hasColumn(namespaceId, rename.table, rename.from)) return notOk({
3011
+ kind: "columnMissing",
3012
+ namespaceId
3013
+ });
3014
+ const [taken] = previous.columnsNamed(namespaceId, rename.table, rename.to).filter((column) => column !== rename.from);
3015
+ if (taken !== void 0) return notOk({
3016
+ kind: "nameTaken",
3017
+ namespaceId,
3018
+ taken
3019
+ });
3020
+ if (!declaresColumn(endContract, namespaceId, rename.table, rename.to)) return notOk({
3021
+ kind: "notInEndContract",
3022
+ namespaceId
3023
+ });
3024
+ return ok({
3025
+ namespaceId,
3026
+ table: rename.table,
3027
+ from: rename.from,
3028
+ to: rename.to
3029
+ });
3030
+ }
3031
+ /** The reason `MIGRATION.COLUMN_RENAME_UNMATCHED` gives for a mismatch. */
3032
+ function columnRenameMismatchReason(rename, mismatch) {
3033
+ switch (mismatch.kind) {
3034
+ case "tableMissing": return `table "${tableLabel$1(rename.namespaceId, rename.table)}" does not exist at this point of the migration`;
3035
+ case "tableInManyNamespaces": return `table "${rename.table}" is declared in more than one namespace (${mismatch.namespaceIds.join(", ")}); name its namespace`;
3036
+ case "columnMissing": return `column ${columnLabel(mismatch.namespaceId, rename.table, rename.from)} does not exist at this point of the migration`;
3037
+ case "nameTaken": return `column ${columnLabel(mismatch.namespaceId, rename.table, rename.to)} already exists at this point of the migration${mismatch.taken === rename.to ? "" : ` as "${mismatch.taken}"`}`;
3038
+ case "notInEndContract": return `column ${columnLabel(mismatch.namespaceId, rename.table, rename.to)} does not exist in the end contract`;
3039
+ }
3040
+ }
3041
+ /**
3042
+ * Resolves a column a migration renames with {@link checkColumnRename}, refusing a mismatch with
3043
+ * `MIGRATION.COLUMN_RENAME_UNMATCHED`.
3044
+ */
3045
+ function resolveColumnRenameAgainst(previous, endContract, rename) {
3046
+ const checked = checkColumnRename(previous, endContract, rename);
3047
+ if (!checked.ok) return notOk(unmatchedColumnRename(rename, columnRenameMismatchReason(rename, checked.failure)));
3048
+ return ok(checked.value);
3049
+ }
3050
+ const TABLE_RENAME_UNMATCHED_CODE = "MIGRATION.TABLE_RENAME_UNMATCHED";
3051
+ function tableLabel(namespaceId, tableName) {
3052
+ return namespaceId === void 0 || namespaceId === UNBOUND_NAMESPACE_ID ? tableName : `${namespaceId}.${tableName}`;
3053
+ }
3054
+ function declares(contract, namespaceId, tableName) {
3055
+ return Object.hasOwn(contract.storage.namespaces[namespaceId]?.entries.table ?? {}, tableName);
3056
+ }
3057
+ /**
3058
+ * Refuses a `renameTable` call that does not match the migration's contracts, with
3059
+ * `MIGRATION.TABLE_RENAME_UNMATCHED`.
3060
+ */
3061
+ function unmatchedTableRename(rename, reason) {
3062
+ return sqlFamilyError(TABLE_RENAME_UNMATCHED_CODE, `renameTable "${tableLabel(rename.namespaceId, rename.from)}" to "${rename.to}" does not match the migration's contracts: ${reason}.`, {
3063
+ why: "renameTable must name a table as the migration's earlier rename operations leave it, and a new name that the end contract has and that no earlier rename operation has already produced. Order the renameTable calls in the sequence the renames happen, make the rename its own schema change, and check the spelling, the table and the namespace.",
3064
+ meta: {
3065
+ from: rename.from,
3066
+ to: rename.to
3067
+ }
3068
+ });
3069
+ }
3070
+ /**
3071
+ * Checks a table rename: the table must exist in `previous` (in exactly one namespace when the
3072
+ * namespace is not given), and the new name must exist in the end contract and not in `previous`.
3073
+ */
3074
+ function checkTableRename(previous, endContract, rename) {
3075
+ const namespaceIds = rename.namespaceId === void 0 ? previous.namespacesWithTable(rename.from) : previous.hasTable(rename.namespaceId, rename.from) ? [rename.namespaceId] : [];
3076
+ const [namespaceId, ...others] = namespaceIds;
3077
+ if (namespaceId === void 0) return notOk({ kind: "tableMissing" });
3078
+ if (others.length > 0) return notOk({
3079
+ kind: "tableInManyNamespaces",
3080
+ namespaceIds
3081
+ });
3082
+ const [taken] = previous.tablesNamed(namespaceId, rename.to).filter((table) => table !== rename.from);
3083
+ if (taken !== void 0) return notOk({
3084
+ kind: "nameTaken",
3085
+ namespaceId,
3086
+ taken
3087
+ });
3088
+ if (!declares(endContract, namespaceId, rename.to)) return notOk({
3089
+ kind: "notInEndContract",
3090
+ namespaceId
3091
+ });
3092
+ return ok({
3093
+ namespaceId,
3094
+ from: rename.from,
3095
+ to: rename.to
3096
+ });
3097
+ }
3098
+ /** The reason `MIGRATION.TABLE_RENAME_UNMATCHED` gives for a mismatch. */
3099
+ function tableRenameMismatchReason(rename, mismatch) {
3100
+ switch (mismatch.kind) {
3101
+ case "tableMissing": return `table "${tableLabel(rename.namespaceId, rename.from)}" does not exist at this point of the migration`;
3102
+ case "tableInManyNamespaces": return `table "${rename.from}" is declared in more than one namespace (${mismatch.namespaceIds.join(", ")}); name its namespace`;
3103
+ case "nameTaken": return `table "${tableLabel(mismatch.namespaceId, rename.to)}" already exists at this point of the migration${mismatch.taken === rename.to ? "" : ` as "${mismatch.taken}"`}`;
3104
+ case "notInEndContract": return `table "${tableLabel(mismatch.namespaceId, rename.to)}" does not exist in the end contract`;
3105
+ }
3106
+ }
3107
+ /**
3108
+ * Resolves a table a migration renames with {@link checkTableRename}, refusing a mismatch with
3109
+ * `MIGRATION.TABLE_RENAME_UNMATCHED`.
3110
+ */
3111
+ function resolveTableRenameAgainst(previous, endContract, rename) {
3112
+ const checked = checkTableRename(previous, endContract, rename);
3113
+ if (!checked.ok) return notOk(unmatchedTableRename(rename, tableRenameMismatchReason(rename, checked.failure)));
3114
+ return ok(checked.value);
3115
+ }
3499
3116
  const RowsHoldingValueMeta = type({ rowsHoldingValue: {
3500
3117
  enumValue: {
3501
3118
  "namespaceId?": "string",
@@ -3601,152 +3218,1334 @@ async function rowsHoldingValueFailure(input) {
3601
3218
  rows: otherRows
3602
3219
  });
3603
3220
  }
3604
- return {
3605
- summary: counted.length === 1 ? rowsHoldingValueSummary(failed.mark, rows) : ["Rows hold values that the migration removes where no null is allowed, so the values cannot be removed:", ...counted.map((each) => `- ${holdingText(each.removal.mark, each.rows)}`)].join("\n"),
3606
- reports: counted.map((each) => report(each.removal, each.rows))
3607
- };
3608
- }
3609
- /** Keywords that end an expression and continue the statement around it. */
3610
- const STATEMENT_KEYWORDS = /* @__PURE__ */ new Set([
3611
- "FROM",
3612
- "WHERE",
3613
- "UNION",
3614
- "INTERSECT",
3615
- "EXCEPT",
3616
- "GROUP",
3617
- "ORDER",
3618
- "HAVING",
3619
- "LIMIT",
3620
- "RETURNING",
3621
- "WINDOW"
3622
- ]);
3623
- const WORD = /[A-Za-z_][A-Za-z0-9_$]*/y;
3624
- const DOLLAR_QUOTE = /\$[A-Za-z_]*\$/y;
3625
- function quoteAt(text, index, quoting) {
3626
- return quoting.find((quote) => text.slice(index, index + quote.open.length).toUpperCase() === quote.open.toUpperCase());
3627
- }
3628
- function endOfQuote(text, start, quote) {
3629
- let index = start + quote.open.length;
3630
- while (index < text.length) {
3631
- if (quote.backslashEscapes && text[index] === "\\") {
3632
- index += 2;
3633
- continue;
3221
+ return {
3222
+ summary: counted.length === 1 ? rowsHoldingValueSummary(failed.mark, rows) : ["Rows hold values that the migration removes where no null is allowed, so the values cannot be removed:", ...counted.map((each) => `- ${holdingText(each.removal.mark, each.rows)}`)].join("\n"),
3223
+ reports: counted.map((each) => report(each.removal, each.rows))
3224
+ };
3225
+ }
3226
+ /** Keywords that end an expression and continue the statement around it. */
3227
+ const STATEMENT_KEYWORDS = /* @__PURE__ */ new Set([
3228
+ "FROM",
3229
+ "WHERE",
3230
+ "UNION",
3231
+ "INTERSECT",
3232
+ "EXCEPT",
3233
+ "GROUP",
3234
+ "ORDER",
3235
+ "HAVING",
3236
+ "LIMIT",
3237
+ "RETURNING",
3238
+ "WINDOW"
3239
+ ]);
3240
+ const WORD = /[A-Za-z_][A-Za-z0-9_$]*/y;
3241
+ const DOLLAR_QUOTE = /\$[A-Za-z_]*\$/y;
3242
+ function quoteAt(text, index, quoting) {
3243
+ return quoting.find((quote) => text.slice(index, index + quote.open.length).toUpperCase() === quote.open.toUpperCase());
3244
+ }
3245
+ function endOfQuote(text, start, quote) {
3246
+ let index = start + quote.open.length;
3247
+ while (index < text.length) {
3248
+ if (quote.backslashEscapes && text[index] === "\\") {
3249
+ index += 2;
3250
+ continue;
3251
+ }
3252
+ if (text.startsWith(quote.close, index)) {
3253
+ const after = index + quote.close.length;
3254
+ if (!quote.doubledCloseEscapes || !text.startsWith(quote.close, after)) return after;
3255
+ index = after + quote.close.length;
3256
+ continue;
3257
+ }
3258
+ index += 1;
3259
+ }
3260
+ }
3261
+ /**
3262
+ * Returns what in `text` could end or extend the statement a migration writes it into, such as the
3263
+ * conversion of an `ALTER COLUMN … USING` clause or a column of an `INSERT … SELECT` list, or
3264
+ * undefined when it finds nothing. Text inside the quotes of `quoting` may hold anything; outside
3265
+ * them the text may not hold a semicolon, a SQL comment, dollar quoting, or, outside parentheses
3266
+ * and brackets, a comma or a keyword that would end the expression. `FROM` directly after
3267
+ * `DISTINCT`, as in `IS DISTINCT FROM`, belongs to the expression. It checks for these mistakes
3268
+ * only; it does not parse the SQL.
3269
+ */
3270
+ function checkSqlExpressionText(text, quoting) {
3271
+ let depth = 0;
3272
+ let index = 0;
3273
+ let previousWord;
3274
+ while (index < text.length) {
3275
+ const character = text[index] ?? "";
3276
+ const quote = quoteAt(text, index, quoting);
3277
+ if (quote !== void 0) {
3278
+ const end = endOfQuote(text, index, quote);
3279
+ if (end === void 0) return "a quote that is not closed";
3280
+ index = end;
3281
+ previousWord = void 0;
3282
+ continue;
3283
+ }
3284
+ if (character === ";") return "a semicolon outside a quoted literal";
3285
+ if (text.startsWith("--", index) || text.startsWith("/*", index)) return "a SQL comment";
3286
+ DOLLAR_QUOTE.lastIndex = index;
3287
+ if (character === "$" && DOLLAR_QUOTE.test(text)) return "dollar quoting";
3288
+ if (character === "," && depth === 0) return "a comma outside parentheses";
3289
+ if (character === "(" || character === "[") depth += 1;
3290
+ if (character === ")" || character === "]") {
3291
+ depth -= 1;
3292
+ if (depth < 0) return "parentheses that do not match";
3293
+ }
3294
+ WORD.lastIndex = index;
3295
+ const word = /[A-Za-z_]/.test(character) ? WORD.exec(text)?.[0].toUpperCase() : void 0;
3296
+ if (word !== void 0) {
3297
+ if (depth === 0 && STATEMENT_KEYWORDS.has(word) && !(word === "FROM" && previousWord === "DISTINCT")) return `the keyword ${word} outside parentheses`;
3298
+ previousWord = word;
3299
+ index += word.length;
3300
+ continue;
3301
+ }
3302
+ if (!/\s/.test(character)) previousWord = void 0;
3303
+ index += 1;
3304
+ }
3305
+ return depth === 0 ? void 0 : "parentheses that do not match";
3306
+ }
3307
+ /** Whether `slot` is a placeholder the user has not filled yet. */
3308
+ function isUnfilledSlot(slot) {
3309
+ return slot?.kind === "placeholder";
3310
+ }
3311
+ /** The SQL of a written slot; undefined for an unfilled one or none. */
3312
+ function sqlOfSlot(slot) {
3313
+ return slot?.kind === "sql" ? slot.sql : void 0;
3314
+ }
3315
+ /** The slot as `migration.ts` writes it: SQL text written through `sql`, or a `placeholder(...)` call. */
3316
+ function slotSource(slot, sql) {
3317
+ return slot.kind === "placeholder" ? `placeholder(${jsonToTsSource(slot.slot)})` : sql.source(slot.sql);
3318
+ }
3319
+ /** `moduleSpecifier` is the module the generated file imports `sql` from. */
3320
+ function createSqlTextSources(moduleSpecifier) {
3321
+ let usesTag = false;
3322
+ return {
3323
+ source(text) {
3324
+ const written = tsTaggedTemplateSource("sql", text);
3325
+ usesTag ||= written.usesTag;
3326
+ return written.source;
3327
+ },
3328
+ imports() {
3329
+ return usesTag ? [{
3330
+ moduleSpecifier,
3331
+ symbol: "sql"
3332
+ }] : [];
3333
+ }
3334
+ };
3335
+ }
3336
+ /** The codecs and data types a set of composed components registers. */
3337
+ function sqlTypeLookupsOf(frameworkComponents) {
3338
+ return {
3339
+ codecLookup: extractCodecLookup(frameworkComponents),
3340
+ dataTypeLookup: assembleDataTypes(frameworkComponents).lookup
3341
+ };
3342
+ }
3343
+ function coordinateKey(coordinate) {
3344
+ return JSON.stringify([
3345
+ coordinate.namespaceId,
3346
+ coordinate.model,
3347
+ "field" in coordinate ? coordinate.field : null
3348
+ ]);
3349
+ }
3350
+ /** The name each namespace has after the namespace rename statements, keyed by its origin name. */
3351
+ function namespaceRenamesOf(statements) {
3352
+ return new Map(statements.flatMap((statement) => statement.entity === "namespace" ? [[statement.from, statement.to]] : []));
3353
+ }
3354
+ function modelRenamesOf(statements, namespaceRenames, fromContract, contract) {
3355
+ const stated = statements.flatMap((statement) => statement.entity === "model" ? [{
3356
+ from: statement.from,
3357
+ to: statement.to,
3358
+ statement
3359
+ }] : []);
3360
+ const named = new Set(stated.flatMap((rename) => [rename.from, rename.to]).map(coordinateKey));
3361
+ const kept = Object.entries(fromContract.domain.namespaces).flatMap(([namespaceId, namespace]) => Object.keys(namespace.models).flatMap((model) => {
3362
+ const from = {
3363
+ namespaceId: asNamespaceId(namespaceId),
3364
+ model
3365
+ };
3366
+ const to = {
3367
+ namespaceId: asNamespaceId(namespaceRenames.get(namespaceId) ?? namespaceId),
3368
+ model
3369
+ };
3370
+ return Object.hasOwn(contract.domain.namespaces[to.namespaceId]?.models ?? {}, model) && !named.has(coordinateKey(from)) && !named.has(coordinateKey(to)) ? [{
3371
+ from,
3372
+ to,
3373
+ statement: void 0
3374
+ }] : [];
3375
+ }));
3376
+ return [...stated, ...kept];
3377
+ }
3378
+ function fieldRenamesOf(statements, models, fromContract, contract) {
3379
+ const stated = statements.flatMap((statement) => statement.entity === "field" ? [{
3380
+ from: statement.from,
3381
+ to: statement.to,
3382
+ statement
3383
+ }] : []);
3384
+ const named = new Set(stated.flatMap((rename) => [rename.from, rename.to]).map(coordinateKey));
3385
+ const kept = models.flatMap((model) => {
3386
+ const originFields = Object.keys(sqlModelStorage(fromContract, model.from)?.fields ?? {});
3387
+ const destinationFields = sqlModelStorage(contract, model.to)?.fields ?? {};
3388
+ return originFields.flatMap((field) => {
3389
+ const from = {
3390
+ ...model.from,
3391
+ field
3392
+ };
3393
+ const to = {
3394
+ ...model.to,
3395
+ field
3396
+ };
3397
+ return Object.hasOwn(destinationFields, field) && !named.has(coordinateKey(from)) && !named.has(coordinateKey(to)) ? [{
3398
+ from,
3399
+ to,
3400
+ statement: void 0
3401
+ }] : [];
3402
+ });
3403
+ });
3404
+ return [...stated, ...kept];
3405
+ }
3406
+ function grouped(items, keyOf, textOf) {
3407
+ const groups = /* @__PURE__ */ new Map();
3408
+ for (const item of items) {
3409
+ const key = keyOf(item);
3410
+ if (key === void 0) continue;
3411
+ const text = textOf(key);
3412
+ const group = groups.get(text);
3413
+ if (group === void 0) groups.set(text, {
3414
+ key,
3415
+ items: [item]
3416
+ });
3417
+ else group.items.push(item);
3418
+ }
3419
+ return [...groups.values()];
3420
+ }
3421
+ function tablesText(key) {
3422
+ return JSON.stringify([
3423
+ key.origin.namespaceId,
3424
+ key.origin.table,
3425
+ key.destination.namespaceId,
3426
+ key.destination.table
3427
+ ]);
3428
+ }
3429
+ function columnsText(key) {
3430
+ return JSON.stringify([
3431
+ tablesText(key),
3432
+ key.from,
3433
+ key.to
3434
+ ]);
3435
+ }
3436
+ /**
3437
+ * The renames a plan makes, from its statements and from the names both contracts keep, and the
3438
+ * tables and columns they move.
3439
+ */
3440
+ var StorageRenames = class {
3441
+ models;
3442
+ fields;
3443
+ tableChanges;
3444
+ columnChanges;
3445
+ #fromContract;
3446
+ #contract;
3447
+ #namespaceRenames;
3448
+ #byOrigin;
3449
+ #byDestination;
3450
+ /** Whether the target takes two table or column names for one. */
3451
+ sameName;
3452
+ constructor(statements, fromContract, contract, sameName) {
3453
+ this.#fromContract = fromContract;
3454
+ this.#contract = contract;
3455
+ this.sameName = sameName;
3456
+ this.#namespaceRenames = namespaceRenamesOf(statements);
3457
+ this.models = modelRenamesOf(statements, this.#namespaceRenames, fromContract, contract);
3458
+ this.fields = fieldRenamesOf(statements, this.models, fromContract, contract);
3459
+ const renames = [...this.models, ...this.fields];
3460
+ this.#byOrigin = new Map(renames.map((rename) => [coordinateKey(rename.from), rename]));
3461
+ this.#byDestination = new Map(renames.map((rename) => [coordinateKey(rename.to), rename]));
3462
+ this.tableChanges = grouped(this.models, (rename) => {
3463
+ const tables = this.#tablesOf(rename);
3464
+ return tables === void 0 || this.inPlace(tables.origin, tables.destination) ? void 0 : tables;
3465
+ }, tablesText).map(({ key, items }) => ({
3466
+ ...key,
3467
+ renames: items
3468
+ }));
3469
+ this.columnChanges = grouped(this.fields, (rename) => {
3470
+ const columns = this.#columnsOf(rename);
3471
+ return columns === void 0 || columns.from === columns.to ? void 0 : columns;
3472
+ }, columnsText).map(({ key, items }) => ({
3473
+ ...key,
3474
+ renames: items
3475
+ }));
3476
+ }
3477
+ #tablesOf(rename) {
3478
+ const origin = modelTable(this.#fromContract, rename.from);
3479
+ const destination = modelTable(this.#contract, rename.to);
3480
+ return origin === void 0 || destination === void 0 ? void 0 : {
3481
+ origin,
3482
+ destination
3483
+ };
3484
+ }
3485
+ #columnsOf(rename) {
3486
+ const tables = this.#tablesOf(rename);
3487
+ const from = fieldColumn(this.#fromContract, rename.from);
3488
+ const to = fieldColumn(this.#contract, rename.to);
3489
+ return tables === void 0 || from === void 0 || to === void 0 ? void 0 : {
3490
+ ...tables,
3491
+ from,
3492
+ to
3493
+ };
3494
+ }
3495
+ /** The namespace an origin namespace has after the namespace rename statements. */
3496
+ namespaceAfterRenames(namespaceId) {
3497
+ return this.#namespaceRenames.get(namespaceId) ?? namespaceId;
3498
+ }
3499
+ /** Whether the origin table is the destination table once the namespace renames are made. */
3500
+ inPlace(origin, destination) {
3501
+ return sameTable({
3502
+ namespaceId: this.namespaceAfterRenames(origin.namespaceId),
3503
+ table: origin.table
3504
+ }, destination);
3505
+ }
3506
+ /** The table change that moves the table of `rename`'s origin model, if its table changes. */
3507
+ tableChangeOf(rename) {
3508
+ return this.tableChanges.find((change) => change.renames.includes(rename));
3509
+ }
3510
+ /** The column change that moves the column of `rename`'s origin field, if its column changes. */
3511
+ columnChangeOf(rename) {
3512
+ return this.columnChanges.find((change) => change.renames.includes(rename));
3513
+ }
3514
+ /** Whether the control policy is `managed` for the origin table and the destination table. */
3515
+ managedOnBothSides(change) {
3516
+ return tableControlPolicy(this.#fromContract, change.origin) === "managed" && tableControlPolicy(this.#contract, change.destination) === "managed";
3517
+ }
3518
+ #renameFrom(origin) {
3519
+ return this.#byOrigin.get(coordinateKey(origin));
3520
+ }
3521
+ #renameTo(destination) {
3522
+ return this.#byDestination.get(coordinateKey(destination));
3523
+ }
3524
+ #storedIn(contract, coordinate) {
3525
+ const table = modelTable(contract, coordinate);
3526
+ if (table === void 0) return void 0;
3527
+ return "field" in coordinate ? {
3528
+ table,
3529
+ column: fieldColumn(contract, coordinate)
3530
+ } : {
3531
+ table,
3532
+ column: void 0
3533
+ };
3534
+ }
3535
+ /** The destination table of an origin model, through the renames: `undefined` when the destination removes the model. */
3536
+ destinationTableOf(model) {
3537
+ const rename = this.#renameFrom(model);
3538
+ return rename === void 0 ? void 0 : modelTable(this.#contract, rename.to);
3539
+ }
3540
+ /** The origin table of a destination model, through the renames: `undefined` for a new model. */
3541
+ originTableOf(model) {
3542
+ const rename = this.#renameTo(model);
3543
+ return rename === void 0 ? void 0 : modelTable(this.#fromContract, rename.from);
3544
+ }
3545
+ /**
3546
+ * Why the rows of table `origin` cannot move whole to table `destination`: an origin model stored
3547
+ * in it that the destination keeps in another table, or a destination model stored in the new
3548
+ * table, as the target compares names, whose origin model is stored elsewhere. Models pair through
3549
+ * the renames. `undefined` when the whole table moves, and nothing else moves there. A model the
3550
+ * destination removes, or a new model, blocks nothing.
3551
+ */
3552
+ sharedTable(change) {
3553
+ const split = this.originModelsIn(change.origin).filter((model) => {
3554
+ const destination = this.destinationTableOf(model);
3555
+ return destination !== void 0 && !sameTable(destination, change.destination);
3556
+ });
3557
+ if (split.length > 0) return {
3558
+ kind: "split",
3559
+ objects: split
3560
+ };
3561
+ const merged = this.destinationModelsIn(change.destination).flatMap((model) => {
3562
+ const rename = this.#renameTo(model);
3563
+ const origin = rename === void 0 ? void 0 : modelTable(this.#fromContract, rename.from);
3564
+ return origin !== void 0 && rename !== void 0 && !sameTable(origin, change.origin) ? [rename.from] : [];
3565
+ });
3566
+ return merged.length > 0 ? {
3567
+ kind: "merged",
3568
+ objects: merged
3569
+ } : void 0;
3570
+ }
3571
+ /**
3572
+ * Why the change cannot rename its column: an origin field stored in it that the destination
3573
+ * keeps in another column, or a destination field stored in the new column, as the target
3574
+ * compares names, whose origin field is stored elsewhere. `undefined` when the whole column
3575
+ * moves, and nothing else moves there.
3576
+ */
3577
+ sharedColumn(change) {
3578
+ const split = fieldsStoring(this.#fromContract, change.origin, change.from, this.sameName).filter((field) => {
3579
+ const rename = this.#renameFrom(field);
3580
+ const destination = rename === void 0 ? void 0 : this.#storedIn(this.#contract, rename.to);
3581
+ return destination?.column !== void 0 && (!sameTable(destination.table, change.destination) || destination.column !== change.to);
3582
+ });
3583
+ if (split.length > 0) return {
3584
+ kind: "split",
3585
+ objects: split
3586
+ };
3587
+ const merged = fieldsStoring(this.#contract, change.destination, change.to, this.sameName).flatMap((field) => {
3588
+ const rename = this.#renameTo(field);
3589
+ const origin = rename === void 0 ? void 0 : this.#storedIn(this.#fromContract, rename.from);
3590
+ return rename !== void 0 && "field" in rename.from && origin?.column !== void 0 && (!sameTable(origin.table, change.origin) || origin.column !== change.from) ? [rename.from] : [];
3591
+ });
3592
+ return merged.length > 0 ? {
3593
+ kind: "merged",
3594
+ objects: merged
3595
+ } : void 0;
3596
+ }
3597
+ /**
3598
+ * A name for `name` to move through that no table of the namespace has in either contract, and
3599
+ * that is not one of `reserved`, as the target compares names.
3600
+ */
3601
+ unusedTableName(namespaceId, name, reserved = []) {
3602
+ const used = [this.#fromContract, this.#contract].flatMap((contract) => Object.keys(contract.storage.namespaces[namespaceId]?.entries.table ?? {}));
3603
+ return this.#unused([...used, ...reserved], name);
3604
+ }
3605
+ /**
3606
+ * A name for `name` to move through that no column of the change's table has in either
3607
+ * contract, and that is not one of `reserved`, as the target compares names.
3608
+ */
3609
+ unusedColumnName(change, name, reserved = []) {
3610
+ const columnsOf = (contract, table) => Object.keys(contract.storage.namespaces[table.namespaceId]?.entries.table?.[table.table]?.columns ?? {});
3611
+ return this.#unused([
3612
+ ...columnsOf(this.#fromContract, change.origin),
3613
+ ...columnsOf(this.#contract, change.destination),
3614
+ ...reserved
3615
+ ], name);
3616
+ }
3617
+ #unused(used, name) {
3618
+ let candidate = `prisma_swap_${name}`;
3619
+ while (used.some((existing) => this.sameName(existing, candidate))) candidate = `${candidate}_`;
3620
+ return candidate;
3621
+ }
3622
+ /** Whether the origin contract has `table`, as the target compares names. */
3623
+ originHasTable(table) {
3624
+ const tables = this.#fromContract.storage.namespaces[table.namespaceId]?.entries.table ?? {};
3625
+ return Object.keys(tables).some((name) => this.sameName(name, table.table));
3626
+ }
3627
+ /** Whether the origin contract has `column` on `table`, as the target compares names. */
3628
+ originHasColumn(table, column) {
3629
+ const stored = this.#fromContract.storage.namespaces[table.namespaceId]?.entries.table?.[table.table];
3630
+ return Object.keys(stored?.columns ?? {}).some((name) => this.sameName(name, column));
3631
+ }
3632
+ /** The models of the origin contract stored in `table`, as the target compares names. */
3633
+ originModelsIn(table) {
3634
+ return modelsStoring(this.#fromContract, table, this.sameName).map(({ coordinate }) => coordinate);
3635
+ }
3636
+ /** The models of the destination contract stored in `table`, as the target compares names. */
3637
+ destinationModelsIn(table) {
3638
+ return modelsStoring(this.#contract, table, this.sameName).map(({ coordinate }) => coordinate);
3639
+ }
3640
+ /** The fields of the origin contract stored in `column` of `table`, as the target compares names. */
3641
+ originFieldsIn(table, column) {
3642
+ return fieldsStoring(this.#fromContract, table, column, this.sameName);
3643
+ }
3644
+ };
3645
+ /** What a table or column change does, in words: the contract change, or the statement that asks for it. */
3646
+ function tableChangeText(change) {
3647
+ const stated = change.renames.find((rename) => rename.statement !== void 0);
3648
+ if (stated !== void 0) return `model "${modelDisplayName(stated.from)}" is renamed to "${modelDisplayName(stated.to)}", which renames table "${change.origin.table}" to "${change.destination.table}"`;
3649
+ return `the table of ${modelsText(change.renames.map((rename) => rename.from))} changes from "${change.origin.table}" to "${change.destination.table}"`;
3650
+ }
3651
+ function columnChangeText(change) {
3652
+ const stated = change.renames.find((rename) => rename.statement !== void 0);
3653
+ if (stated !== void 0) return `field "${fieldDisplayName(stated.from)}" is renamed to "${fieldDisplayName(stated.to)}", which renames column "${change.from}" to "${change.to}"`;
3654
+ return `the column of ${fieldsText(change.renames.map((rename) => rename.from))} changes from "${change.from}" to "${change.to}"`;
3655
+ }
3656
+ /**
3657
+ * The route that works on both commands for a chain or swap of names: a plan that moves each
3658
+ * object to a name nothing uses, then a plan that moves it to its final name.
3659
+ */
3660
+ function temporaryNamesRoute(noun, moves, withStatements) {
3661
+ const give = (name) => joinedList(moves.map((move) => `${move.objects} the ${noun} "${name(move)}"`));
3662
+ return `Make the change in two plans: first give ${give(({ through }) => through)}, ${noun}s nothing uses, and plan and apply that${withStatements ? " with the same statements" : ""}; then give ${give(({ to }) => to)}, and plan again${withStatements ? " without them" : ""}.`;
3663
+ }
3664
+ /**
3665
+ * The changes of `pair` and every change of `changes` linked to them by a name one frees and
3666
+ * another takes, in either direction. All of them must move through names nothing uses before any
3667
+ * takes its final name. The order is `pair`, then the changes after it in the chain, then those
3668
+ * before it.
3669
+ */
3670
+ function linkedChanges(pair, changes, takesFrom) {
3671
+ const linked = [...pair];
3672
+ for (const current of linked) for (const other of changes) {
3673
+ if (linked.includes(other)) continue;
3674
+ if (takesFrom(current, other) || takesFrom(other, current)) linked.push(other);
3675
+ }
3676
+ const ordered = [...pair];
3677
+ const follow = (from, step) => {
3678
+ for (let next = step(from); next !== void 0 && !ordered.includes(next); next = step(next)) ordered.push(next);
3679
+ };
3680
+ follow(pair[1], (change) => linked.find((other) => takesFrom(change, other)));
3681
+ follow(pair[0], (change) => linked.find((other) => takesFrom(other, change)));
3682
+ return [...ordered, ...linked.filter((change) => !ordered.includes(change))];
3683
+ }
3684
+ function tableRoute(pair, changes, renames) {
3685
+ const linked = linkedChanges(pair, changes, (taker, freer) => taker.destination.namespaceId === freer.origin.namespaceId && renames.sameName(taker.destination.table, freer.origin.table));
3686
+ const reserved = [];
3687
+ return temporaryNamesRoute("table", linked.map((moving) => {
3688
+ const { namespaceId, table } = moving.destination;
3689
+ const through = renames.unusedTableName(namespaceId, table, reserved.filter((name) => name.namespaceId === namespaceId).map(({ name }) => name));
3690
+ reserved.push({
3691
+ namespaceId,
3692
+ name: through
3693
+ });
3694
+ return {
3695
+ objects: modelsText(moving.renames.map((rename) => rename.to)),
3696
+ through,
3697
+ to: table
3698
+ };
3699
+ }), linked.some(hasStatement));
3700
+ }
3701
+ function columnRoute(pair, changes, renames) {
3702
+ const linked = linkedChanges(pair, changes, (taker, freer) => renames.sameName(taker.to, freer.from));
3703
+ const reserved = [];
3704
+ return temporaryNamesRoute("column", linked.map((moving) => {
3705
+ const through = renames.unusedColumnName(moving, moving.to, reserved);
3706
+ reserved.push(through);
3707
+ return {
3708
+ objects: fieldsText(moving.renames.map((rename) => rename.to)),
3709
+ through,
3710
+ to: moving.to
3711
+ };
3712
+ }), linked.some(hasStatement));
3713
+ }
3714
+ const ORDER = "A rename onto a name another rename frees, or takes, needs an order or a temporary name that the plan does not work out";
3715
+ /**
3716
+ * Refuses a rename. With the statement that asks for it, the conflict carries the statement; a
3717
+ * rename no statement asks for is refused as a contract change the plan cannot make, and its text
3718
+ * names that change.
3719
+ */
3720
+ function renameRefused(statement, summary, why, location, refusedOperationClass) {
3721
+ return {
3722
+ ...statement === void 0 ? { kind: "unsupportedOperation" } : {
3723
+ kind: "statementRefused",
3724
+ refusedStatement: statement
3725
+ },
3726
+ summary,
3727
+ why,
3728
+ ...refusedOperationClass === void 0 ? {} : { refusedOperationClass },
3729
+ ...location === void 0 ? {} : { location: {
3730
+ namespaceId: location.namespaceId,
3731
+ entityKind: "table",
3732
+ entityName: location.table,
3733
+ ...location.column === void 0 ? {} : { column: location.column }
3734
+ } }
3735
+ };
3736
+ }
3737
+ function contractChangeRefused(summary, why, location) {
3738
+ return renameRefused(void 0, summary, why, location);
3739
+ }
3740
+ function hasStatement(change) {
3741
+ return change.renames.some((rename) => rename.statement !== void 0);
3742
+ }
3743
+ /** How the first of two plans frees a name: it removes what the origin stores there, or the table or column itself when nothing is. */
3744
+ function freeName(kind, held, holders, unused) {
3745
+ if (holders.count === 0) return `remove ${kind} "${held}" or give it a name nothing uses, such as "${unused}"`;
3746
+ const [them, their] = holders.count === 1 ? ["it", "its"] : ["them", "their"];
3747
+ return `remove ${holders.text}, or keep ${them} and change ${their} ${kind} to a name nothing uses, such as "${unused}"`;
3748
+ }
3749
+ /**
3750
+ * Refuses a table rename that no statement asks for when it swaps, chains or merges with another
3751
+ * rename, or moves onto a name the schema being planned from already has. Names compare the way
3752
+ * the target compares them, through `tables`.
3753
+ */
3754
+ function tableRenameConflict(change, current, changes, tables, renames) {
3755
+ const { namespaceId } = change.origin;
3756
+ const from = change.origin.table;
3757
+ const to = change.destination.table;
3758
+ const label = `Cannot rename table "${from}" to "${to}"`;
3759
+ const location = change.origin;
3760
+ const changeText = capitalized(tableChangeText(change));
3761
+ const movingModels = modelsText(change.renames.map((rename) => rename.from));
3762
+ const misread = (table) => `rows of table "${table}" as rows of ${movingModels}`;
3763
+ const others = changes.filter((other) => other !== change);
3764
+ const { sameName } = renames;
3765
+ const [held] = tables.tablesNamed(namespaceId, to).filter((table) => !sameName(table, from) && table !== current);
3766
+ if (held !== void 0) {
3767
+ const heldTable = {
3768
+ namespaceId,
3769
+ table: held
3770
+ };
3771
+ const moved = others.find((other) => other.origin.namespaceId === namespaceId && sameName(other.origin.table, held));
3772
+ if (moved !== void 0) return contractChangeRefused(`${label}: table "${held}" is renamed in the same plan`, `${changeText}, and ${tableChangeText(moved)}. ${ORDER}, and without the renames the plan would read the ${misread(held)}. ${tableRoute([change, moved], others, renames)}`, location);
3773
+ if (!renames.originHasTable(heldTable)) return contractChangeRefused(`${label}: the database has both tables`, `${changeText}, and the database has both table "${from}" and table "${held}". One of two things happened, and each has its own fix. If the rename was half done by hand, or something created table "${held}" before db update ran, table "${from}" holds the rows of ${movingModels}: move into table "${from}" the rows of table "${held}" that it does not already hold, and where both tables hold a row with the same key, keep the version you want in table "${from}"; then drop table "${held}", and run again. If table "${from}" was renamed to "${held}" by hand and the name "${from}" then used for another table, table "${held}" holds the rows of ${movingModels}: drop table "${from}", and run again; to keep the rows of that other table, first move them into a table the contract has, since db update drops every table the contract does not have.`, location);
3774
+ const holders = renames.originModelsIn(heldTable);
3775
+ return contractChangeRefused(`${label}: the schema being planned from already has a table "${to}"${held === to ? "" : `, as "${held}"`}`, `${changeText}, and the schema being planned from already has table "${held}"${holders.length === 0 ? "" : `, the table of ${modelsText(holders)}`}. Without the rename the plan would read the ${misread(held)}. Make the change in two plans: first ${freeName("table", held, {
3776
+ text: modelsText(holders),
3777
+ count: holders.length
3778
+ }, renames.unusedTableName(namespaceId, held))}, and plan and apply that; then make this change and plan again.`, location);
3779
+ }
3780
+ const takes = others.find((other) => hasStatement(other) && other.destination.namespaceId === change.destination.namespaceId && sameName(other.destination.table, from));
3781
+ if (takes !== void 0) return contractChangeRefused(`${label}: another rename in the same plan takes table name "${takes.destination.table}"`, `${changeText}, and ${tableChangeText(takes)}. ${ORDER}. ${tableRoute([change, takes], others, renames)}`, location);
3782
+ }
3783
+ function columnRenameConflict(change, table, current, changes, tables, renames) {
3784
+ const { namespaceId } = change.origin;
3785
+ const label = `Cannot rename column "${table}"."${change.from}" to "${change.to}"`;
3786
+ const location = {
3787
+ namespaceId,
3788
+ table,
3789
+ column: change.from
3790
+ };
3791
+ const changeText = capitalized(columnChangeText(change));
3792
+ const movingFields = fieldsText(change.renames.map((rename) => rename.from));
3793
+ const misread = (column) => `values of column "${column}" as values of ${movingFields}`;
3794
+ const others = changes.filter((other) => other !== change && sameTable(other.origin, change.origin));
3795
+ const { sameName } = renames;
3796
+ const [held] = tables.columnsNamed(namespaceId, table, change.to).filter((column) => !sameName(column, change.from) && column !== current);
3797
+ if (held !== void 0) {
3798
+ const moved = others.find((other) => sameName(other.from, held));
3799
+ if (moved !== void 0) return contractChangeRefused(`${label}: column "${held}" is renamed in the same plan`, `${changeText}, and ${columnChangeText(moved)}. ${ORDER}, and without the renames the plan would read the ${misread(held)}. ${columnRoute([change, moved], others, renames)}`, location);
3800
+ if (!renames.originHasColumn(change.origin, held)) return contractChangeRefused(`${label}: the database has both columns`, `${changeText}, and table "${table}" in the database has both column "${change.from}" and column "${held}". One of two things happened, and each has its own fix. If the rename was half done by hand, or something created column "${held}" before db update ran, column "${change.from}" holds the values of ${movingFields}: copy into column "${change.from}" the value of column "${held}" in each row where column "${held}" holds one and column "${change.from}" holds none, and where both hold a value, keep the one you want in column "${change.from}"; then drop column "${held}", and run again. If column "${change.from}" was renamed to "${held}" by hand and the name "${change.from}" then used for another column, column "${held}" holds the values of ${movingFields}: drop column "${change.from}", and run again; to keep the values of that other column, first move them into a column the contract has, since db update drops every column the contract does not have.`, location);
3801
+ const holders = renames.originFieldsIn(change.origin, held);
3802
+ return contractChangeRefused(`${label}: the schema being planned from already has a column "${change.to}" on table "${table}"${held === change.to ? "" : `, as "${held}"`}`, `${changeText}, and the schema being planned from already has column "${held}" on table "${table}"${holders.length === 0 ? "" : `, the column of ${fieldsText(holders)}`}. Without the rename the plan would read the ${misread(held)}. Make the change in two plans: first ${freeName("column", held, {
3803
+ text: fieldsText(holders),
3804
+ count: holders.length
3805
+ }, renames.unusedColumnName(change, held))}, and plan and apply that; then make this change and plan again.`, location);
3806
+ }
3807
+ const takes = others.find((other) => hasStatement(other) && sameName(other.to, change.from));
3808
+ if (takes !== void 0) return contractChangeRefused(`${label}: another rename in the same plan takes column name "${takes.to}"`, `${changeText}, and ${columnChangeText(takes)}. ${ORDER}. ${columnRoute([change, takes], others, renames)}`, location);
3809
+ }
3810
+ function foundName(found, matches) {
3811
+ return found.find(({ change }) => matches(change))?.name;
3812
+ }
3813
+ /**
3814
+ * The name the table of a column change has in the schema being planned from: its origin name
3815
+ * when the table stays or is renamed from it, the name the schema has it under when that differs,
3816
+ * and `undefined` when the plan does not move the table.
3817
+ */
3818
+ function columnTableInSchema(change, tables, foundTables, renames) {
3819
+ if (renames.inPlace(change.origin, change.destination)) return change.origin.table;
3820
+ const matches = (table) => sameTable(table.origin, change.origin) && sameTable(table.destination, change.destination);
3821
+ const found = foundName(foundTables, matches);
3822
+ if (found !== void 0) return found;
3823
+ return tables.some(matches) ? change.origin.table : void 0;
3824
+ }
3825
+ /**
3826
+ * Checks every rename that no statement asks for against all the renames of the plan, before any
3827
+ * is applied, and returns the first that cannot be planned.
3828
+ */
3829
+ function storageRenameConflict(planned, tables, renames) {
3830
+ for (const change of planned.tables) {
3831
+ if (hasStatement(change)) continue;
3832
+ const conflict = tableRenameConflict(change, foundName(planned.foundTables, (found) => found === change), planned.tables, tables, renames);
3833
+ if (conflict !== void 0) return conflict;
3834
+ }
3835
+ for (const change of planned.columns) {
3836
+ if (hasStatement(change)) continue;
3837
+ const table = columnTableInSchema(change, planned.tables, planned.foundTables, renames);
3838
+ if (table === void 0) continue;
3839
+ const conflict = columnRenameConflict(change, table, foundName(planned.foundColumns, (found) => found === change), planned.columns, tables, renames);
3840
+ if (conflict !== void 0) return conflict;
3841
+ }
3842
+ }
3843
+ /**
3844
+ * What the plan does for a change no statement asks for, from what the schema being planned from
3845
+ * has, as the target compares names: `current`, the name it has for the old one, and `held`, a
3846
+ * name it has for the new one that is not the old one. With the old name, the plan renames it from
3847
+ * `current`, unless `current` is the new name already. With only the new name, the rename is already
3848
+ * done, and a rename gives it the contract's case; when the origin contract has that name too, it is a
3849
+ * rename, which the conflict check refuses. With neither, nothing is planned.
3850
+ */
3851
+ function disposition(to, current, held, originHasHeld) {
3852
+ if (current !== void 0) return current === to ? {
3853
+ kind: "alreadyDone",
3854
+ found: current
3855
+ } : {
3856
+ kind: "rename",
3857
+ found: current
3858
+ };
3859
+ if (held === void 0) return { kind: "none" };
3860
+ if (originHasHeld(held)) return {
3861
+ kind: "rename",
3862
+ found: void 0
3863
+ };
3864
+ return held === to ? {
3865
+ kind: "alreadyDone",
3866
+ found: held
3867
+ } : {
3868
+ kind: "rename",
3869
+ found: held
3870
+ };
3871
+ }
3872
+ /**
3873
+ * The renames the plan makes: every change a statement asks for, and each change no statement
3874
+ * asks for whose whole table or column moves, whose control policy is `managed` in both
3875
+ * contracts, and whose old table or column the schema being planned from has, under the old name
3876
+ * or one the target takes for it. A change whose new name the schema has in place of the old one is
3877
+ * already done. A column change on a table that changes needs the table change planned or already
3878
+ * done.
3879
+ */
3880
+ function plannedStorageRenames(renames, tables) {
3881
+ const { sameName } = renames;
3882
+ const plannedTables = [];
3883
+ const foundTables = [];
3884
+ const record = (change, from, outcome, planned, found) => {
3885
+ if (outcome.kind === "none") return;
3886
+ if (outcome.kind === "rename") planned.push(change);
3887
+ if (outcome.found !== void 0 && outcome.found !== from) found.push({
3888
+ change,
3889
+ name: outcome.found
3890
+ });
3891
+ };
3892
+ for (const change of renames.tableChanges) {
3893
+ if (hasStatement(change)) {
3894
+ plannedTables.push(change);
3895
+ continue;
3896
+ }
3897
+ if (renames.namespaceAfterRenames(change.origin.namespaceId) !== change.destination.namespaceId || !renames.managedOnBothSides(change) || renames.sharedTable(change) !== void 0) continue;
3898
+ const { namespaceId, table: from } = change.origin;
3899
+ const to = change.destination.table;
3900
+ const [current] = tables.tablesNamed(namespaceId, from);
3901
+ const [held] = tables.tablesNamed(namespaceId, to).filter((table) => !sameName(table, from));
3902
+ record(change, from, disposition(to, current, held, (name) => renames.originHasTable({
3903
+ namespaceId,
3904
+ table: name
3905
+ })), plannedTables, foundTables);
3906
+ }
3907
+ const plannedColumns = [];
3908
+ const foundColumns = [];
3909
+ for (const change of renames.columnChanges) {
3910
+ if (hasStatement(change)) {
3911
+ plannedColumns.push(change);
3912
+ continue;
3913
+ }
3914
+ const table = columnTableInSchema(change, plannedTables, foundTables, renames);
3915
+ if (table === void 0 || !renames.managedOnBothSides(change) || renames.sharedColumn(change) !== void 0) continue;
3916
+ const { namespaceId } = change.origin;
3917
+ const [current] = tables.columnsNamed(namespaceId, table, change.from);
3918
+ const [held] = tables.columnsNamed(namespaceId, table, change.to).filter((column) => !sameName(column, change.from));
3919
+ const outcome = disposition(change.to, current, held, (name) => renames.originHasColumn(change.origin, name));
3920
+ record(change, change.from, outcome, plannedColumns, foundColumns);
3921
+ }
3922
+ return {
3923
+ tables: plannedTables,
3924
+ columns: plannedColumns,
3925
+ foundTables,
3926
+ foundColumns
3927
+ };
3928
+ }
3929
+ /**
3930
+ * The storage effect of a model rename: the origin model's table compared with the destination
3931
+ * model's. Equal tables mean the rename needs no storage change.
3932
+ */
3933
+ function modelRenameStorageEffect(statement, fromContract, contract) {
3934
+ const from = modelTable(fromContract, statement.from);
3935
+ if (from === void 0) return notOk({
3936
+ kind: "noTable",
3937
+ model: statement.from
3938
+ });
3939
+ const to = modelTable(contract, statement.to);
3940
+ if (to === void 0) return notOk({
3941
+ kind: "noTable",
3942
+ model: statement.to
3943
+ });
3944
+ if (from.namespaceId !== to.namespaceId) return ok({
3945
+ kind: "moveNamespace",
3946
+ from,
3947
+ to
3948
+ });
3949
+ if (from.table === to.table) return ok({ kind: "unchanged" });
3950
+ return ok({
3951
+ kind: "renameTable",
3952
+ rename: {
3953
+ namespaceId: from.namespaceId,
3954
+ from: from.table,
3955
+ to: to.table
3956
+ }
3957
+ });
3958
+ }
3959
+ /**
3960
+ * The storage effect of a field rename: the origin field's column compared with the destination
3961
+ * field's. A relation field has no column on either side, and equal columns need no change.
3962
+ */
3963
+ function fieldRenameStorageEffect(statement, fromContract, contract) {
3964
+ const table = modelTable(fromContract, statement.from);
3965
+ if (table === void 0) return notOk({
3966
+ kind: "noTable",
3967
+ model: statement.from
3968
+ });
3969
+ const from = fieldColumn(fromContract, statement.from);
3970
+ const to = fieldColumn(contract, statement.to);
3971
+ if (from === void 0 && to === void 0) return ok({ kind: "unchanged" });
3972
+ if (from === void 0 || to === void 0) return notOk({ kind: "columnOnOneSide" });
3973
+ if (from === to) return ok({ kind: "unchanged" });
3974
+ return ok({
3975
+ kind: "renameColumn",
3976
+ table,
3977
+ from,
3978
+ to
3979
+ });
3980
+ }
3981
+ function operationsOf(call) {
3982
+ return [call, ...call.companions];
3983
+ }
3984
+ /** The origins of a plan whose statements renamed and moved nothing. */
3985
+ const NO_RENAMED_ORIGINS = {
3986
+ originTable: (current) => current,
3987
+ originColumn: (_origin, column) => column
3988
+ };
3989
+ const PLANNED_WITH_DIFF = { kind: "plannedWithDiff" };
3990
+ function plannedAt(operationIndexes) {
3991
+ return {
3992
+ kind: "planned",
3993
+ operationIndexes
3994
+ };
3995
+ }
3996
+ const DRIFTED = "so the database has drifted from that contract. Inspect it with prisma db schema, or leave out this statement.";
3997
+ const UNMATCHED = "A statement plans the rename a hand-written rename call makes, and that call does not match the contracts. Leave out this statement.";
3998
+ function leaveOutShared(moving) {
3999
+ return `Leave out this statement to plan the change without moving them: the plan then asks about the data it drops. A question about ${moving} offers this same rename again, which is refused again for the same reason. Answer it with --delete, which it also offers: that plans the change and deletes the data.`;
4000
+ }
4001
+ const HAND_WRITTEN_WITH_MIGRATION_PLAN = "To keep the data with migration plan, write this change as a hand-written migration instead: ";
4002
+ function tableKey(table) {
4003
+ return JSON.stringify([table.namespaceId, table.table]);
4004
+ }
4005
+ /** A contract space other than the one planned that declares the namespace, if any. */
4006
+ function otherSpaceDeclaring(ownership, namespaceId) {
4007
+ return (ownership.oracle?.namespaceDeclaringSpaces(namespaceId) ?? []).find((spaceId) => spaceId !== ownership.spaceId);
4008
+ }
4009
+ function withoutNamespacesRefused(statement, label) {
4010
+ return renameRefused(statement, `${label}: the database target keeps every table in one namespace`, "This database target has no namespaces, so a statement cannot rename a namespace or move a model to another one. Leave out this statement.", void 0);
4011
+ }
4012
+ function namespaceText(namespaceId) {
4013
+ return namespaceId === UNBOUND_NAMESPACE_ID ? "the unbound namespace" : `namespace "${namespaceId}"`;
4014
+ }
4015
+ function qualifiedTable(table) {
4016
+ return table.namespaceId === UNBOUND_NAMESPACE_ID ? table.table : `${table.namespaceId}.${table.table}`;
4017
+ }
4018
+ function tableRenameRefused(statement, label, rename, mismatch) {
4019
+ switch (mismatch.kind) {
4020
+ case "tableMissing": return renameRefused(statement, `${label}: the schema being planned from has no table "${rename.from}"`, `The database has no table "${rename.from}", although the contract it was last updated to names it, ${DRIFTED}`, {
4021
+ namespaceId: rename.namespaceId,
4022
+ table: rename.from
4023
+ });
4024
+ case "nameTaken": return renameRefused(statement, `${label}: the schema being planned from already has a table "${rename.to}"${mismatch.taken === rename.to ? "" : `, as "${mismatch.taken}"`}`, `A rename cannot replace a table that already exists. Rename or drop table "${mismatch.taken}" first, or leave out this statement.`, {
4025
+ namespaceId: rename.namespaceId,
4026
+ table: rename.to
4027
+ });
4028
+ case "tableInManyNamespaces":
4029
+ case "notInEndContract": return renameRefused(statement, `${label}: ${tableRenameMismatchReason(rename, mismatch)}`, UNMATCHED, {
4030
+ namespaceId: rename.namespaceId,
4031
+ table: rename.from
4032
+ });
4033
+ }
4034
+ }
4035
+ function columnRenameRefused(statement, label, rename, mismatch) {
4036
+ const table = {
4037
+ namespaceId: rename.namespaceId,
4038
+ table: rename.table
4039
+ };
4040
+ switch (mismatch.kind) {
4041
+ case "tableMissing": return renameRefused(statement, `${label}: the schema being planned from has no table "${rename.table}"`, `The database has no table "${rename.table}", although the contract it was last updated to names it, ${DRIFTED}`, table);
4042
+ case "columnMissing": return renameRefused(statement, `${label}: the schema being planned from has no column "${rename.from}" on table "${rename.table}"`, `The database has no column "${rename.from}" on table "${rename.table}", although the contract it was last updated to names it, ${DRIFTED}`, {
4043
+ ...table,
4044
+ column: rename.from
4045
+ });
4046
+ case "nameTaken": return renameRefused(statement, `${label}: the schema being planned from already has a column "${mismatch.taken}" on table "${rename.table}"`, `A rename cannot replace a column that already exists. Rename or drop column "${mismatch.taken}" of table "${rename.table}" first, or leave out this statement.`, {
4047
+ ...table,
4048
+ column: rename.to
4049
+ });
4050
+ case "tableInManyNamespaces":
4051
+ case "notInEndContract": return renameRefused(statement, `${label}: ${columnRenameMismatchReason(rename, mismatch)}`, UNMATCHED, {
4052
+ ...table,
4053
+ column: rename.from
4054
+ });
4055
+ }
4056
+ }
4057
+ function planned(operationIndexes) {
4058
+ return operationIndexes.ok ? ok(plannedAt(operationIndexes.value)) : operationIndexes;
4059
+ }
4060
+ var StatementPlanner = class {
4061
+ #fromContract;
4062
+ #contract;
4063
+ #policy;
4064
+ #target;
4065
+ /** Where each table renamed or moved so far is in the working schema, keyed by its origin place. */
4066
+ #renamedTables = /* @__PURE__ */ new Map();
4067
+ /** The origin place of each table renamed or moved so far, keyed as `#renamedTables`. */
4068
+ #originTables = /* @__PURE__ */ new Map();
4069
+ /** Each column renamed so far, keyed by its origin table and origin name: its name now. */
4070
+ #renamedColumns = /* @__PURE__ */ new Map();
4071
+ /** The name each namespace renamed so far has in the working schema, keyed by its origin name. */
4072
+ #renamedNamespaces = /* @__PURE__ */ new Map();
4073
+ #ownership;
4074
+ #storageRenames;
4075
+ calls = [];
4076
+ /** How many operations the calls planned so far lower to. */
4077
+ #operationCount = 0;
4078
+ tableRenames = [];
4079
+ columnRenames = [];
4080
+ constructor(input) {
4081
+ this.#fromContract = input.fromContract;
4082
+ this.#contract = input.contract;
4083
+ this.#policy = input.policy;
4084
+ this.#target = input.target;
4085
+ this.#ownership = input.ownership;
4086
+ this.#storageRenames = input.storageRenames;
4087
+ }
4088
+ /** Renames a table no statement asks for, where it is in the working schema now. */
4089
+ planTableChange(change) {
4090
+ const current = this.#current(change.origin);
4091
+ return this.#renameTable({
4092
+ statement: void 0,
4093
+ change: tableChangeText(change)
4094
+ }, `Cannot rename table "${current.table}" to "${change.destination.table}"`, change.origin, {
4095
+ namespaceId: current.namespaceId,
4096
+ from: current.table,
4097
+ to: change.destination.table
4098
+ });
4099
+ }
4100
+ /** Renames a column no statement asks for, as the working schema has it and its table now. */
4101
+ planColumnChange(change) {
4102
+ const current = this.#current(change.origin);
4103
+ const from = this.#currentColumn(change.origin, change.from);
4104
+ return this.#renameColumn({
4105
+ statement: void 0,
4106
+ change: columnChangeText(change)
4107
+ }, `Cannot rename column "${current.table}"."${from}" to "${change.to}"`, change.origin, change.from, {
4108
+ namespaceId: current.namespaceId,
4109
+ table: current.table,
4110
+ from,
4111
+ to: change.to
4112
+ });
4113
+ }
4114
+ /**
4115
+ * Records that the working schema has the table of a change no statement asks for as `table`:
4116
+ * later renames and questions find it there, as after a planned rename.
4117
+ */
4118
+ recordTableFound(change, table) {
4119
+ const current = this.#current(change.origin);
4120
+ this.#renamedTables.set(tableKey(change.origin), {
4121
+ namespaceId: current.namespaceId,
4122
+ table
4123
+ });
4124
+ this.#originTables.set(tableKey(change.origin), change.origin);
4125
+ return ok([]);
4126
+ }
4127
+ /** Records that the working schema has the column of a change no statement asks for as `column`. */
4128
+ recordColumnFound(change, column) {
4129
+ this.#recordColumn(change.origin, change.from, column);
4130
+ return ok([]);
4131
+ }
4132
+ /** Plans one statement; the result is the operations it accounts for. */
4133
+ plan(statement) {
4134
+ switch (statement.entity) {
4135
+ case "namespace": return planned(this.#planNamespace(statement));
4136
+ case "model": return planned(this.#planModel(statement));
4137
+ case "field": return planned(this.#planField(statement));
4138
+ case "enumValue":
4139
+ case "valueObjectField": return ok(PLANNED_WITH_DIFF);
4140
+ }
4141
+ }
4142
+ #recordColumn(origin, from, to) {
4143
+ this.#renamedColumns.set(JSON.stringify([tableKey(origin), from]), {
4144
+ origin,
4145
+ from,
4146
+ to
4147
+ });
4148
+ }
4149
+ /** The name a column of an origin table has in the working schema, after the renames planned so far. */
4150
+ #currentColumn(origin, column) {
4151
+ return this.#renamedColumns.get(JSON.stringify([tableKey(origin), column]))?.to ?? column;
4152
+ }
4153
+ /** Where a table of the origin is in the working schema, after the renames planned so far. */
4154
+ #current(origin) {
4155
+ const table = this.#renamedTables.get(tableKey(origin)) ?? origin;
4156
+ return {
4157
+ namespaceId: this.#renamedNamespaces.get(table.namespaceId) ?? table.namespaceId,
4158
+ table: table.table
4159
+ };
4160
+ }
4161
+ #planNamespace(statement) {
4162
+ const rename = {
4163
+ from: statement.from,
4164
+ to: statement.to
4165
+ };
4166
+ const label = `Cannot rename namespace "${rename.from}" to "${rename.to}"`;
4167
+ const namespaces = this.#target.namespaces;
4168
+ if (namespaces === void 0) return notOk(withoutNamespacesRefused(statement, label));
4169
+ const movePerModel = `--rename ${rename.from}.<Model>:${rename.to}.<Model>`;
4170
+ const refusal = namespaces.namespaceRenameRefusal(rename);
4171
+ if (refusal !== void 0) return notOk(renameRefused(statement, `${label}: ${refusal.reason}`, refusal.fix, void 0));
4172
+ const otherSpace = this.#ownership === void 0 ? void 0 : otherSpaceDeclaring(this.#ownership, rename.from);
4173
+ if (otherSpace !== void 0) return notOk(renameRefused(statement, `${label}: contract space "${otherSpace}" also declares it`, `Renaming the namespace would rename it under contract space "${otherSpace}" too, whose contract still names it "${rename.from}". Leave out this statement, or move each model with ${movePerModel} instead.`, void 0));
4174
+ const tables = Object.keys(this.#contract.storage.namespaces[rename.to]?.entries.table ?? {});
4175
+ for (const table of tables) {
4176
+ const controlPolicy = tableControlPolicy(this.#contract, {
4177
+ namespaceId: rename.to,
4178
+ table
4179
+ });
4180
+ if (controlPolicy === "managed") continue;
4181
+ return notOk(renameRefused(statement, `${label}: table "${table}" has control policy "${controlPolicy}"`, `Statements rename only namespaces whose tables all have control policy "managed"; table "${table}" is "${controlPolicy}". Make the change in the database yourself and leave out this statement.`, {
4182
+ namespaceId: rename.to,
4183
+ table
4184
+ }));
4185
+ }
4186
+ const schemaTables = this.#target.tables();
4187
+ if (!schemaTables.hasNamespace(rename.from)) return notOk(renameRefused(statement, `${label}: the schema being planned from has no namespace "${rename.from}"`, `The database has no namespace "${rename.from}", although the contract it was last updated to names it, ${DRIFTED}`, void 0));
4188
+ if (schemaTables.hasNamespace(rename.to)) return notOk(renameRefused(statement, `${label}: the database already has a namespace "${rename.to}"`, `The database already has a namespace "${rename.to}", which the contract it was last updated to does not declare. If it holds nothing, drop or rename it in the database yourself; otherwise move each model with ${movePerModel} instead of this statement.`, void 0));
4189
+ const planned = this.#emit({ statement }, label, void 0, namespaces.renameNamespaceCall(rename));
4190
+ if (planned.ok) this.#renamedNamespaces.set(rename.from, rename.to);
4191
+ return planned;
4192
+ }
4193
+ #controlPolicyRefusal(statement, label, destinationTable) {
4194
+ const controlPolicy = tableControlPolicy(this.#contract, destinationTable);
4195
+ if (controlPolicy === "managed") return void 0;
4196
+ return renameRefused(statement, `${label}: the table's control policy is "${controlPolicy}"`, `Statements rename only tables, and columns of tables, whose control policy is "managed"; table "${destinationTable.table}" is "${controlPolicy}". Make the change in the database yourself and leave out this statement.`, destinationTable);
4197
+ }
4198
+ #emit(source, label, location, call) {
4199
+ const refused = operationsOf(call).map((operation) => operation.operationClass).find((operationClass) => !this.#policy.allowedOperationClasses.includes(operationClass));
4200
+ if (refused !== void 0) {
4201
+ const allowed = this.#policy.allowedOperationClasses.map((c) => `"${c}"`).join(", ");
4202
+ return notOk(renameRefused(source.statement, `${label}: the plan does not allow "${refused}" operations`, source.statement === void 0 ? `${capitalized(source.change)}, and the rename produces a "${refused}" operation, which this command does not plan: it plans only ${allowed} operations. Make the change with a command that allows "${refused}" operations, such as db update or migration plan.` : `The rename produces a "${refused}" operation, and this command plans only ${allowed} operations. Leave out this statement, or make the change with a command that allows "${refused}" operations, such as migration plan.`, location, refused));
4203
+ }
4204
+ this.#target.apply(call);
4205
+ this.calls.push(call);
4206
+ const first = this.#operationCount;
4207
+ this.#operationCount += operationsOf(call).length;
4208
+ return ok(operationsOf(call).map((_, offset) => first + offset));
4209
+ }
4210
+ #planModel(statement) {
4211
+ const worked = modelRenameStorageEffect(statement, this.#fromContract, this.#contract);
4212
+ if (!worked.ok) return notOk(renameRefused(statement, `Model "${modelDisplayName(worked.failure.model)}" has no table in its contract`, `A model rename renames the model's table, and model "${modelDisplayName(worked.failure.model)}" has none in its contract. Leave out this statement.`, void 0));
4213
+ const effect = worked.value;
4214
+ if (effect.kind === "unchanged") return ok([]);
4215
+ const shared = this.#sharedTableRefusal(statement);
4216
+ if (shared !== void 0) return notOk(shared);
4217
+ const [origin, destination] = effect.kind === "moveNamespace" ? [effect.from, effect.to] : [{
4218
+ namespaceId: effect.rename.namespaceId,
4219
+ table: effect.rename.from
4220
+ }, {
4221
+ namespaceId: effect.rename.namespaceId,
4222
+ table: effect.rename.to
4223
+ }];
4224
+ const current = this.#current(origin);
4225
+ if (current.namespaceId === destination.namespaceId) {
4226
+ if (current.table === destination.table) return ok([]);
4227
+ return this.#planTableRename(statement, origin, {
4228
+ namespaceId: destination.namespaceId,
4229
+ from: current.table,
4230
+ to: destination.table
4231
+ });
4232
+ }
4233
+ return this.#planMove(statement, origin, current, destination);
4234
+ }
4235
+ #planTableRename(statement, origin, rename) {
4236
+ const destinationTable = {
4237
+ namespaceId: rename.namespaceId,
4238
+ table: rename.to
4239
+ };
4240
+ const label = `Cannot rename table "${rename.from}" to "${rename.to}"`;
4241
+ const policyRefusal = this.#controlPolicyRefusal(statement, label, destinationTable);
4242
+ if (policyRefusal !== void 0) return notOk(policyRefusal);
4243
+ const checked = checkTableRename(this.#target.tables(), this.#contract, rename);
4244
+ if (!checked.ok) return notOk(tableRenameRefused(statement, label, rename, checked.failure));
4245
+ return this.#renameTable({ statement }, label, origin, rename);
4246
+ }
4247
+ #renameTable(source, label, origin, rename) {
4248
+ const destinationTable = {
4249
+ namespaceId: rename.namespaceId,
4250
+ table: rename.to
4251
+ };
4252
+ const planned = this.#emit(source, label, destinationTable, this.#target.renameTableCall(rename));
4253
+ if (planned.ok) {
4254
+ this.tableRenames.push(rename);
4255
+ this.#renamedTables.set(tableKey(origin), destinationTable);
4256
+ this.#originTables.set(tableKey(origin), origin);
4257
+ }
4258
+ return planned;
4259
+ }
4260
+ #sharedTableRefusal(statement) {
4261
+ const rename = this.#storageRenames.models.find((model) => model.statement === statement);
4262
+ const change = rename === void 0 ? void 0 : this.#storageRenames.tableChangeOf(rename);
4263
+ const shared = change === void 0 ? void 0 : this.#storageRenames.sharedTable(change);
4264
+ if (change === void 0 || shared === void 0) return void 0;
4265
+ const from = change.origin.table;
4266
+ const to = change.destination.table;
4267
+ const label = `Cannot rename table "${from}" to "${to}"`;
4268
+ const moving = change.renames.map((renamed) => renamed.from);
4269
+ const others = modelsText(shared.objects);
4270
+ return renameRefused(statement, shared.kind === "split" ? `${label}: table "${from}" also stores ${others}` : `${label}: table "${to}" also stores ${others}, whose rows are not in table "${from}"`, shared.kind === "split" ? `A table rename moves every row of the table, and the rows of ${others} do not move to table "${to}". Moving the rows of one model out of a table it shares with others is a data migration, which a plan does not write. ${leaveOutShared(modelsText(moving))} ${HAND_WRITTEN_WITH_MIGRATION_PLAN}${handWrittenMigrationSteps(`the rows of ${modelsText(moving)} into table "${to}"`)}` : `A table rename moves the rows of one table, and table "${to}" would also store the rows of ${others}. Moving the rows of two tables into one is a data migration, which a plan does not write. ${leaveOutShared(modelsText(moving))} ${HAND_WRITTEN_WITH_MIGRATION_PLAN}${handWrittenMigrationSteps(`the rows of ${modelsText(moving)}, and those of ${others} that table "${to}" does not already hold, into table "${to}"`)}`, change.origin);
4271
+ }
4272
+ #sharedColumnRefusal(statement) {
4273
+ const rename = this.#storageRenames.fields.find((field) => field.statement === statement);
4274
+ const change = rename === void 0 ? void 0 : this.#storageRenames.columnChangeOf(rename);
4275
+ const shared = change === void 0 ? void 0 : this.#storageRenames.sharedColumn(change);
4276
+ if (change === void 0 || shared === void 0) return void 0;
4277
+ const { from, to } = change;
4278
+ const label = `Cannot rename column "${change.origin.table}"."${from}" to "${to}"`;
4279
+ const moving = change.renames.map((renamed) => renamed.from);
4280
+ const others = fieldsText(shared.objects);
4281
+ return renameRefused(statement, shared.kind === "split" ? `${label}: column "${from}" also stores ${others}` : `${label}: column "${to}" also stores ${others}, whose values are not in column "${from}"`, shared.kind === "split" ? `A column rename moves the values of every row, and the values of ${others} do not move to column "${to}". Moving the values of one field out of a column it shares with others is a data migration, which a plan does not write. ${leaveOutShared(fieldsText(moving))} ${HAND_WRITTEN_WITH_MIGRATION_PLAN}${handWrittenMigrationSteps(`the values of ${fieldsText(moving)} into column "${to}"`)}` : `A column rename moves the values of one column, and column "${to}" would also store the values of ${others}. Moving the values of two columns into one is a data migration, which a plan does not write. ${leaveOutShared(fieldsText(moving))} ${HAND_WRITTEN_WITH_MIGRATION_PLAN}${handWrittenMigrationSteps(`the values of ${fieldsText(moving)}, and those of ${others} that column "${to}" does not already hold, into column "${to}"`)}`, {
4282
+ ...change.origin,
4283
+ column: from
4284
+ });
4285
+ }
4286
+ /**
4287
+ * Moves the table to the destination namespace under its own name, creating the namespace first
4288
+ * when the working schema lacks it, then renames it there when the destination names it
4289
+ * differently. The statement accounts for the move and the rename, not the namespace's creation.
4290
+ */
4291
+ #planMove(statement, origin, from, to) {
4292
+ const label = `Cannot move table "${from.table}" from ${namespaceText(from.namespaceId)} to ${namespaceText(to.namespaceId)}`;
4293
+ const namespaces = this.#target.namespaces;
4294
+ if (namespaces === void 0) return notOk(withoutNamespacesRefused(statement, label));
4295
+ if (to.namespaceId === UNBOUND_NAMESPACE_ID) return notOk(renameRefused(statement, `Cannot move table "${from.table}" from ${namespaceText(from.namespaceId)} to the unbound namespace: the unbound namespace has no fixed place in the database`, `A table of the unbound namespace lives wherever the connection that uses it looks, so a migration cannot move a table there. Move the table yourself and leave out this statement, or keep the model in ${namespaceText(from.namespaceId)}.`, from));
4296
+ const moved = {
4297
+ namespaceId: to.namespaceId,
4298
+ table: from.table
4299
+ };
4300
+ const policyRefusal = this.#controlPolicyRefusal(statement, label, to);
4301
+ if (policyRefusal !== void 0) return notOk(policyRefusal);
4302
+ const tables = this.#target.tables();
4303
+ if (!tables.hasTable(from.namespaceId, from.table)) return notOk(renameRefused(statement, `${label}: the schema being planned from has no table "${qualifiedTable(from)}"`, `The database has no table "${qualifiedTable(from)}", although the contract it was last updated to names it, ${DRIFTED}`, from));
4304
+ const [taken] = [...tables.tablesNamed(to.namespaceId, from.table), ...tables.tablesNamed(to.namespaceId, to.table)];
4305
+ if (taken !== void 0) {
4306
+ const takenTable = qualifiedTable({
4307
+ namespaceId: to.namespaceId,
4308
+ table: taken
4309
+ });
4310
+ return notOk(renameRefused(statement, `${label}: the schema being planned from already has a table "${takenTable}"`, `A move cannot replace a table that already exists. Rename, move or drop table "${takenTable}" first, or leave out this statement.`, {
4311
+ namespaceId: to.namespaceId,
4312
+ table: taken
4313
+ }));
4314
+ }
4315
+ for (const call of namespaces.createNamespaceCalls(to.namespaceId)) {
4316
+ const created = this.#emit({ statement }, label, moved, call);
4317
+ if (!created.ok) return created;
4318
+ }
4319
+ const planned = this.#emit({ statement }, label, moved, namespaces.moveTableCall({
4320
+ table: from.table,
4321
+ from: from.namespaceId,
4322
+ to: to.namespaceId
4323
+ }));
4324
+ if (!planned.ok) return planned;
4325
+ this.#renamedTables.set(tableKey(origin), moved);
4326
+ this.#originTables.set(tableKey(origin), origin);
4327
+ if (to.table === from.table) return planned;
4328
+ const renamed = this.#planTableRename(statement, origin, {
4329
+ namespaceId: to.namespaceId,
4330
+ from: from.table,
4331
+ to: to.table
4332
+ });
4333
+ if (!renamed.ok) return renamed;
4334
+ return ok([...planned.value, ...renamed.value]);
4335
+ }
4336
+ #planField(statement) {
4337
+ const worked = fieldRenameStorageEffect(statement, this.#fromContract, this.#contract);
4338
+ if (!worked.ok && worked.failure.kind === "noTable") return notOk(renameRefused(statement, `Model "${modelDisplayName(worked.failure.model)}" has no table in its contract`, `A field rename renames the field's column, and model "${modelDisplayName(worked.failure.model)}" has no table in its contract. Leave out this statement.`, void 0));
4339
+ if (!worked.ok) return notOk(renameRefused(statement, `Field "${modelDisplayName(statement.from)}.${statement.from.field}" has a column on one side only of ${describeMigrationStatement(statement, this.#fromContract, this.#contract)}`, "A field rename renames a column or changes nothing in storage, and this field gains or loses its column. Leave out this statement and plan the change without it.", void 0));
4340
+ const effect = worked.value;
4341
+ if (effect.kind === "unchanged") return ok([]);
4342
+ const current = this.#current(effect.table);
4343
+ const table = current.table;
4344
+ const destinationTable = modelTable(this.#contract, statement.to);
4345
+ if (destinationTable !== void 0 && !sameTable(destinationTable, current)) return notOk(renameRefused(statement, `Cannot rename column "${table}"."${effect.from}": the model's table changes from "${table}" to "${destinationTable.table}", and the plan does not rename it`, `The plan renames a table only when every model stored in it moves to the same new table and its control policy is "managed" in both contracts, so the column would be renamed on a table the destination does not store the model in. Leave out this statement.`, {
4346
+ namespaceId: current.namespaceId,
4347
+ table,
4348
+ column: effect.from
4349
+ }));
4350
+ const rename = {
4351
+ namespaceId: current.namespaceId,
4352
+ table,
4353
+ from: this.#currentColumn(effect.table, effect.from),
4354
+ to: effect.to
4355
+ };
4356
+ const tableLocation = {
4357
+ namespaceId: rename.namespaceId,
4358
+ table
4359
+ };
4360
+ const label = `Cannot rename column "${table}"."${rename.from}" to "${rename.to}"`;
4361
+ const policyRefusal = this.#controlPolicyRefusal(statement, label, tableLocation);
4362
+ if (policyRefusal !== void 0) return notOk(policyRefusal);
4363
+ const renamedAlready = rename.from === rename.to;
4364
+ if (!renamedAlready) {
4365
+ const checked = checkColumnRename(this.#target.tables(), this.#contract, rename);
4366
+ if (!checked.ok) return notOk(columnRenameRefused(statement, label, rename, checked.failure));
3634
4367
  }
3635
- if (text.startsWith(quote.close, index)) {
3636
- const after = index + quote.close.length;
3637
- if (!quote.doubledCloseEscapes || !text.startsWith(quote.close, after)) return after;
3638
- index = after + quote.close.length;
3639
- continue;
4368
+ const shared = this.#sharedColumnRefusal(statement);
4369
+ if (shared !== void 0) return notOk(shared);
4370
+ if (renamedAlready) return ok([]);
4371
+ return this.#renameColumn({ statement }, label, effect.table, effect.from, rename);
4372
+ }
4373
+ #renameColumn(source, label, origin, originColumn, rename) {
4374
+ const planned = this.#emit(source, label, {
4375
+ namespaceId: rename.namespaceId,
4376
+ table: rename.table,
4377
+ column: rename.from
4378
+ }, this.#target.renameColumnCall(rename));
4379
+ if (planned.ok) {
4380
+ this.columnRenames.push(rename);
4381
+ this.#recordColumn(origin, originColumn, rename.to);
3640
4382
  }
3641
- index += 1;
4383
+ return planned;
3642
4384
  }
3643
- }
4385
+ /** The origins of the working schema's tables and columns, as the statements left them. */
4386
+ origins() {
4387
+ return {
4388
+ originTable: (current) => {
4389
+ for (const origin of this.#originTables.values()) if (sameTable(this.#current(origin), current)) return origin;
4390
+ for (const [origin, renamed] of this.#renamedNamespaces) if (renamed === current.namespaceId) return {
4391
+ namespaceId: origin,
4392
+ table: current.table
4393
+ };
4394
+ return current;
4395
+ },
4396
+ originColumn: (origin, column) => [...this.#renamedColumns.values()].find((renamed) => sameTable(renamed.origin, origin) && renamed.to === column)?.from ?? column
4397
+ };
4398
+ }
4399
+ };
3644
4400
  /**
3645
- * Returns what in `text` could end or extend the statement a migration writes it into, such as the
3646
- * conversion of an `ALTER COLUMN … USING` clause or a column of an `INSERT … SELECT` list, or
3647
- * undefined when it finds nothing. Text inside the quotes of `quoting` may hold anything; outside
3648
- * them the text may not hold a semicolon, a SQL comment, dollar quoting, or, outside parentheses
3649
- * and brackets, a comma or a keyword that would end the expression. `FROM` directly after
3650
- * `DISTINCT`, as in `IS DISTINCT FROM`, belongs to the expression. It checks for these mistakes
3651
- * only; it does not parse the SQL.
4401
+ * Plans the renames of a plan against a target's working schema: those its statements ask for, and
4402
+ * those of the tables and columns whose models and fields both contracts name alike. Every rename
4403
+ * no statement asks for is checked against all the others first. Then, in order: namespace
4404
+ * renames, the table renames no statement asks for, the other statements in the order given, and
4405
+ * the column renames no statement asks for. Each model rename becomes a table rename and each field
4406
+ * rename a column rename, computed against the schema earlier renames left, then applied to it.
4407
+ * The first rename that cannot be planned fails the whole plan; its conflict carries the statement
4408
+ * that asks for it, if one does.
3652
4409
  */
3653
- function checkSqlExpressionText(text, quoting) {
3654
- let depth = 0;
3655
- let index = 0;
3656
- let previousWord;
3657
- while (index < text.length) {
3658
- const character = text[index] ?? "";
3659
- const quote = quoteAt(text, index, quoting);
3660
- if (quote !== void 0) {
3661
- const end = endOfQuote(text, index, quote);
3662
- if (end === void 0) return "a quote that is not closed";
3663
- index = end;
3664
- previousWord = void 0;
3665
- continue;
3666
- }
3667
- if (character === ";") return "a semicolon outside a quoted literal";
3668
- if (text.startsWith("--", index) || text.startsWith("/*", index)) return "a SQL comment";
3669
- DOLLAR_QUOTE.lastIndex = index;
3670
- if (character === "$" && DOLLAR_QUOTE.test(text)) return "dollar quoting";
3671
- if (character === "," && depth === 0) return "a comma outside parentheses";
3672
- if (character === "(" || character === "[") depth += 1;
3673
- if (character === ")" || character === "]") {
3674
- depth -= 1;
3675
- if (depth < 0) return "parentheses that do not match";
3676
- }
3677
- WORD.lastIndex = index;
3678
- const word = /[A-Za-z_]/.test(character) ? WORD.exec(text)?.[0].toUpperCase() : void 0;
3679
- if (word !== void 0) {
3680
- if (depth === 0 && STATEMENT_KEYWORDS.has(word) && !(word === "FROM" && previousWord === "DISTINCT")) return `the keyword ${word} outside parentheses`;
3681
- previousWord = word;
3682
- index += word.length;
3683
- continue;
3684
- }
3685
- if (!/\s/.test(character)) previousWord = void 0;
3686
- index += 1;
4410
+ function planStatements(input) {
4411
+ const { fromContract } = input;
4412
+ const [first] = input.statements;
4413
+ if (fromContract === null) {
4414
+ if (first === void 0) return ok({
4415
+ calls: [],
4416
+ tableRenames: [],
4417
+ columnRenames: [],
4418
+ alreadyRenamedTables: [],
4419
+ plannedStatements: [],
4420
+ origins: NO_RENAMED_ORIGINS,
4421
+ storageRenames: void 0
4422
+ });
4423
+ return notOk(renameRefused(first, "Statements need an origin contract, and this plan has none", "A statement names models and fields of the origin contract, and this plan has none. Plan from a contract that has the old names, or leave out the statement.", void 0));
3687
4424
  }
3688
- return depth === 0 ? void 0 : "parentheses that do not match";
3689
- }
3690
- /** Whether `slot` is a placeholder the user has not filled yet. */
3691
- function isUnfilledSlot(slot) {
3692
- return slot?.kind === "placeholder";
3693
- }
3694
- /** The SQL of a written slot; undefined for an unfilled one or none. */
3695
- function sqlOfSlot(slot) {
3696
- return slot?.kind === "sql" ? slot.sql : void 0;
3697
- }
3698
- /** The slot as `migration.ts` writes it: SQL text written through `sql`, or a `placeholder(...)` call. */
3699
- function slotSource(slot, sql) {
3700
- return slot.kind === "placeholder" ? `placeholder(${jsonToTsSource(slot.slot)})` : sql.source(slot.sql);
3701
- }
3702
- /** `moduleSpecifier` is the module the generated file imports `sql` from. */
3703
- function createSqlTextSources(moduleSpecifier) {
3704
- let usesTag = false;
3705
- return {
3706
- source(text) {
3707
- const written = tsTaggedTemplateSource("sql", text);
3708
- usesTag ||= written.usesTag;
3709
- return written.source;
3710
- },
3711
- imports() {
3712
- return usesTag ? [{
3713
- moduleSpecifier,
3714
- symbol: "sql"
3715
- }] : [];
3716
- }
3717
- };
3718
- }
3719
- /** The codecs and data types a set of composed components registers. */
3720
- function sqlTypeLookupsOf(frameworkComponents) {
3721
- return {
3722
- codecLookup: extractCodecLookup(frameworkComponents),
3723
- dataTypeLookup: assembleDataTypes(frameworkComponents).lookup
4425
+ const tables = input.target.tables();
4426
+ const storageRenames = new StorageRenames(input.statements, fromContract, input.contract, tables.sameName);
4427
+ const planned = plannedStorageRenames(storageRenames, tables);
4428
+ const conflict = storageRenameConflict(planned, tables, storageRenames);
4429
+ if (conflict !== void 0) return notOk(conflict);
4430
+ const planner = new StatementPlanner({
4431
+ ...input,
4432
+ fromContract,
4433
+ ownership: input.ownership,
4434
+ storageRenames
4435
+ });
4436
+ const unstated = (change) => change.renames.every((rename) => rename.statement === void 0);
4437
+ const plannedStatements = [];
4438
+ const planStatement = (statement) => {
4439
+ const operations = planner.plan(statement);
4440
+ if (operations.ok) plannedStatements.push({
4441
+ statement,
4442
+ operations: operations.value
4443
+ });
4444
+ return operations;
3724
4445
  };
4446
+ const steps = [
4447
+ ...input.statements.filter((statement) => statement.entity === "namespace").map((statement) => () => planStatement(statement)),
4448
+ ...planned.foundTables.map(({ change, name }) => () => planner.recordTableFound(change, name)),
4449
+ ...planned.tables.filter(unstated).map((change) => () => planner.planTableChange(change)),
4450
+ ...input.statements.filter((statement) => statement.entity !== "namespace").map((statement) => () => planStatement(statement)),
4451
+ ...planned.foundColumns.map(({ change, name }) => () => planner.recordColumnFound(change, name)),
4452
+ ...planned.columns.filter(unstated).map((change) => () => planner.planColumnChange(change))
4453
+ ];
4454
+ for (const step of steps) {
4455
+ const result = step();
4456
+ if (!result.ok) return result;
4457
+ }
4458
+ return ok({
4459
+ calls: planner.calls,
4460
+ tableRenames: planner.tableRenames,
4461
+ columnRenames: planner.columnRenames,
4462
+ alreadyRenamedTables: planned.foundTables.filter(({ change }) => !planned.tables.includes(change)).map(({ change, name }) => ({
4463
+ namespaceId: change.destination.namespaceId,
4464
+ table: name
4465
+ })),
4466
+ plannedStatements,
4467
+ origins: planner.origins(),
4468
+ storageRenames
4469
+ });
3725
4470
  }
3726
- /** The edit that keeps the data a removal loses: the removal, replaced by the replacements, in order. */
3727
- function keepDataEdit(removal, replacements, classes) {
4471
+ /**
4472
+ * The column of each field a convert or backfill statement names, as the destination contract
4473
+ * stores it. These statements rename nothing, so the strategies that plan a field's change read
4474
+ * them instead of the working schema. A field with no column has none to list.
4475
+ */
4476
+ function fieldStatementColumns(statements, contract) {
4477
+ const columnsOf = (kind) => statements.flatMap((statement) => {
4478
+ if (statement.kind !== kind || statement.entity !== "field") return [];
4479
+ const table = modelTable(contract, statement.field);
4480
+ const column = fieldColumn(contract, statement.field);
4481
+ return table === void 0 || column === void 0 ? [] : [{
4482
+ ...table,
4483
+ column,
4484
+ field: statement.field,
4485
+ text: fieldStatementText(contract, statement.field)
4486
+ }];
4487
+ });
3728
4488
  return {
3729
- remove: removal.renderTypeScript(),
3730
- replaceWith: replacements.map((replacement) => classes.replacementOf(removal, replacement).renderTypeScript()).join(", ")
4489
+ convert: columnsOf("convert"),
4490
+ backfill: columnsOf("backfill")
3731
4491
  };
3732
4492
  }
3733
4493
  /**
3734
- * The enum value each removal is about, with the edit that keeps its data when the member keeps
3735
- * its name and only its stored value changes.
4494
+ * A conflict for the first backfill statement that names a field the origin model does not have and
4495
+ * whose column has a default: the default fills the existing rows when the column is added, so the
4496
+ * statement has nothing to fill. A field already in the origin keeps its backfill, since a default
4497
+ * does not fill the rows that hold NULL when the column becomes required.
3736
4498
  */
3737
- function storedValueSubjects(calls, classes) {
3738
- const subjects = /* @__PURE__ */ new Map();
3739
- for (const [call, rewrite] of calls) {
3740
- if (!classes.isRemoval(call)) continue;
3741
- subjects.set(call, {
3742
- enumValue: rewrite.enumValue,
3743
- ...ifDefined("keepDataEdit", rewrite.keepData === void 0 ? void 0 : {
3744
- ...keepDataEdit(call, rewrite.keepData, classes),
3745
- ...rewrite.swapsValues ? { swapsValues: true } : {}
3746
- })
4499
+ function backfillOfDefaultedField(statements, fromContract, contract) {
4500
+ for (const statement of statements) {
4501
+ if (statement.kind !== "backfill" || statement.entity !== "field" || fromContract === null) continue;
4502
+ const originModel = sqlModelStorage(fromContract, statement.field);
4503
+ if (originModel === void 0 || Object.hasOwn(originModel.fields, statement.field.field)) continue;
4504
+ const table = modelTable(contract, statement.field);
4505
+ const column = fieldColumn(contract, statement.field);
4506
+ if (table === void 0 || column === void 0) continue;
4507
+ if ((contract.storage.namespaces[table.namespaceId]?.entries.table?.[table.table]?.columns[column])?.default === void 0) continue;
4508
+ return renameRefused(statement, `${describeMigrationStatement(statement, fromContract, contract)}: the field is new and has a default`, "The default fills the existing rows when the column is added, so there is nothing to backfill. Leave out the --backfill statement.", {
4509
+ namespaceId: table.namespaceId,
4510
+ table: table.table,
4511
+ column
3747
4512
  });
3748
4513
  }
3749
- return subjects;
4514
+ }
4515
+ /**
4516
+ * The operations of a statement the statement planner does not take: a value object field backfill
4517
+ * and a variant convert are planned with the diff; a field convert or backfill accounts for none.
4518
+ */
4519
+ function operationsOutsideStatementPlanner(statement) {
4520
+ if (statement.kind === "rename") return plannedAt([]);
4521
+ switch (statement.entity) {
4522
+ case "field": return plannedAt([]);
4523
+ case "valueObjectField":
4524
+ case "model": return PLANNED_WITH_DIFF;
4525
+ }
4526
+ }
4527
+ /**
4528
+ * Every statement of a plan in the order given, with the operations it accounts for: a planned
4529
+ * statement's from `planned`, and a statement planned with the diff's from
4530
+ * `operationIndexesPlannedWithDiff`, which finds them among the target's whole plan. A model rename
4531
+ * takes both, since renaming a variant whose discriminator value changed also rewrites the value.
4532
+ */
4533
+ function appliedStatementsInOrder(statements, planned, operationIndexesPlannedWithDiff) {
4534
+ return statements.map((statement) => {
4535
+ const operations = planned.find((entry) => entry.statement === statement)?.operations ?? operationsOutsideStatementPlanner(statement);
4536
+ if (operations.kind === "plannedWithDiff") return {
4537
+ statement,
4538
+ operationIndexes: operationIndexesPlannedWithDiff(statement)
4539
+ };
4540
+ return {
4541
+ statement,
4542
+ operationIndexes: statement.kind === "rename" && statement.entity === "model" ? [...operations.operationIndexes, ...operationIndexesPlannedWithDiff(statement)].sort((left, right) => left - right) : operations.operationIndexes
4543
+ };
4544
+ });
4545
+ }
4546
+ /** The enum value each removal is about. */
4547
+ function storedValueSubjects(calls, classes) {
4548
+ return new Map([...calls].filter(([call]) => classes.isRemoval(call)).map(([call, rewrite]) => [call, { enumValue: rewrite.enumValue }]));
3750
4549
  }
3751
4550
  /**
3752
4551
  * The edit that keeps the data a failed removal check found: `removal`, the call the check's mark
@@ -3754,10 +4553,13 @@ function storedValueSubjects(calls, classes) {
3754
4553
  * `"<stored value>"`.
3755
4554
  */
3756
4555
  function keepRowsEdit(removal, mark, classes) {
3757
- return keepDataEdit(removal, [{
3758
- from: mark.value,
3759
- to: "<stored value>"
3760
- }], classes);
4556
+ return {
4557
+ remove: removal.renderTypeScript(),
4558
+ replaceWith: classes.replacementOf(removal, {
4559
+ from: mark.value,
4560
+ to: "<stored value>"
4561
+ }).renderTypeScript()
4562
+ };
3761
4563
  }
3762
4564
  function operationCount(call) {
3763
4565
  return "companions" in call && Array.isArray(call.companions) ? 1 + call.companions.length : 1;
@@ -4338,6 +5140,6 @@ function columnCodecRef(codecId, column) {
4338
5140
  }
4339
5141
  var control_default = new SqlFamilyDescriptor();
4340
5142
  //#endregion
4341
- export { requiredColumnOf as $, isUnfilledSlot as A, planFieldEventCalls as B, encodeStoredValue as C, unnamedFieldFillOf as Ct, fieldStatementColumns as D, fieldRenameStorageEffect as E, otherSpaceDeclaring as F, planValueObjectFieldRewrites as G, planStatements as H, parseJsonPath as I, plannerSuccess as J, planVariantRowRewrites as K, partitionCallsByControlPolicy as L, keepRowsEdit as M, keyPathOf as N, fillKeyProblem as O, modelRenameStorageEffect as P, requiredColumnMeta as Q, partitionIssuesByControlPolicy as R, detectTableNameCaseChanges as S, unmatchedTableRename as St, fieldOfColumn as T, planStoredRewrites as U, planFieldEventOperations as V, planValueObjectFieldFills as W, readReportedDefault as X, readColumnDefault as Y, removalsOfMigration as Z, convertedColumnMeta as _, storedValueSubjects as _t, UnfilledValue as a, rowsHoldingValueOf as at, createSqlTextSources as b, unknownCallNames as bt, assembleAuthoringContributions$1 as c, runnerFailure as ct, checkSqlExpressionText as d, slotSource as dt, requiredColumnsOfMigration as et, columnTakesTemporaryValue as f, sqlDefaultFunctions as ft, control_default as g, storedValueOperationIndexes as gt, contractToSchemaIR as h, storageNameOfOperation as ht, TABLE_NAME_CASE_CHANGED_CODE as i, rowsHoldingValueMeta as it, jsonPathText as j, fillValueProblem as k, backfillOfDefaultedField as l, runnerSuccess as lt, contractNamespaceToSchemaIR as m, sqlTypeLookupsOf as mt, INIT_ADDITIVE_POLICY as n, resolveTableRenameAgainst as nt, acceptedByDataType as o, rowsWithoutValueFailure as ot, contractColumns as p, sqlOfSlot as pt, plannerFailure as q, NO_RENAMED_ORIGINS as r, rowsHoldingValueFailure as rt, appliedStatementsInOrder as s, rowsWithoutValueSummary as st, COLUMN_RENAME_UNMATCHED_CODE as t, resolveColumnRenameAgainst as tt, checkDatabasePoliciesHeld as u, scalarTypeNamesOf as ut, convertedColumnOf as v, subjectsOfCalls as vt, fieldEventStorage as w, detectDestructiveChanges as x, unmatchedColumnRename as xt, createMigrationPlan as y, unconvertedFieldOf as yt, planEnumValueRewrites as z };
5143
+ export { removalsOfMigration as $, fillKeyProblem as A, partitionIssuesByControlPolicy as B, detectTableNameCaseChanges as C, unmatchedColumnRename as Ct, fieldOfColumn as D, fieldEventStorage as E, keyPathOf as F, planStoredRewrites as G, planFieldEventCalls as H, modelRenameStorageEffect as I, planVariantRowRewrites as J, planValueObjectFieldFills as K, otherSpaceDeclaring as L, isUnfilledSlot as M, jsonPathText as N, fieldRenameStorageEffect as O, keepRowsEdit as P, readReportedDefault as Q, parseJsonPath as R, detectDestructiveChanges as S, unknownCallNames as St, exactName as T, unnamedFieldFillOf as Tt, planFieldEventOperations as U, planEnumValueRewrites as V, planStatements as W, plannerSuccess as X, plannerFailure as Y, readColumnDefault as Z, control_default as _, storageNameOfOperation as _t, TABLE_NAME_CASE_CHANGED_CODE as a, rowsHoldingValueFailure as at, createMigrationPlan as b, subjectsOfCalls as bt, appliedStatementsInOrder as c, rowsWithoutValueFailure as ct, checkDatabasePoliciesHeld as d, runnerSuccess as dt, requiredColumnMeta as et, checkSqlExpressionText as f, scalarTypeNamesOf as ft, contractToSchemaIR as g, sqlTypeLookupsOf as gt, contractNamespaceToSchemaIR as h, sqlOfSlot as ht, StorageRenames as i, resolveTableRenameAgainst as it, fillValueProblem as j, fieldStatementColumns as k, assembleAuthoringContributions$1 as l, rowsWithoutValueSummary as lt, contractColumns as m, sqlDefaultFunctions as mt, INIT_ADDITIVE_POLICY as n, requiredColumnsOfMigration as nt, UnfilledValue as o, rowsHoldingValueMeta as ot, columnTakesTemporaryValue as p, slotSource as pt, planValueObjectFieldRewrites as q, NO_RENAMED_ORIGINS as r, resolveColumnRenameAgainst as rt, acceptedByDataType as s, rowsHoldingValueOf as st, COLUMN_RENAME_UNMATCHED_CODE as t, requiredColumnOf as tt, backfillOfDefaultedField as u, runnerFailure as ut, convertedColumnMeta as v, storedValueOperationIndexes as vt, encodeStoredValue as w, unmatchedTableRename as wt, createSqlTextSources as x, unconvertedFieldOf as xt, convertedColumnOf as y, storedValueSubjects as yt, partitionCallsByControlPolicy as z };
4342
5144
 
4343
- //# sourceMappingURL=control-kHFMtE8A.mjs.map
5145
+ //# sourceMappingURL=control-Mh99W3HI.mjs.map