@prisma/orm-target-postgres 0.16.0-dev.36

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 (279) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +23 -0
  3. package/dist/adapter-CWvVo0PV.d.mts +22 -0
  4. package/dist/adapter-CWvVo0PV.d.mts.map +1 -0
  5. package/dist/adapter-DhqcO3YO-jzwDVcCv.mjs +70 -0
  6. package/dist/adapter-DhqcO3YO-jzwDVcCv.mjs.map +1 -0
  7. package/dist/adapter.d.mts +12 -0
  8. package/dist/adapter.mjs +7 -0
  9. package/dist/adapter__adapter.d.mts +2 -0
  10. package/dist/adapter__adapter.mjs +2 -0
  11. package/dist/adapter__column-types.d.mts +2 -0
  12. package/dist/adapter__column-types.mjs +2 -0
  13. package/dist/adapter__control.d.mts +5 -0
  14. package/dist/adapter__control.mjs +441 -0
  15. package/dist/adapter__control.mjs.map +1 -0
  16. package/dist/adapter__operation-types.d.mts +2 -0
  17. package/dist/adapter__operation-types.mjs +1 -0
  18. package/dist/adapter__runtime.d.mts +2 -0
  19. package/dist/adapter__runtime.mjs +38 -0
  20. package/dist/adapter__runtime.mjs.map +1 -0
  21. package/dist/adapter__types.d.mts +4 -0
  22. package/dist/adapter__types.mjs +1 -0
  23. package/dist/authoring-03FwIL2k-kPjZAp3s.mjs +757 -0
  24. package/dist/authoring-03FwIL2k-kPjZAp3s.mjs.map +1 -0
  25. package/dist/canonicalize-CQlxSR4D-MnrT5gtW.d.mts +34 -0
  26. package/dist/canonicalize-CQlxSR4D-MnrT5gtW.d.mts.map +1 -0
  27. package/dist/canonicalize-CrN3u_xM-D4MrOqcB.mjs +59 -0
  28. package/dist/canonicalize-CrN3u_xM-D4MrOqcB.mjs.map +1 -0
  29. package/dist/codec-descriptor-Bec_zukr-BfvtUqhm.d.mts +37 -0
  30. package/dist/codec-descriptor-Bec_zukr-BfvtUqhm.d.mts.map +1 -0
  31. package/dist/codec-descriptor-Bg-_412t.d.mts +1 -0
  32. package/dist/codec-descriptor-CB6x0xEu-C-Zn2IEz.mjs +135 -0
  33. package/dist/codec-descriptor-CB6x0xEu-C-Zn2IEz.mjs.map +1 -0
  34. package/dist/codec-ids-CsOU3xDv-mPI0INiF.d.mts +33 -0
  35. package/dist/codec-ids-CsOU3xDv-mPI0INiF.d.mts.map +1 -0
  36. package/dist/codec-ids-fgafMLR7.d.mts +1 -0
  37. package/dist/codec-ids-tX7Svtz--BuOfRaVU.mjs +33 -0
  38. package/dist/codec-ids-tX7Svtz--BuOfRaVU.mjs.map +1 -0
  39. package/dist/codec-types-BHwY9Ff-.d.mts +2 -0
  40. package/dist/codec-types-mWhnDEAf-CAQzGFnF.d.mts +82 -0
  41. package/dist/codec-types-mWhnDEAf-CAQzGFnF.d.mts.map +1 -0
  42. package/dist/codecs-CBl0nD44-CaWPc1bd.mjs +1486 -0
  43. package/dist/codecs-CBl0nD44-CaWPc1bd.mjs.map +1 -0
  44. package/dist/codecs-CHIVTNZs.mjs +15 -0
  45. package/dist/codecs-CHIVTNZs.mjs.map +1 -0
  46. package/dist/codecs-Cvqvb9pV-Cdc51FKY.d.mts +589 -0
  47. package/dist/codecs-Cvqvb9pV-Cdc51FKY.d.mts.map +1 -0
  48. package/dist/codecs-DBn-uIv-.d.mts +15 -0
  49. package/dist/codecs-DBn-uIv-.d.mts.map +1 -0
  50. package/dist/column-types-BH-MU6uU.d.mts +108 -0
  51. package/dist/column-types-BH-MU6uU.d.mts.map +1 -0
  52. package/dist/column-types-CwAyCgp2.mjs +126 -0
  53. package/dist/column-types-CwAyCgp2.mjs.map +1 -0
  54. package/dist/contract-free-BZUS18FU.mjs +118 -0
  55. package/dist/contract-free-BZUS18FU.mjs.map +1 -0
  56. package/dist/contract-free-DzpGxLfb.d.mts +258 -0
  57. package/dist/contract-free-DzpGxLfb.d.mts.map +1 -0
  58. package/dist/control-2F195jJk.d.mts +11 -0
  59. package/dist/control-2F195jJk.d.mts.map +1 -0
  60. package/dist/control-6WFTtLAM.mjs +60 -0
  61. package/dist/control-6WFTtLAM.mjs.map +1 -0
  62. package/dist/control-B-FTbEnE.d.mts +22 -0
  63. package/dist/control-B-FTbEnE.d.mts.map +1 -0
  64. package/dist/control-D85zv_aY.d.mts +199 -0
  65. package/dist/control-D85zv_aY.d.mts.map +1 -0
  66. package/dist/control-DRMWptiJ.mjs +1355 -0
  67. package/dist/control-DRMWptiJ.mjs.map +1 -0
  68. package/dist/control-adapter-B9t0g7Pf-HrCxlM65.mjs +1901 -0
  69. package/dist/control-adapter-B9t0g7Pf-HrCxlM65.mjs.map +1 -0
  70. package/dist/control-policy-Cl3RRSPg-CT3QGpR3.mjs +1257 -0
  71. package/dist/control-policy-Cl3RRSPg-CT3QGpR3.mjs.map +1 -0
  72. package/dist/data-transform-BSM7TQpE.d.mts +1 -0
  73. package/dist/data-transform-ChZzy2dP-CxVCat_8.mjs +53 -0
  74. package/dist/data-transform-ChZzy2dP-CxVCat_8.mjs.map +1 -0
  75. package/dist/data-transform-Ck5FbyNO-BNE7QlAo.d.mts +38 -0
  76. package/dist/data-transform-Ck5FbyNO-BNE7QlAo.d.mts.map +1 -0
  77. package/dist/ddl-B4Rh8ntj.d.mts +1 -0
  78. package/dist/ddl-BdP4q3KY-Duef4uHw.mjs +395 -0
  79. package/dist/ddl-BdP4q3KY-Duef4uHw.mjs.map +1 -0
  80. package/dist/default-normalizer-B36TOul4.d.mts +31 -0
  81. package/dist/default-normalizer-B36TOul4.d.mts.map +1 -0
  82. package/dist/default-normalizer-Ba5ZebHM-isV86rjy.mjs +253 -0
  83. package/dist/default-normalizer-Ba5ZebHM-isV86rjy.mjs.map +1 -0
  84. package/dist/descriptor-meta-2IlVC6_d-DnV00Qd_.mjs +351 -0
  85. package/dist/descriptor-meta-2IlVC6_d-DnV00Qd_.mjs.map +1 -0
  86. package/dist/descriptor-meta-DnHabAS3-C53XXPQw.mjs +28 -0
  87. package/dist/descriptor-meta-DnHabAS3-C53XXPQw.mjs.map +1 -0
  88. package/dist/descriptor-meta-runtime-UwYdV8fD-B_m_Ha8r.mjs +13 -0
  89. package/dist/descriptor-meta-runtime-UwYdV8fD-B_m_Ha8r.mjs.map +1 -0
  90. package/dist/diff-database-schema-BfRs2vrG-D2o4KII0.mjs +390 -0
  91. package/dist/diff-database-schema-BfRs2vrG-D2o4KII0.mjs.map +1 -0
  92. package/dist/diff-database-schema-DsoNznGC.d.mts +38 -0
  93. package/dist/diff-database-schema-DsoNznGC.d.mts.map +1 -0
  94. package/dist/driver.d.mts +3 -0
  95. package/dist/driver.mjs +2 -0
  96. package/dist/driver__control.d.mts +2 -0
  97. package/dist/driver__control.mjs +2 -0
  98. package/dist/driver__runtime.d.mts +2 -0
  99. package/dist/driver__runtime.mjs +597 -0
  100. package/dist/driver__runtime.mjs.map +1 -0
  101. package/dist/errors-DCcVX4j1.d.mts +32 -0
  102. package/dist/errors-DCcVX4j1.d.mts.map +1 -0
  103. package/dist/errors-kYxOQjdD-D4T3rbVp.mjs +39 -0
  104. package/dist/errors-kYxOQjdD-D4T3rbVp.mjs.map +1 -0
  105. package/dist/issue-planner-jkY6p-Ca.d.mts +105 -0
  106. package/dist/issue-planner-jkY6p-Ca.d.mts.map +1 -0
  107. package/dist/migration-CBSAPE8S.d.mts +25 -0
  108. package/dist/migration-CBSAPE8S.d.mts.map +1 -0
  109. package/dist/migration-PTHAY9Cv.mjs +21 -0
  110. package/dist/migration-PTHAY9Cv.mjs.map +1 -0
  111. package/dist/namespace-ids-xtp_ZY86-Cpp8PTxD.mjs +7 -0
  112. package/dist/namespace-ids-xtp_ZY86-Cpp8PTxD.mjs.map +1 -0
  113. package/dist/native-type-normalizer-DqJlOTeX.d.mts +19 -0
  114. package/dist/native-type-normalizer-DqJlOTeX.d.mts.map +1 -0
  115. package/dist/native-type-normalizer-yvd3tqv-.mjs +38 -0
  116. package/dist/native-type-normalizer-yvd3tqv-.mjs.map +1 -0
  117. package/dist/nodes-BU-V-aZA-RqwPH68u.d.mts +235 -0
  118. package/dist/nodes-BU-V-aZA-RqwPH68u.d.mts.map +1 -0
  119. package/dist/nodes-DAvDJLvJ-BBdvFXNa.mjs +255 -0
  120. package/dist/nodes-DAvDJLvJ-BBdvFXNa.mjs.map +1 -0
  121. package/dist/normalize-error-CNjgVO71-CLlZ3CuJ.mjs +121 -0
  122. package/dist/normalize-error-CNjgVO71-CLlZ3CuJ.mjs.map +1 -0
  123. package/dist/op-factory-call-DifL68KT-Bo6pxs-R.mjs +2009 -0
  124. package/dist/op-factory-call-DifL68KT-Bo6pxs-R.mjs.map +1 -0
  125. package/dist/op-factory-call-FEA5mnWH.d.mts +1 -0
  126. package/dist/op-factory-call-jd4cgfjA-CyNT4YVn.d.mts +521 -0
  127. package/dist/op-factory-call-jd4cgfjA-CyNT4YVn.d.mts.map +1 -0
  128. package/dist/operation-types-BfRocNI8.d.mts +22 -0
  129. package/dist/operation-types-BfRocNI8.d.mts.map +1 -0
  130. package/dist/pack-DFM4tmob.d.mts +610 -0
  131. package/dist/pack-DFM4tmob.d.mts.map +1 -0
  132. package/dist/planner-Bmje9ii8-B99fEsNM.mjs +588 -0
  133. package/dist/planner-Bmje9ii8-B99fEsNM.mjs.map +1 -0
  134. package/dist/planner-DL4Bh5Nk.d.mts +163 -0
  135. package/dist/planner-DL4Bh5Nk.d.mts.map +1 -0
  136. package/dist/planner-ddl-builders-CbfICQfm-CxYiLrhX.mjs +102 -0
  137. package/dist/planner-ddl-builders-CbfICQfm-CxYiLrhX.mjs.map +1 -0
  138. package/dist/planner-ddl-builders-ijp60-JO.d.mts +19 -0
  139. package/dist/planner-ddl-builders-ijp60-JO.d.mts.map +1 -0
  140. package/dist/planner-identity-values-BmHn5C6U-BYBbUAyR.mjs +90 -0
  141. package/dist/planner-identity-values-BmHn5C6U-BYBbUAyR.mjs.map +1 -0
  142. package/dist/planner-identity-values-TfEhnoWa.d.mts +25 -0
  143. package/dist/planner-identity-values-TfEhnoWa.d.mts.map +1 -0
  144. package/dist/planner-produced-postgres-migration-B0PQLLUb-qsS6cQqX.d.mts +25 -0
  145. package/dist/planner-produced-postgres-migration-B0PQLLUb-qsS6cQqX.d.mts.map +1 -0
  146. package/dist/planner-produced-postgres-migration-C3GPZWeC.d.mts +1 -0
  147. package/dist/planner-produced-postgres-migration-Cicg2sXg-Ck9iDxGI.mjs +47 -0
  148. package/dist/planner-produced-postgres-migration-Cicg2sXg-Ck9iDxGI.mjs.map +1 -0
  149. package/dist/planner-schema-lookup-C4DHAddq.d.mts +21 -0
  150. package/dist/planner-schema-lookup-C4DHAddq.d.mts.map +1 -0
  151. package/dist/planner-schema-lookup-kMIVP2y--CdO4VlnF.mjs +57 -0
  152. package/dist/planner-schema-lookup-kMIVP2y--CdO4VlnF.mjs.map +1 -0
  153. package/dist/planner-sql-checks-CFgbRTJw.d.mts +20 -0
  154. package/dist/planner-sql-checks-CFgbRTJw.d.mts.map +1 -0
  155. package/dist/planner-sql-checks-DRc_78n8-C9nHOrvU.mjs +152 -0
  156. package/dist/planner-sql-checks-DRc_78n8-C9nHOrvU.mjs.map +1 -0
  157. package/dist/planner-target-details-HkP4RrRO-_xPQVPF0.d.mts +12 -0
  158. package/dist/planner-target-details-HkP4RrRO-_xPQVPF0.d.mts.map +1 -0
  159. package/dist/planner-type-resolution-Bt2f_q-F-C4T6YTae.mjs +15 -0
  160. package/dist/planner-type-resolution-Bt2f_q-F-C4T6YTae.mjs.map +1 -0
  161. package/dist/postgres-contract-view-2OP5JnXl-D2fpy4-8.d.mts +36 -0
  162. package/dist/postgres-contract-view-2OP5JnXl-D2fpy4-8.d.mts.map +1 -0
  163. package/dist/postgres-contract-view-FdLX7dV9-Cat1VKV9.mjs +144 -0
  164. package/dist/postgres-contract-view-FdLX7dV9-Cat1VKV9.mjs.map +1 -0
  165. package/dist/postgres-database-schema-node-CyfpHXDr-BqyozkQE.d.mts +285 -0
  166. package/dist/postgres-database-schema-node-CyfpHXDr-BqyozkQE.d.mts.map +1 -0
  167. package/dist/postgres-migration-CDJj7CvD-Bsqs_fVo.d.mts +260 -0
  168. package/dist/postgres-migration-CDJj7CvD-Bsqs_fVo.d.mts.map +1 -0
  169. package/dist/postgres-migration-CJshdIZn-DYYjgdD0.mjs +201 -0
  170. package/dist/postgres-migration-CJshdIZn-DYYjgdD0.mjs.map +1 -0
  171. package/dist/postgres-native-enum-CdP3b_-R-Cgz9KEKx.mjs +45 -0
  172. package/dist/postgres-native-enum-CdP3b_-R-Cgz9KEKx.mjs.map +1 -0
  173. package/dist/postgres-rls-policy-CnDxf3z9-C3LIHAIG.d.mts +61 -0
  174. package/dist/postgres-rls-policy-CnDxf3z9-C3LIHAIG.d.mts.map +1 -0
  175. package/dist/postgres-role-schema-node-B8Z5i5D--PObwlU2Z.mjs +204 -0
  176. package/dist/postgres-role-schema-node-B8Z5i5D--PObwlU2Z.mjs.map +1 -0
  177. package/dist/postgres-schema-KSzLDONj-CsXGoY8b.mjs +421 -0
  178. package/dist/postgres-schema-KSzLDONj-CsXGoY8b.mjs.map +1 -0
  179. package/dist/postgres-schema-Xsjt3RKO-Buv2X8ai.d.mts +269 -0
  180. package/dist/postgres-schema-Xsjt3RKO-Buv2X8ai.d.mts.map +1 -0
  181. package/dist/postgres-table-schema-node-BBkitBQh-DT1T5VWU.mjs +212 -0
  182. package/dist/postgres-table-schema-node-BBkitBQh-DT1T5VWU.mjs.map +1 -0
  183. package/dist/render-ops-DPwhZt2W.d.mts +11 -0
  184. package/dist/render-ops-DPwhZt2W.d.mts.map +1 -0
  185. package/dist/render-ops-DxzTxSsv-Bz85uUHk.mjs +34 -0
  186. package/dist/render-ops-DxzTxSsv-Bz85uUHk.mjs.map +1 -0
  187. package/dist/render-typescript-6sCFvMBh.d.mts +21 -0
  188. package/dist/render-typescript-6sCFvMBh.d.mts.map +1 -0
  189. package/dist/render-typescript-Cw3lFO28-Cx0lXWmv.mjs +117 -0
  190. package/dist/render-typescript-Cw3lFO28-Cx0lXWmv.mjs.map +1 -0
  191. package/dist/resolve-ddl-schema-CxqlLW47-0GiHRziS.mjs +22 -0
  192. package/dist/resolve-ddl-schema-CxqlLW47-0GiHRziS.mjs.map +1 -0
  193. package/dist/runtime-BbSRVwdd.d.mts +12 -0
  194. package/dist/runtime-BbSRVwdd.d.mts.map +1 -0
  195. package/dist/runtime-CDewySU9.d.mts +55 -0
  196. package/dist/runtime-CDewySU9.d.mts.map +1 -0
  197. package/dist/runtime-_TfO66h5.d.mts +32 -0
  198. package/dist/runtime-_TfO66h5.d.mts.map +1 -0
  199. package/dist/schema-ir-annotations-DuuYh0gl.d.mts +15 -0
  200. package/dist/schema-ir-annotations-DuuYh0gl.d.mts.map +1 -0
  201. package/dist/schema-node-kinds-qlnURWJy-Bo30pwTM.d.mts +30 -0
  202. package/dist/schema-node-kinds-qlnURWJy-Bo30pwTM.d.mts.map +1 -0
  203. package/dist/sql-utils-BnBlQxyh-DaX9Nb7Z.mjs +90 -0
  204. package/dist/sql-utils-BnBlQxyh-DaX9Nb7Z.mjs.map +1 -0
  205. package/dist/sql-utils-DW6fkczF.d.mts +62 -0
  206. package/dist/sql-utils-DW6fkczF.d.mts.map +1 -0
  207. package/dist/table-source-ikHOZmhD-DriY1Lcr.d.mts +15 -0
  208. package/dist/table-source-ikHOZmhD-DriY1Lcr.d.mts.map +1 -0
  209. package/dist/target.d.mts +47 -0
  210. package/dist/target.mjs +34 -0
  211. package/dist/target__codec-descriptor.d.mts +3 -0
  212. package/dist/target__codec-descriptor.mjs +2 -0
  213. package/dist/target__codec-ids.d.mts +3 -0
  214. package/dist/target__codec-ids.mjs +2 -0
  215. package/dist/target__codec-types.d.mts +4 -0
  216. package/dist/target__codec-types.mjs +1 -0
  217. package/dist/target__codecs.d.mts +3 -0
  218. package/dist/target__codecs.mjs +3 -0
  219. package/dist/target__contract-free.d.mts +3 -0
  220. package/dist/target__contract-free.mjs +4 -0
  221. package/dist/target__control.d.mts +2 -0
  222. package/dist/target__control.mjs +2 -0
  223. package/dist/target__data-transform.d.mts +3 -0
  224. package/dist/target__data-transform.mjs +2 -0
  225. package/dist/target__ddl.d.mts +4 -0
  226. package/dist/target__ddl.mjs +2 -0
  227. package/dist/target__default-normalizer.d.mts +2 -0
  228. package/dist/target__default-normalizer.mjs +2 -0
  229. package/dist/target__diff-database-schema.d.mts +2 -0
  230. package/dist/target__diff-database-schema.mjs +2 -0
  231. package/dist/target__errors.d.mts +2 -0
  232. package/dist/target__errors.mjs +2 -0
  233. package/dist/target__issue-planner.d.mts +2 -0
  234. package/dist/target__issue-planner.mjs +2 -0
  235. package/dist/target__migration.d.mts +4 -0
  236. package/dist/target__migration.mjs +5 -0
  237. package/dist/target__native-type-normalizer.d.mts +2 -0
  238. package/dist/target__native-type-normalizer.mjs +2 -0
  239. package/dist/target__op-factory-call.d.mts +3 -0
  240. package/dist/target__op-factory-call.mjs +2 -0
  241. package/dist/target__pack.d.mts +2 -0
  242. package/dist/target__pack.mjs +2 -0
  243. package/dist/target__planner-ddl-builders.d.mts +2 -0
  244. package/dist/target__planner-ddl-builders.mjs +2 -0
  245. package/dist/target__planner-identity-values.d.mts +2 -0
  246. package/dist/target__planner-identity-values.mjs +2 -0
  247. package/dist/target__planner-produced-postgres-migration.d.mts +3 -0
  248. package/dist/target__planner-produced-postgres-migration.mjs +2 -0
  249. package/dist/target__planner-schema-lookup.d.mts +2 -0
  250. package/dist/target__planner-schema-lookup.mjs +2 -0
  251. package/dist/target__planner-sql-checks.d.mts +2 -0
  252. package/dist/target__planner-sql-checks.mjs +2 -0
  253. package/dist/target__planner-target-details.d.mts +2 -0
  254. package/dist/target__planner-target-details.mjs +1 -0
  255. package/dist/target__planner.d.mts +2 -0
  256. package/dist/target__planner.mjs +3 -0
  257. package/dist/target__render-ops.d.mts +2 -0
  258. package/dist/target__render-ops.mjs +2 -0
  259. package/dist/target__render-typescript.d.mts +2 -0
  260. package/dist/target__render-typescript.mjs +2 -0
  261. package/dist/target__rls-canonicalize.d.mts +2 -0
  262. package/dist/target__rls-canonicalize.mjs +2 -0
  263. package/dist/target__runtime.d.mts +3 -0
  264. package/dist/target__runtime.mjs +23 -0
  265. package/dist/target__runtime.mjs.map +1 -0
  266. package/dist/target__schema-ir-annotations.d.mts +2 -0
  267. package/dist/target__schema-ir-annotations.mjs +2 -0
  268. package/dist/target__sql-utils.d.mts +2 -0
  269. package/dist/target__sql-utils.mjs +2 -0
  270. package/dist/target__types.d.mts +7 -0
  271. package/dist/target__types.mjs +5 -0
  272. package/dist/types-CkryN1AS-6MNZLjLY.d.mts +27 -0
  273. package/dist/types-CkryN1AS-6MNZLjLY.d.mts.map +1 -0
  274. package/dist/types-Cp_Jf2tk.d.mts +1 -0
  275. package/dist/types-ue6jkJyF-BQJzjx1P.d.mts +10 -0
  276. package/dist/types-ue6jkJyF-BQJzjx1P.d.mts.map +1 -0
  277. package/dist/types-xa86TkcV.d.mts +32 -0
  278. package/dist/types-xa86TkcV.d.mts.map +1 -0
  279. package/package.json +95 -0
@@ -0,0 +1,1257 @@
1
+ import { r as quoteIdentifier } from "./sql-utils-BnBlQxyh-DaX9Nb7Z.mjs";
2
+ import { d as isPostgresSchema } from "./postgres-schema-KSzLDONj-CsXGoY8b.mjs";
3
+ import { n as PostgresSchemaNodeKind, o as postgresNodeEntityKind, r as PostgresTableSchemaNode, t as PostgresNativeEnumSchemaNode } from "./postgres-table-schema-node-BBkitBQh-DT1T5VWU.mjs";
4
+ import { t as buildExpectedFormatType } from "./planner-sql-checks-DRc_78n8-C9nHOrvU.mjs";
5
+ import { n as buildColumnTypeSql, t as buildColumnDefaultSql } from "./planner-ddl-builders-CbfICQfm-CxYiLrhX.mjs";
6
+ import { C as DropNativeEnumTypeCall, D as EnableRowLevelSecurityCall, E as DropTableCall, I as postgresDefaultToDdlColumnDefault, M as SetNotNullCall, N as buildTargetDetails, O as RawSqlCall, S as DropIndexCall, _ as DisableRowLevelSecurityCall, a as AddNotNullColumnDirectCall, b as DropConstraintCall, c as AddUniqueCall, d as CreateIndexCall, f as CreateNativeEnumTypeCall, g as DataTransformCall, h as CreateTableCall, i as AddNativeEnumValueCall, j as SetDefaultCall, l as AlterColumnTypeCall, m as CreateSchemaCall, n as AddColumnCall, o as AddNotNullColumnWithTempDefaultCall, r as AddForeignKeyCall, s as AddPrimaryKeyCall, t as AddCheckConstraintCall, v as DropCheckConstraintCall, w as DropNotNullCall, x as DropDefaultCall, y as DropColumnCall } from "./op-factory-call-DifL68KT-Bo6pxs-R.mjs";
7
+ import { n as resolveIdentityValue } from "./planner-identity-values-BmHn5C6U-BYBbUAyR.mjs";
8
+ import { i as hasUniqueConstraint, n as hasForeignKey, t as buildSchemaLookupMap } from "./planner-schema-lookup-kMIVP2y--CdO4VlnF.mjs";
9
+ import { blindCast } from "@prisma/orm-framework/utils/casts";
10
+ import { UNBOUND_NAMESPACE_ID, entityAt } from "@prisma/orm-framework/components/ir";
11
+ import { StorageTable } from "@prisma/orm-family-sql/contract/types";
12
+ import { ifDefined } from "@prisma/orm-framework/utils/defined";
13
+ import * as contractFree from "@prisma/orm-family-sql/relational-core/contract-free";
14
+ import { issueOutcome, orderIssuesByDependencies } from "@prisma/orm-framework/components/control";
15
+ import { resolveValueSetValues } from "@prisma/orm-family-sql/family/control";
16
+ import { RelationalSchemaNodeKind, SqlSchemaIR } from "@prisma/orm-family-sql/schema-ir/types";
17
+ import { InternalError } from "@prisma/orm-framework/utils/internal-error";
18
+ import { notOk, ok } from "@prisma/orm-framework/utils/result";
19
+ //#region ../../../3-targets/3-targets/postgres/dist/control-policy-Cl3RRSPg.mjs
20
+ /**
21
+ * The storage-`entries` coordinate `(entityKind, entityName)` a Postgres diff
22
+ * node addresses — a table by its name, a native enum by its physical type
23
+ * name. `undefined` for a node that is not a whole storage entity (a namespace,
24
+ * a column, a policy). Lets ownership/subject resolution treat every entity kind
25
+ * uniformly, the node self-describing its storage identity.
26
+ */
27
+ function postgresNodeStorageCoordinate(node) {
28
+ if (PostgresTableSchemaNode.is(node)) {
29
+ const entityKind = postgresNodeEntityKind(node.nodeKind);
30
+ return entityKind === void 0 ? void 0 : {
31
+ entityKind,
32
+ entityName: node.name
33
+ };
34
+ }
35
+ if (PostgresNativeEnumSchemaNode.is(node)) {
36
+ const entityKind = postgresNodeEntityKind(node.nodeKind);
37
+ return entityKind === void 0 ? void 0 : {
38
+ entityKind,
39
+ entityName: node.typeName
40
+ };
41
+ }
42
+ }
43
+ /**
44
+ * Reconstructs the `StorageColumn`-shaped fields the DDL builder functions
45
+ * (`buildColumnTypeSql`, `buildExpectedFormatType`, `resolveIdentityValue`)
46
+ * expect, from a column node's own stamped codec identity (`codecRef` /
47
+ * `codecBaseNativeType` / `codecNamedType`, Decision 5) — never the
48
+ * contract. The builders were written against `StorageColumn` and are
49
+ * unchanged here; only the shape feeding them moves from the contract to
50
+ * the node. An empty `storageTypes` catalog is passed alongside: the
51
+ * node's fields are already resolved past any `typeRef` indirection, so no
52
+ * live lookup is needed, and passing a non-empty catalog would risk a
53
+ * false `typeRef` hit against an unrelated storage type.
54
+ */
55
+ function columnLike(column) {
56
+ if (column.codecRef === void 0 || column.codecBaseNativeType === void 0) throw new InternalError(`columnLike: expected column "${column.name}" carries no codec identity — the expected tree must be derived via contractToSchemaIR for planning`);
57
+ return {
58
+ nativeType: column.codecBaseNativeType,
59
+ codecId: column.codecRef.codecId,
60
+ nullable: column.nullable,
61
+ ...ifDefined("many", column.many ?? column.codecRef.many),
62
+ ...ifDefined("typeParams", column.codecRef.typeParams !== void 0 ? blindCast(column.codecRef.typeParams) : void 0),
63
+ ...column.codecNamedType ? { typeRef: "<resolved>" } : {},
64
+ ...ifDefined("default", column.resolvedDefault)
65
+ };
66
+ }
67
+ /**
68
+ * Builds the `CREATE TABLE` / `ADD COLUMN` DDL column for an expected column
69
+ * node, resolving type rendering from the node's codec identity against the
70
+ * codec hooks the caller holds — the same builder the pre-`plan(start, end)`
71
+ * op-path called, so the output is byte-identical.
72
+ */
73
+ function renderColumnDdl(name, column, codecHooks) {
74
+ const like = columnLike(column);
75
+ const typeSql = buildColumnTypeSql(like, codecHooks, {});
76
+ const ddlDefault = postgresDefaultToDdlColumnDefault(like.default);
77
+ return contractFree.col(name, typeSql, {
78
+ ...!column.nullable ? { notNull: true } : {},
79
+ ...ifDefined("default", ddlDefault),
80
+ ...ifDefined("codecRef", column.codecRef)
81
+ });
82
+ }
83
+ /**
84
+ * Builds the `ALTER COLUMN … TYPE` operands for an expected column node.
85
+ */
86
+ function renderColumnAlterType(column, codecHooks) {
87
+ const like = columnLike(column);
88
+ return {
89
+ qualifiedTargetType: buildColumnTypeSql(like, codecHooks, {}, false),
90
+ formatTypeExpected: buildExpectedFormatType(like, codecHooks, {})
91
+ };
92
+ }
93
+ /**
94
+ * Resolves the identity value (monoid neutral element) SQL literal used as
95
+ * the temporary default when adding a NOT-NULL column with no contract
96
+ * default (`notNullAddColumnCallStrategy`'s shared-temp-default backfill).
97
+ * `null` when the column's type has no built-in/codec-provided identity
98
+ * value.
99
+ */
100
+ function resolveColumnTemporaryDefault(column, codecHooks) {
101
+ return resolveIdentityValue(columnLike(column), codecHooks, {});
102
+ }
103
+ /**
104
+ * The column's `SET DEFAULT` clause SQL, resolved from a column-default
105
+ * diff node. `''` when the node carries no resolved default.
106
+ */
107
+ function renderColumnDefaultSql(defaultNode) {
108
+ if (defaultNode.resolved === void 0) return "";
109
+ return buildColumnDefaultSql(defaultNode.resolved, {
110
+ nativeType: defaultNode.nativeTypeContext ?? "",
111
+ ...ifDefined("many", defaultNode.many)
112
+ });
113
+ }
114
+ /**
115
+ * Look up a storage table by its explicit namespace coordinate. Returns
116
+ * `undefined` when the namespace has no table by that name (or no such
117
+ * namespace exists). Callers that get `undefined` MUST treat it as an
118
+ * explicit conflict — never silently fall back to a global default
119
+ * schema or a name-only walk, because that footgun would resolve a
120
+ * stale or duplicate table name to whichever namespace the iteration
121
+ * order surfaced first (a real data-loss hazard in multi-namespace
122
+ * contracts where two namespaces can carry the same table name).
123
+ */
124
+ function tableAt(storage, namespaceId, tableName) {
125
+ const ns = storage.namespaces[namespaceId];
126
+ if (ns === void 0) return void 0;
127
+ return ns.entries.table?.[tableName];
128
+ }
129
+ /**
130
+ * Resolve the DDL schema name for a namespace coordinate. Postgres-aware
131
+ * namespaces dispatch to their polymorphic `ddlSchemaName` override —
132
+ * named schemas return their own id; the unbound singleton returns
133
+ * `UNBOUND_NAMESPACE_ID`. Legacy single-namespace contracts whose
134
+ * `__unbound__` slot is the framework-default `SqlUnboundNamespace`
135
+ * (rather than the Postgres-aware `PostgresUnboundSchema`) flow the
136
+ * coordinate through unchanged so downstream `qualifyTableName`
137
+ * resolves polymorphically.
138
+ */
139
+ function resolveDdlSchemaForNamespace(ctx, namespaceId) {
140
+ const namespace = ctx.toContract.storage.namespaces[namespaceId];
141
+ if (isPostgresSchema(namespace)) return namespace.ddlSchemaName(ctx.toContract.storage);
142
+ return namespaceId;
143
+ }
144
+ /**
145
+ * Recovers the contract namespace id for a DDL schema name embedded in a
146
+ * diff-issue path (`path[1]`). The strategies need the CONTRACT column/table
147
+ * (for codec-hook reads and eligibility probes the retained subsystems still
148
+ * run) even though the issue itself only carries the resolved DDL schema —
149
+ * this is the reverse of `resolveDdlSchemaForNamespace`.
150
+ */
151
+ function namespaceIdForDdlSchema(ctx, ddlSchemaName) {
152
+ return resolveNamespaceIdForDdlSchema(ctx.toContract, ddlSchemaName);
153
+ }
154
+ /** A `not-equal` column issue whose node pair is narrowed to `SqlColumnIR`. */
155
+ function columnNodePair(issue) {
156
+ const node = issueNode(issue);
157
+ if (node === void 0 || node.nodeKind !== RelationalSchemaNodeKind.column) return void 0;
158
+ if (issue.expected === void 0 || issue.actual === void 0) return void 0;
159
+ return {
160
+ expected: blindCast(issue.expected),
161
+ actual: blindCast(issue.actual)
162
+ };
163
+ }
164
+ const notNullBackfillCallStrategy = (issues, ctx) => {
165
+ if (!ctx.policy.allowedOperationClasses.includes("data")) return { kind: "no_match" };
166
+ const matched = [];
167
+ const calls = [];
168
+ for (const issue of issues) {
169
+ if (issueOutcome(issue) !== "not-found") continue;
170
+ const node = issueNode(issue);
171
+ if (node === void 0 || node.nodeKind !== RelationalSchemaNodeKind.column) continue;
172
+ const expected = blindCast(issue.expected);
173
+ if (expected.nullable !== false || expected.resolvedDefault !== void 0) continue;
174
+ const ddlSchemaName = issueSchemaName(issue);
175
+ const tableName = issueTableName(issue);
176
+ if (ddlSchemaName === void 0 || tableName === void 0) continue;
177
+ const schemaName = emissionSchemaName(ctx, ddlSchemaName);
178
+ matched.push(issue);
179
+ const ddl = renderColumnDdl(expected.name, expected, ctx.codecHooks);
180
+ const nullableSpec = contractFree.col(ddl.name, ddl.type, { ...ddl.codecRef !== void 0 ? { codecRef: ddl.codecRef } : {} });
181
+ calls.push(new AddColumnCall(schemaName, tableName, nullableSpec), new DataTransformCall(`backfill-${tableName}-${expected.name}`, `backfill-${tableName}-${expected.name}:check`, `backfill-${tableName}-${expected.name}:run`), new SetNotNullCall(schemaName, tableName, expected.name));
182
+ }
183
+ if (matched.length === 0) return { kind: "no_match" };
184
+ return {
185
+ kind: "match",
186
+ issues: issues.filter((i) => !matched.includes(i)),
187
+ calls,
188
+ recipe: true
189
+ };
190
+ };
191
+ const SAFE_WIDENINGS = /* @__PURE__ */ new Set([
192
+ "int2→int4",
193
+ "int2→int8",
194
+ "int4→int8",
195
+ "float4→float8"
196
+ ]);
197
+ /**
198
+ * Handles `not-equal` column issues whose TYPE differs. `fromContract` is
199
+ * only supplied by `migration plan` — for reconciliation (`db update` /
200
+ * `db init`, `fromContract === null`) this strategy never fires, mirroring
201
+ * the legacy `typeChangeCallStrategy`'s requirement of a prior contract:
202
+ * `mapNodeIssueToCall`'s in-place ALTER covers reconciliation directly.
203
+ *
204
+ * A single node issue can carry BOTH type and nullability drift (Postgres
205
+ * alters in place, so the differ emits one `not-equal` column issue where
206
+ * the legacy coordinate walk emitted two: `type_mismatch` +
207
+ * `nullability_mismatch`). When this strategy consumes the issue for its
208
+ * type portion, it also emits whatever nullability delta the same node pair
209
+ * carries — using the same construction `nullableTighteningCallStrategy` /
210
+ * the mapper's direct dispatch would have used — so the issue is never
211
+ * partially handled.
212
+ */
213
+ const typeChangeCallStrategy = (issues, ctx) => {
214
+ if (ctx.fromContract === null) return { kind: "no_match" };
215
+ const dataAllowed = ctx.policy.allowedOperationClasses.includes("data");
216
+ const matched = [];
217
+ const calls = [];
218
+ for (const issue of issues) {
219
+ if (issueOutcome(issue) !== "not-equal") continue;
220
+ const pair = columnNodePair(issue);
221
+ if (pair === void 0) continue;
222
+ const { expected, actual } = pair;
223
+ if (!columnTypeChangedNativeOnly(expected, actual)) continue;
224
+ const fromType = actual.nativeType;
225
+ const toType = expected.nativeType;
226
+ const isSafeWidening = SAFE_WIDENINGS.has(`${fromType}→${toType}`);
227
+ if (!isSafeWidening && !dataAllowed) continue;
228
+ const ddlSchemaName = issueSchemaName(issue);
229
+ const tableName = issueTableName(issue);
230
+ if (ddlSchemaName === void 0 || tableName === void 0) continue;
231
+ const schemaName = emissionSchemaName(ctx, ddlSchemaName);
232
+ matched.push(issue);
233
+ const { qualifiedTargetType, formatTypeExpected } = renderColumnAlterType(expected, ctx.codecHooks);
234
+ const alterOpts = {
235
+ qualifiedTargetType,
236
+ formatTypeExpected,
237
+ rawTargetTypeForLabel: qualifiedTargetType
238
+ };
239
+ if (isSafeWidening) calls.push(new AlterColumnTypeCall(schemaName, tableName, expected.name, alterOpts));
240
+ else calls.push(new DataTransformCall(`typechange-${tableName}-${expected.name}`, `typechange-${tableName}-${expected.name}:check`, `typechange-${tableName}-${expected.name}:run`), new AlterColumnTypeCall(schemaName, tableName, expected.name, alterOpts));
241
+ if (expected.nullable !== actual.nullable) if (expected.nullable) calls.push(new DropNotNullCall(schemaName, tableName, expected.name));
242
+ else if (dataAllowed) calls.push(new DataTransformCall(`handle-nulls-${tableName}-${expected.name}`, `handle-nulls-${tableName}-${expected.name}:check`, `handle-nulls-${tableName}-${expected.name}:run`), new SetNotNullCall(schemaName, tableName, expected.name));
243
+ else calls.push(new SetNotNullCall(schemaName, tableName, expected.name));
244
+ }
245
+ if (matched.length === 0) return { kind: "no_match" };
246
+ return {
247
+ kind: "match",
248
+ issues: issues.filter((i) => !matched.includes(i)),
249
+ calls,
250
+ recipe: true
251
+ };
252
+ };
253
+ /**
254
+ * Whether the raw (unresolved) native type differs — the SAME comparison
255
+ * `typeChangeCallStrategy` always used (`fromColumn.nativeType !==
256
+ * toColumn.nativeType`), which for the widenable numeric/float types
257
+ * `SAFE_WIDENINGS` lists is identical to the resolved comparison
258
+ * `columnTypeChanged` (in `issue-planner.ts`) performs.
259
+ */
260
+ function columnTypeChangedNativeOnly(expected, actual) {
261
+ return expected.nativeType !== actual.nativeType;
262
+ }
263
+ /**
264
+ * Handles `not-equal` column issues whose type did NOT change but
265
+ * nullability tightened (contract requires NOT NULL, live column is
266
+ * nullable). A type-changed issue's nullability delta (if any) is already
267
+ * handled by `typeChangeCallStrategy`, which runs first — this strategy
268
+ * only ever sees issues that strategy left behind.
269
+ */
270
+ const nullableTighteningCallStrategy = (issues, ctx) => {
271
+ if (!ctx.policy.allowedOperationClasses.includes("data")) return { kind: "no_match" };
272
+ const matched = [];
273
+ const calls = [];
274
+ for (const issue of issues) {
275
+ if (issueOutcome(issue) !== "not-equal") continue;
276
+ const pair = columnNodePair(issue);
277
+ if (pair === void 0) continue;
278
+ const { expected, actual } = pair;
279
+ if (columnTypeChangedNativeOnly(expected, actual)) continue;
280
+ if (expected.nullable !== false || actual.nullable !== true) continue;
281
+ const ddlSchemaName = issueSchemaName(issue);
282
+ const tableName = issueTableName(issue);
283
+ if (ddlSchemaName === void 0 || tableName === void 0) continue;
284
+ const schemaName = emissionSchemaName(ctx, ddlSchemaName);
285
+ matched.push(issue);
286
+ calls.push(new DataTransformCall(`handle-nulls-${tableName}-${expected.name}`, `handle-nulls-${tableName}-${expected.name}:check`, `handle-nulls-${tableName}-${expected.name}:run`), new SetNotNullCall(schemaName, tableName, expected.name));
287
+ }
288
+ if (matched.length === 0) return { kind: "no_match" };
289
+ return {
290
+ kind: "match",
291
+ issues: issues.filter((i) => !matched.includes(i)),
292
+ calls,
293
+ recipe: true
294
+ };
295
+ };
296
+ /**
297
+ * Collects every check constraint from a table in the contract storage.
298
+ * Returns an empty array when the table has no checks or the table is absent.
299
+ */
300
+ function collectContractChecks(storage, namespaceId, tableName) {
301
+ const ns = storage.namespaces[namespaceId];
302
+ const tableRaw = ns !== void 0 ? ns.entries.table?.[tableName] : void 0;
303
+ if (!(tableRaw instanceof StorageTable)) return [];
304
+ const checks = tableRaw.checks;
305
+ if (!checks || checks.length === 0) return [];
306
+ return checks.map((c) => ({
307
+ name: c.name,
308
+ column: c.column,
309
+ permittedValues: resolveValueSetValues(c.valueSet, storage, `check "${c.name}" on "${tableName}"`)
310
+ }));
311
+ }
312
+ /**
313
+ * Compares two value arrays as unordered sets.
314
+ */
315
+ function checkValueSetsEqual(a, b) {
316
+ if (a.length !== b.length) return false;
317
+ const bSet = new Set(b);
318
+ return a.every((v) => bSet.has(v));
319
+ }
320
+ /**
321
+ * Plans check-constraint migrations for `enumType`-authored columns.
322
+ *
323
+ * Walks every namespace's tables in the target contract (the check nodes'
324
+ * resolved `permittedValues` are ultimately sourced from the same
325
+ * contract-declared value sets, so walking the contract directly is the
326
+ * simplest faithful port — the strategy's decisions never depend on which
327
+ * ISSUES happen to be in the input list, only on the contract + live schema
328
+ * shapes). For each table that carries `checks`, diffs the contract-expected
329
+ * checks against the live schema's checks:
330
+ *
331
+ * - Check in contract, absent from live DB → `AddCheckConstraintCall`.
332
+ * - Check in live DB, absent from contract → `DropCheckConstraintCall`.
333
+ * - Check on both sides but value sets differ → `DropCheckConstraintCall`
334
+ * then `AddCheckConstraintCall` (drop + recreate; a check predicate cannot
335
+ * be altered in place).
336
+ *
337
+ * Consumes every `sql-check-constraint` issue on a table this walk handles
338
+ * (not-found/not-expected/not-equal), leaving check issues on tables with
339
+ * NO contract checks to `mapNodeIssueToCall`'s `not-expected` fallback.
340
+ */
341
+ const checkConstraintPlanCallStrategy = (issues, ctx) => {
342
+ const calls = [];
343
+ const handledIssueKeys = /* @__PURE__ */ new Set();
344
+ for (const [namespaceId, ns] of Object.entries(ctx.toContract.storage.namespaces)) for (const tableName of Object.keys(ns.entries.table ?? {})) {
345
+ const contractChecks = collectContractChecks(ctx.toContract.storage, namespaceId, tableName);
346
+ if (contractChecks.length === 0) continue;
347
+ const liveChecks = ctx.schema.tables[tableName]?.checks ?? [];
348
+ const ddlSchema = resolveDdlSchemaForNamespace(ctx, namespaceId);
349
+ for (const contractCheck of contractChecks) {
350
+ const liveCheck = liveChecks.find((c) => c.name === contractCheck.name);
351
+ const issueKey = `${tableName} ${contractCheck.name}`;
352
+ if (!liveCheck) {
353
+ calls.push(new AddCheckConstraintCall(ddlSchema, tableName, contractCheck.name, contractCheck.column, contractCheck.permittedValues));
354
+ handledIssueKeys.add(issueKey);
355
+ } else if (!checkValueSetsEqual(contractCheck.permittedValues, liveCheck.permittedValues)) {
356
+ calls.push(new DropCheckConstraintCall(ddlSchema, tableName, contractCheck.name), new AddCheckConstraintCall(ddlSchema, tableName, contractCheck.name, contractCheck.column, contractCheck.permittedValues));
357
+ handledIssueKeys.add(issueKey);
358
+ } else handledIssueKeys.add(issueKey);
359
+ }
360
+ for (const liveCheck of liveChecks) if (!contractChecks.some((c) => c.name === liveCheck.name)) {
361
+ const issueKey = `${tableName} ${liveCheck.name}`;
362
+ calls.push(new DropCheckConstraintCall(ddlSchema, tableName, liveCheck.name));
363
+ handledIssueKeys.add(issueKey);
364
+ }
365
+ }
366
+ if (calls.length === 0 && handledIssueKeys.size === 0) return { kind: "no_match" };
367
+ return {
368
+ kind: "match",
369
+ issues: issues.filter((issue) => {
370
+ const node = issueNode(issue);
371
+ if (node === void 0 || node.nodeKind !== RelationalSchemaNodeKind.check) return true;
372
+ const tableName = issueTableName(issue);
373
+ if (tableName === void 0) return true;
374
+ const checkName = blindCast(node).name;
375
+ return !handledIssueKeys.has(`${tableName} ${checkName}`);
376
+ }),
377
+ calls
378
+ };
379
+ };
380
+ /**
381
+ * Dispatches codec-typed storage types through their codec's
382
+ * `planTypeOperations` hook (the authoritative source for codec-driven DDL
383
+ * such as custom type creation). Codec extension/type ops are not modeled as
384
+ * diff nodes — this strategy drives entirely off `ctx.toContract.storage.types`
385
+ * + codec hooks, consuming nothing from the node issue list (there is no
386
+ * node-vocabulary equivalent of `type_missing` / `enum_values_changed`).
387
+ */
388
+ const storageTypePlanCallStrategy = (issues, ctx) => {
389
+ const storageTypes = ctx.toContract.storage.types ?? {};
390
+ if (Object.keys(storageTypes).length === 0) return { kind: "no_match" };
391
+ const calls = [];
392
+ for (const [typeName, typeInstance] of Object.entries(storageTypes).sort(([a], [b]) => a.localeCompare(b))) {
393
+ const codecInstance = typeInstance;
394
+ const hook = ctx.codecHooks.get(codecInstance.codecId);
395
+ if (!hook?.planTypeOperations) continue;
396
+ const planResult = hook.planTypeOperations({
397
+ typeName,
398
+ typeInstance: codecInstance,
399
+ contract: ctx.toContract,
400
+ schema: ctx.schema,
401
+ schemaName: ctx.schemaName,
402
+ policy: ctx.policy
403
+ });
404
+ if (!planResult) continue;
405
+ for (const op of planResult.operations) calls.push(new RawSqlCall({
406
+ ...op,
407
+ target: {
408
+ id: op.target.id,
409
+ details: buildTargetDetails("type", typeName, ctx.schemaName)
410
+ }
411
+ }));
412
+ }
413
+ if (calls.length === 0) return { kind: "no_match" };
414
+ return {
415
+ kind: "match",
416
+ issues,
417
+ calls
418
+ };
419
+ };
420
+ /**
421
+ * Handles `not-found` column issues for NOT NULL columns without a contract
422
+ * default. Replaces the legacy `buildAddColumnItem` non-default branches.
423
+ *
424
+ * Two shapes:
425
+ * - Shared-temp-default safe: emit a single atomic composite op (add
426
+ * nullable → backfill identity value → `SET NOT NULL` → `DROP DEFAULT`).
427
+ * The temp-default value is resolved from the column node's `codecRef`
428
+ * (`resolveColumnTemporaryDefault`, wrapping `resolveIdentityValue`).
429
+ * - Empty-table guarded: emit a hand-built op with a `tableIsEmptyCheck`
430
+ * precheck so the failure message is "table is not empty" rather than the
431
+ * raw PG NOT NULL violation.
432
+ *
433
+ * "Normal" not-found column cases (nullable or has a contract default) are
434
+ * left for `mapNodeIssueToCall`'s default `AddColumnCall` emission.
435
+ */
436
+ const notNullAddColumnCallStrategy = (issues, ctx) => {
437
+ const matched = [];
438
+ const calls = [];
439
+ const schemaLookups = buildSchemaLookupMap(ctx.schema);
440
+ const mutableCodecHooks = ctx.codecHooks;
441
+ const mutableStorageTypes = ctx.storageTypes;
442
+ for (const issue of issues) {
443
+ if (issueOutcome(issue) !== "not-found") continue;
444
+ const node = issueNode(issue);
445
+ if (node === void 0 || node.nodeKind !== RelationalSchemaNodeKind.column) continue;
446
+ const expected = blindCast(issue.expected);
447
+ if (expected.nullable !== false || expected.resolvedDefault !== void 0) continue;
448
+ const ddlSchemaName = issueSchemaName(issue);
449
+ const tableName = issueTableName(issue);
450
+ if (ddlSchemaName === void 0 || tableName === void 0) continue;
451
+ const namespaceId = namespaceIdForDdlSchema(ctx, ddlSchemaName);
452
+ const schemaName = namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchemaName;
453
+ const contractTable = tableAt(ctx.toContract.storage, namespaceId, tableName);
454
+ const column = contractTable?.columns[expected.name];
455
+ if (!contractTable || !column) continue;
456
+ const schemaTable = ctx.schema.tables[tableName];
457
+ if (!schemaTable) continue;
458
+ const temporaryDefault = resolveColumnTemporaryDefault(expected, ctx.codecHooks);
459
+ const schemaLookup = schemaLookups.get(tableName);
460
+ const canUseSharedTempDefault = temporaryDefault !== null && canUseSharedTemporaryDefaultStrategy({
461
+ table: contractTable,
462
+ schemaTable,
463
+ schemaLookup,
464
+ columnName: expected.name
465
+ });
466
+ matched.push(issue);
467
+ if (canUseSharedTempDefault && temporaryDefault !== null) {
468
+ calls.push(new AddNotNullColumnWithTempDefaultCall({
469
+ schemaName,
470
+ tableName,
471
+ columnName: expected.name,
472
+ column,
473
+ codecHooks: mutableCodecHooks,
474
+ storageTypes: mutableStorageTypes,
475
+ temporaryDefault
476
+ }));
477
+ continue;
478
+ }
479
+ calls.push(new AddNotNullColumnDirectCall(schemaName, tableName, expected.name, renderColumnDdl(expected.name, expected, ctx.codecHooks)));
480
+ }
481
+ if (matched.length === 0) return { kind: "no_match" };
482
+ return {
483
+ kind: "match",
484
+ issues: issues.filter((i) => !matched.includes(i)),
485
+ calls
486
+ };
487
+ };
488
+ function canUseSharedTemporaryDefaultStrategy(options) {
489
+ const { table, schemaTable, schemaLookup, columnName } = options;
490
+ if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) return false;
491
+ for (const unique of table.uniques) {
492
+ if (!unique.columns.includes(columnName)) continue;
493
+ if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) return false;
494
+ }
495
+ for (const foreignKey of table.foreignKeys) {
496
+ if (!foreignKey.source.columns.includes(columnName)) continue;
497
+ if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) return false;
498
+ }
499
+ return true;
500
+ }
501
+ /**
502
+ * Ordered list of Postgres planner strategies, shared by `migration plan`
503
+ * and `db update` / `db init`. The issue planner runs each strategy in
504
+ * order, letting it consume any issues it handles, and routes whatever's
505
+ * left through `mapNodeIssueToCall`. Behavior diverges purely on
506
+ * `policy.allowedOperationClasses`:
507
+ *
508
+ * - When `'data'` is allowed (`migration plan`), the data-safe strategies
509
+ * (`notNullBackfillCallStrategy`, `typeChangeCallStrategy`,
510
+ * `nullableTighteningCallStrategy`) consume their matching issues and emit
511
+ * `DataTransformCall` placeholders or recipe ops.
512
+ *
513
+ * - When `'data'` is not allowed (`db update` / `db init`), the
514
+ * placeholder-emitting strategies short-circuit to `no_match`, leaving
515
+ * the issue for the downstream strategies (`storageTypePlanCallStrategy`,
516
+ * `notNullAddColumnCallStrategy`) or the `mapNodeIssueToCall` default to
517
+ * handle with direct DDL.
518
+ *
519
+ * Codec-typed storage type entries are dispatched through
520
+ * `storageTypePlanCallStrategy`.
521
+ */
522
+ const postgresPlannerStrategies = [
523
+ notNullBackfillCallStrategy,
524
+ typeChangeCallStrategy,
525
+ nullableTighteningCallStrategy,
526
+ checkConstraintPlanCallStrategy,
527
+ storageTypePlanCallStrategy,
528
+ notNullAddColumnCallStrategy
529
+ ];
530
+ /**
531
+ * Deterministic name for the element-non-null CHECK constraint on a scalar-array
532
+ * column. Distinct `_elem_not_null` suffix avoids collision with the enum
533
+ * value-set `_check` constraints. Re-emitting the same schema produces the same
534
+ * name, so `pg_get_constraintdef`-based verify sees no drift.
535
+ */
536
+ function elementNonNullCheckName(tableName, columnName) {
537
+ return `${tableName}_${columnName}_elem_not_null`;
538
+ }
539
+ /**
540
+ * Predicate enforcing that a scalar-array column carries no NULL element. The
541
+ * array column itself may be NULL (container nullability is the column's NOT NULL
542
+ * clause); `array_position` over a NULL array yields NULL, which a CHECK treats
543
+ * as satisfied, so a nullable array column is unaffected.
544
+ */
545
+ function elementNonNullCheckExpression(columnName) {
546
+ return `array_position(${quoteIdentifier(columnName)}, NULL) IS NULL`;
547
+ }
548
+ function issueConflict(kind, summary, location) {
549
+ return {
550
+ kind,
551
+ summary,
552
+ why: "Use `migration new` to author a custom migration for this change.",
553
+ ...location ? { location } : {}
554
+ };
555
+ }
556
+ /**
557
+ * Classifies calls into DDL sequencing buckets. The order matches the
558
+ * legacy walk-schema planner's emission order so `db init` and `db update`
559
+ * produce byte-identical plans for the shared shape (deps → drops → tables
560
+ * → columns → alters → PKs → uniques → indexes → FKs).
561
+ *
562
+ * `dropType` (DROP TYPE for a managed native enum) is its own bucket, ordered
563
+ * after the general drop bucket: a type can only be dropped once every table
564
+ * whose column uses it is gone. A column→enum edge would make this precise,
565
+ * but `coalesceSubtreeIssues` removes the column issue under a whole-table
566
+ * drop, so the edge never reaches the graph; the coarse bucket stands in until
567
+ * that edge lands (the coordinate work is a later slice).
568
+ */
569
+ function classifyCall(call) {
570
+ switch (call.factoryName) {
571
+ case "createExtension":
572
+ case "createSchema":
573
+ case "createNativeEnumType":
574
+ case "addNativeEnumValue": return "dep";
575
+ case "dropNativeEnumType": return "dropType";
576
+ case "dropTable":
577
+ case "dropColumn":
578
+ case "dropConstraint":
579
+ case "dropCheckConstraint":
580
+ case "dropIndex":
581
+ case "dropDefault": return "drop";
582
+ case "addCheckConstraint": return "unique";
583
+ case "createTable": return "table";
584
+ case "enableRowLevelSecurity":
585
+ case "disableRowLevelSecurity": return "rlsEnable";
586
+ case "createRlsPolicy": return "rlsPolicy";
587
+ case "dropRlsPolicy": return "drop";
588
+ case "addColumn": return "column";
589
+ case "alterColumnType":
590
+ case "setNotNull":
591
+ case "dropNotNull":
592
+ case "setDefault": return "alter";
593
+ case "addPrimaryKey": return "primaryKey";
594
+ case "addUnique": return "unique";
595
+ case "createIndex":
596
+ case "renameIndex": return "index";
597
+ case "addForeignKey": return "foreignKey";
598
+ case "rawSql":
599
+ if (call.op?.target?.details?.objectType === "type") return "dep";
600
+ return "alter";
601
+ default: return "alter";
602
+ }
603
+ }
604
+ const DEFAULT_POLICY = { allowedOperationClasses: [
605
+ "additive",
606
+ "widening",
607
+ "destructive",
608
+ "data"
609
+ ] };
610
+ function emptySchemaIR() {
611
+ return new SqlSchemaIR({ tables: {} });
612
+ }
613
+ function conflictKindForCall(call) {
614
+ switch (call.factoryName) {
615
+ case "alterColumnType": return "typeMismatch";
616
+ case "setNotNull":
617
+ case "dropNotNull": return "nullabilityConflict";
618
+ case "addForeignKey":
619
+ case "dropConstraint": return "foreignKeyConflict";
620
+ case "createIndex":
621
+ case "renameIndex":
622
+ case "dropIndex": return "indexIncompatible";
623
+ case "createRlsPolicy":
624
+ case "dropRlsPolicy":
625
+ case "renameRlsPolicy": return "rlsPolicyIncompatible";
626
+ default: return "missingButNonAdditive";
627
+ }
628
+ }
629
+ function locationForCall(call) {
630
+ const anyCall = call;
631
+ const location = {};
632
+ if (anyCall.tableName) {
633
+ location.entityKind = "table";
634
+ location.entityName = anyCall.tableName;
635
+ } else if (anyCall.typeName) {
636
+ location.entityKind = "native_enum";
637
+ location.entityName = anyCall.typeName;
638
+ }
639
+ if (anyCall.columnName) location.column = anyCall.columnName;
640
+ if (anyCall.indexName) location.index = anyCall.indexName;
641
+ else if (anyCall.newIndexName) location.index = anyCall.newIndexName;
642
+ if (anyCall.constraintName) location.constraint = anyCall.constraintName;
643
+ if (anyCall.policyName) location.rlsPolicy = anyCall.policyName;
644
+ else if (anyCall.policy?.name) location.rlsPolicy = anyCall.policy.name;
645
+ else if (anyCall.newPolicyName) location.rlsPolicy = anyCall.newPolicyName;
646
+ return Object.keys(location).length > 0 ? location : void 0;
647
+ }
648
+ function conflictForDisallowedCall(call, allowed) {
649
+ const summary = `Operation "${call.label}" requires class "${call.operationClass}", but policy allows only: ${allowed.join(", ")}`;
650
+ const location = locationForCall(call);
651
+ return {
652
+ kind: conflictKindForCall(call),
653
+ summary,
654
+ why: "Use `migration new` to author a custom migration for this change.",
655
+ ...location ? { location } : {}
656
+ };
657
+ }
658
+ /** The diff node an issue concerns — expected when present, else the actual (extra) node. */
659
+ function issueNode(issue) {
660
+ const node = issue.expected ?? issue.actual;
661
+ if (node === void 0) return void 0;
662
+ return blindCast(node);
663
+ }
664
+ /** DDL schema segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */
665
+ function issueSchemaName(issue) {
666
+ return issue.path[1];
667
+ }
668
+ /** Table segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */
669
+ function issueTableName(issue) {
670
+ return issue.path[2];
671
+ }
672
+ /** Column name embedded in a column/default issue path segment (`column:<name>`). */
673
+ function issueColumnName(issue) {
674
+ const segment = issue.path[3];
675
+ if (segment === void 0 || !segment.startsWith("column:")) return void 0;
676
+ return segment.slice(7);
677
+ }
678
+ /**
679
+ * The DDL schema name to use when EMITTING an op against `ddlSchemaName` (the
680
+ * diff tree's resolved physical schema, `issueSchemaName(issue)`). The
681
+ * unbound namespace's diff-tree identity resolves to `public` (a concrete
682
+ * physical default the differ needs in order to compare its tree against
683
+ * introspection — `resolveDdlSchemaForNamespaceStorage`), but DDL EMISSION
684
+ * must stay unqualified so the live connection's `search_path` resolves it
685
+ * at runtime (`boundSchema`). Recovers the logical namespace id via the
686
+ * contract and substitutes the unbound sentinel back in when it resolves
687
+ * there; every other namespace's `ddlSchemaName` already agrees between the
688
+ * two resolution paths, so it passes through unchanged.
689
+ */
690
+ function emissionSchemaName(ctx, ddlSchemaName) {
691
+ return resolveNamespaceIdForDdlSchema(ctx.toContract, ddlSchemaName) === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchemaName;
692
+ }
693
+ /**
694
+ * Whether a column node is a scalar-array (`many: true`) column. The family
695
+ * converter (`contractToSchemaIR`'s `convertColumn`) never stamps `many` on
696
+ * the derived node — array-ness is folded into the `[]` suffix on
697
+ * `nativeType` instead — so the node-derived check reads the suffix; `.many`
698
+ * is still checked first for nodes a caller stamps directly (e.g. hand-built
699
+ * test fixtures, or an adapter that populates it at introspection).
700
+ */
701
+ function isManyColumn(column) {
702
+ return column.many === true || column.nativeType.endsWith("[]");
703
+ }
704
+ /** Whether the expected/actual native type (resolved, or raw+many fallback) differs — mirrors `SqlColumnIR.isEqualTo`'s type comparison. */
705
+ function columnTypeChanged(expected, actual) {
706
+ if (expected.resolvedNativeType !== void 0 && actual.resolvedNativeType !== void 0) return expected.resolvedNativeType !== actual.resolvedNativeType;
707
+ return expected.nativeType !== actual.nativeType || Boolean(expected.many) !== Boolean(actual.many);
708
+ }
709
+ /**
710
+ * The generic differ is total: a missing/extra table (or column) emits an
711
+ * issue for itself AND for every node in its subtree. `CreateTable`/`DropTable`
712
+ * and `AddColumn`/`DropColumn` already account for the whole subtree, so the
713
+ * nested issues are redundant — coalescing drops any issue whose path is a
714
+ * strict descendant of a `not-found`/`not-expected` issue's path. Run over the
715
+ * relational subset ONLY (policy issues and synthesized namespace issues are
716
+ * handled on their own paths, never coalesced against tables).
717
+ */
718
+ function coalesceSubtreeIssues(issues) {
719
+ const collapsingPaths = issues.filter((issue) => issueOutcome(issue) !== "not-equal").map((issue) => issue.path);
720
+ if (collapsingPaths.length === 0) return issues;
721
+ return issues.filter((issue) => !collapsingPaths.some((ancestor) => isStrictDescendantPath(issue.path, ancestor)));
722
+ }
723
+ function isStrictDescendantPath(path, ancestor) {
724
+ if (path.length <= ancestor.length) return false;
725
+ for (let i = 0; i < ancestor.length; i += 1) if (path[i] !== ancestor[i]) return false;
726
+ return true;
727
+ }
728
+ function fkSpecFromNode(fk, tableName) {
729
+ return {
730
+ name: fk.name ?? `${tableName}_${fk.columns.join("_")}_fkey`,
731
+ columns: [...fk.columns],
732
+ references: {
733
+ schema: fk.referencedSchema ?? "",
734
+ table: fk.referencedTable,
735
+ columns: [...fk.referencedColumns]
736
+ },
737
+ ...ifDefined("onDelete", fk.onDelete),
738
+ ...ifDefined("onUpdate", fk.onUpdate)
739
+ };
740
+ }
741
+ /**
742
+ * Builds the `CreateTable` + child `CreateIndex` / `AddForeignKey` / `AddUnique`
743
+ * calls for a newly-expected table, reading only the table node's children. The
744
+ * PK and element-non-null CHECKs go inline as table constraints; indexes
745
+ * (declared + FK-backing, already merged and ordered at derivation) and the
746
+ * FK / unique constraints are separate calls (re-bucketed downstream). Every
747
+ * column's DDL is resolved from its `codecRef` via `renderColumnDdl`.
748
+ */
749
+ function buildCreateTableCallsFromNode(schemaName, ddlSchemaName, table, codecHooks) {
750
+ const ddlColumns = Object.values(table.columns).map((c) => renderColumnDdl(c.name, c, codecHooks));
751
+ const primaryKeyConstraints = table.primaryKey ? [contractFree.primaryKey([...table.primaryKey.columns], { ...ifDefined("name", table.primaryKey.name) })] : [];
752
+ const elementNonNullChecks = Object.values(table.columns).filter((c) => isManyColumn(c)).map((c) => contractFree.checkExpression(elementNonNullCheckName(table.name, c.name), elementNonNullCheckExpression(c.name)));
753
+ const allTableConstraints = [...primaryKeyConstraints, ...elementNonNullChecks];
754
+ const calls = [new CreateTableCall(schemaName, table.name, ddlColumns, allTableConstraints.length > 0 ? allTableConstraints : void 0)];
755
+ for (const index of table.indexes) calls.push(createIndexCallFromNode(index, schemaName, table.name));
756
+ for (const fk of table.foreignKeys) calls.push(new AddForeignKeyCall(schemaName, table.name, fkSpecFromNode(fk, table.name)));
757
+ for (const unique of table.uniques) {
758
+ const constraintName = unique.name ?? `${table.name}_${unique.columns.join("_")}_key`;
759
+ calls.push(new AddUniqueCall(schemaName, table.name, constraintName, [...unique.columns]));
760
+ }
761
+ if (table.rlsEnabled) calls.push(new EnableRowLevelSecurityCall(ddlSchemaName, table.name));
762
+ return calls;
763
+ }
764
+ function nodeConflict(kind, message) {
765
+ return issueConflict(kind, message);
766
+ }
767
+ /**
768
+ * True when `actualMembers` (the live database's ordered members) is a
769
+ * strict, order-preserving prefix of `expectedMembers` (the contract's) —
770
+ * the database already carries every contract member, in declaration
771
+ * order, and the contract declares at least one member the database still
772
+ * lacks. Any other relationship — a renamed value, a removed value, a
773
+ * reordering, or the database holding members the contract lacks — is not
774
+ * a suffix append.
775
+ */
776
+ function isNativeEnumSuffixAppend(actualMembers, expectedMembers) {
777
+ if (actualMembers.length >= expectedMembers.length) return false;
778
+ return actualMembers.every((member, index) => member === expectedMembers[index]);
779
+ }
780
+ /** Operator-worded refusal for a native-enum member change beyond a suffix append (design ruling — tests match this verbatim). */
781
+ function nativeEnumMemberChangeRefusal(options) {
782
+ return `Native enum type "${options.ddlSchemaName}"."${options.typeName}" changed beyond appending new values (contract declares [${options.expectedMembers.join(", ")}], database has [${options.actualMembers.join(", ")}]). Prisma Next does not modify a native enum's existing values (rename, removal, reorder) — see https://pris.ly/d/postgres-native-enums. Author the change manually with \`migration new\`.`;
783
+ }
784
+ /**
785
+ * Managed native-enum issue -> op lowering. A missing declared type creates
786
+ * it; an unclaimed live type drops it (ownership-scoped upstream by
787
+ * `retainUnownedExtras`, destructiveness gated by the operation-class
788
+ * policy); a paired member-value mismatch lowers to one `ALTER TYPE ... ADD
789
+ * VALUE` per appended member when the database's members are a strict,
790
+ * order-preserving prefix of the contract's — any other change (rename,
791
+ * removal, reorder, or the database holding members the contract lacks) is
792
+ * refused with a NAMED diagnostic, never a silent no-op and never a
793
+ * drop-and-recreate.
794
+ */
795
+ function mapNativeEnumNodeIssue(issue, ctx) {
796
+ const ddlSchemaName = issueSchemaName(issue);
797
+ if (ddlSchemaName === void 0) return notOk(nodeConflict("unsupportedOperation", `Enum issue has no schema in its path: ${issue.path.join("/")}`));
798
+ const schemaName = emissionSchemaName(ctx, ddlSchemaName);
799
+ if (issueOutcome(issue) === "not-found") {
800
+ const expected = blindCast(issue.expected);
801
+ return ok([new CreateNativeEnumTypeCall(schemaName, expected.typeName, expected.members)]);
802
+ }
803
+ if (issueOutcome(issue) === "not-expected") return ok([new DropNativeEnumTypeCall(schemaName, blindCast(issue.actual).typeName)]);
804
+ const expected = blindCast(issue.expected);
805
+ const actual = blindCast(issue.actual);
806
+ if (isNativeEnumSuffixAppend(actual.members, expected.members)) return ok(expected.members.slice(actual.members.length).map((value) => new AddNativeEnumValueCall(schemaName, expected.typeName, value)));
807
+ return notOk(nodeConflict("unsupportedOperation", nativeEnumMemberChangeRefusal({
808
+ ddlSchemaName,
809
+ typeName: expected.typeName,
810
+ expectedMembers: expected.members,
811
+ actualMembers: actual.members
812
+ })));
813
+ }
814
+ function mapTableNodeIssue(issue, schemaName, ddlSchemaName, codecHooks) {
815
+ if (issueOutcome(issue) === "not-found") return ok(buildCreateTableCallsFromNode(schemaName, ddlSchemaName, blindCast(issue.expected), codecHooks));
816
+ if (issueOutcome(issue) === "not-expected") return ok([new DropTableCall(schemaName, blindCast(issue.actual).name)]);
817
+ const expected = blindCast(issue.expected);
818
+ const actual = blindCast(issue.actual);
819
+ if (expected.rlsEnabled && !actual.rlsEnabled) return ok([new EnableRowLevelSecurityCall(ddlSchemaName, expected.name)]);
820
+ if (!expected.rlsEnabled && actual.rlsEnabled) return ok([new DisableRowLevelSecurityCall(ddlSchemaName, expected.name)]);
821
+ return notOk(nodeConflict("unsupportedOperation", `unhandled table-attribute drift on "${expected.name}": table not-equal with no rlsEnabled delta (a second table attribute drifted)`));
822
+ }
823
+ function mapColumnNodeIssue(issue, schemaName, tableName, codecHooks) {
824
+ if (issueOutcome(issue) === "not-found") {
825
+ const column = blindCast(issue.expected);
826
+ return ok([new AddColumnCall(schemaName, tableName, renderColumnDdl(column.name, column, codecHooks))]);
827
+ }
828
+ if (issueOutcome(issue) === "not-expected") return ok([new DropColumnCall(schemaName, tableName, blindCast(issue.actual).name)]);
829
+ const expected = blindCast(issue.expected);
830
+ const actual = blindCast(issue.actual);
831
+ const calls = [];
832
+ if (columnTypeChanged(expected, actual)) {
833
+ const { qualifiedTargetType, formatTypeExpected } = renderColumnAlterType(expected, codecHooks);
834
+ calls.push(new AlterColumnTypeCall(schemaName, tableName, expected.name, {
835
+ qualifiedTargetType,
836
+ formatTypeExpected,
837
+ rawTargetTypeForLabel: qualifiedTargetType
838
+ }));
839
+ }
840
+ if (expected.nullable !== actual.nullable) calls.push(expected.nullable ? new DropNotNullCall(schemaName, tableName, expected.name) : new SetNotNullCall(schemaName, tableName, expected.name));
841
+ return ok(calls);
842
+ }
843
+ function mapColumnDefaultNodeIssue(issue, schemaName, tableName, columnName) {
844
+ if (issueOutcome(issue) === "not-expected") return ok([new DropDefaultCall(schemaName, tableName, columnName)]);
845
+ if (issue.expected === void 0) return ok([]);
846
+ const defaultSql = renderColumnDefaultSql(blindCast(issue.expected));
847
+ if (!defaultSql) return ok([]);
848
+ return ok([new SetDefaultCall(schemaName, tableName, columnName, defaultSql, issueOutcome(issue) === "not-equal" ? "widening" : "additive")]);
849
+ }
850
+ function mapPrimaryKeyNodeIssue(issue, schemaName, tableName) {
851
+ if (issueOutcome(issue) === "not-found") {
852
+ const pk = blindCast(issue.expected);
853
+ return ok([new AddPrimaryKeyCall(schemaName, tableName, pk.name ?? `${tableName}_pkey`, [...pk.columns])]);
854
+ }
855
+ if (issueOutcome(issue) === "not-expected") return ok([new DropConstraintCall(schemaName, tableName, blindCast(issue.actual).name ?? `${tableName}_pkey`, "primaryKey")]);
856
+ return notOk(nodeConflict("indexIncompatible", issue.path.join("/")));
857
+ }
858
+ function mapForeignKeyNodeIssue(issue, schemaName, tableName) {
859
+ if (issueOutcome(issue) === "not-found") return ok([new AddForeignKeyCall(schemaName, tableName, fkSpecFromNode(blindCast(issue.expected), tableName))]);
860
+ if (issueOutcome(issue) === "not-expected") {
861
+ const fk = blindCast(issue.actual);
862
+ return ok([new DropConstraintCall(schemaName, tableName, fk.name ?? `${tableName}_${fk.columns.join("_")}_fkey`, "foreignKey")]);
863
+ }
864
+ return notOk(nodeConflict("foreignKeyConflict", issue.path.join("/")));
865
+ }
866
+ function mapUniqueNodeIssue(issue, schemaName, tableName) {
867
+ if (issueOutcome(issue) === "not-found") {
868
+ const unique = blindCast(issue.expected);
869
+ return ok([new AddUniqueCall(schemaName, tableName, unique.name ?? `${tableName}_${unique.columns.join("_")}_key`, [...unique.columns])]);
870
+ }
871
+ if (issueOutcome(issue) === "not-expected") {
872
+ const unique = blindCast(issue.actual);
873
+ return ok([new DropConstraintCall(schemaName, tableName, unique.name ?? `${tableName}_${unique.columns.join("_")}_key`, "unique")]);
874
+ }
875
+ return notOk(nodeConflict("indexIncompatible", issue.path.join("/")));
876
+ }
877
+ /**
878
+ * The CreateIndexCall for a name-identified index node: the node's own name
879
+ * verbatim, its element list (column tuple or opaque expression), and the
880
+ * unique/type/options/where attributes carried through.
881
+ */
882
+ function createIndexCallFromNode(index, schemaName, tableName) {
883
+ const extras = {};
884
+ if (index.type !== void 0) extras.type = index.type;
885
+ if (index.options !== void 0) extras.options = index.options;
886
+ if (index.where !== void 0) extras.where = index.where;
887
+ if (index.unique) extras.unique = true;
888
+ return new CreateIndexCall(schemaName, tableName, index.name, index.columns !== void 0 ? { columns: [...index.columns] } : { expression: index.expression ?? "" }, extras);
889
+ }
890
+ function mapIndexNodeIssue(issue, schemaName, tableName) {
891
+ if (issueOutcome(issue) === "not-found") return ok([createIndexCallFromNode(blindCast(issue.expected), schemaName, tableName)]);
892
+ if (issueOutcome(issue) === "not-expected") return ok([new DropIndexCall(schemaName, tableName, blindCast(issue.actual).name)]);
893
+ return notOk(nodeConflict("indexIncompatible", issue.path.join("/")));
894
+ }
895
+ function mapCheckNodeIssue(issue, schemaName, tableName) {
896
+ if (issueOutcome(issue) === "not-expected") return ok([new DropCheckConstraintCall(schemaName, tableName, blindCast(issue.actual).name)]);
897
+ return notOk(nodeConflict("unsupportedOperation", `Check constraint drift on "${tableName}" — handled by checkConstraintPlanCallStrategy: ${issue.path.join("/")}`));
898
+ }
899
+ /**
900
+ * Maps one node-typed diff issue to its migration call(s), dispatching on the
901
+ * node's `nodeKind` and the issue's presence-derived `issueOutcome`, reading
902
+ * nodes and resolving column DDL from `codecRef` via `column-ddl-rendering.ts`.
903
+ */
904
+ function mapNodeIssueToCall(issue, ctx) {
905
+ const node = issueNode(issue);
906
+ if (node === void 0) return notOk(nodeConflict("unsupportedOperation", `Issue carries neither an expected nor an actual node: ${issue.path.join("/")}`));
907
+ if (node.nodeKind === PostgresSchemaNodeKind.namespace) {
908
+ if (issueOutcome(issue) !== "not-found") return notOk(nodeConflict("unsupportedOperation", `Unexpected namespace drift: ${issue.path.join("/")}`));
909
+ return ok([new CreateSchemaCall(blindCast(issue.expected).schemaName)]);
910
+ }
911
+ if (node.nodeKind === PostgresSchemaNodeKind.nativeEnum) return mapNativeEnumNodeIssue(issue, ctx);
912
+ const ddlSchemaName = issueSchemaName(issue);
913
+ const tableName = issueTableName(issue);
914
+ if (ddlSchemaName === void 0 || tableName === void 0) return notOk(nodeConflict("unsupportedOperation", `Issue has no schema/table in its path: ${issue.path.join("/")}`));
915
+ const schemaName = emissionSchemaName(ctx, ddlSchemaName);
916
+ switch (node.nodeKind) {
917
+ case PostgresSchemaNodeKind.table: return mapTableNodeIssue(issue, schemaName, ddlSchemaName, ctx.codecHooks);
918
+ case RelationalSchemaNodeKind.column: return mapColumnNodeIssue(issue, schemaName, tableName, ctx.codecHooks);
919
+ case RelationalSchemaNodeKind.columnDefault: {
920
+ const columnName = issueColumnName(issue);
921
+ if (columnName === void 0) return notOk(nodeConflict("unsupportedOperation", `Default issue has no column in its path: ${issue.path.join("/")}`));
922
+ return mapColumnDefaultNodeIssue(issue, schemaName, tableName, columnName);
923
+ }
924
+ case RelationalSchemaNodeKind.primaryKey: return mapPrimaryKeyNodeIssue(issue, schemaName, tableName);
925
+ case RelationalSchemaNodeKind.foreignKey: return mapForeignKeyNodeIssue(issue, schemaName, tableName);
926
+ case RelationalSchemaNodeKind.unique: return mapUniqueNodeIssue(issue, schemaName, tableName);
927
+ case RelationalSchemaNodeKind.index: return mapIndexNodeIssue(issue, schemaName, tableName);
928
+ case RelationalSchemaNodeKind.check: return mapCheckNodeIssue(issue, schemaName, tableName);
929
+ default: return notOk(nodeConflict("unsupportedOperation", `Unhandled node kind: ${node.nodeKind}`));
930
+ }
931
+ }
932
+ /**
933
+ * Runs the ordered strategy list over the node-typed diff issues, maps
934
+ * leftover issues via {@link mapNodeIssueToCall}, applies operation-class
935
+ * policy gating, and buckets calls into the fixed DDL emission order (dep →
936
+ * drop → table → column → recipe → alter → primaryKey → unique → index →
937
+ * foreignKey).
938
+ */
939
+ function planIssues(options) {
940
+ const policyProvided = options.policy !== void 0;
941
+ const policy = options.policy ?? DEFAULT_POLICY;
942
+ const schema = options.schema ?? emptySchemaIR();
943
+ const frameworkComponents = options.frameworkComponents ?? [];
944
+ const context = {
945
+ toContract: options.toContract,
946
+ fromContract: options.fromContract,
947
+ schemaName: options.schemaName,
948
+ codecHooks: options.codecHooks,
949
+ storageTypes: options.storageTypes,
950
+ schema,
951
+ policy,
952
+ frameworkComponents
953
+ };
954
+ const strategies = options.strategies ?? postgresPlannerStrategies;
955
+ let remaining = options.issues;
956
+ const recipeCalls = [];
957
+ const bucketablePatternCalls = [];
958
+ for (const strategy of strategies) {
959
+ const result = strategy(remaining, context);
960
+ if (result.kind === "match") {
961
+ remaining = result.issues;
962
+ if (result.recipe) recipeCalls.push(...result.calls);
963
+ else bucketablePatternCalls.push(...result.calls);
964
+ }
965
+ }
966
+ const sorted = orderIssuesByDependencies(remaining);
967
+ const defaultCalls = [];
968
+ const conflicts = [];
969
+ for (const issue of sorted) {
970
+ const result = mapNodeIssueToCall(issue, context);
971
+ if (result.ok) defaultCalls.push(...result.value);
972
+ else conflicts.push(result.failure);
973
+ }
974
+ const allowed = policy.allowedOperationClasses;
975
+ let gatedDefault = defaultCalls;
976
+ let gatedRecipe = recipeCalls;
977
+ let gatedBucketable = bucketablePatternCalls;
978
+ if (policyProvided) {
979
+ const keepIfAllowed = (bucket) => (call) => {
980
+ if (allowed.includes(call.operationClass)) {
981
+ bucket.push(call);
982
+ return;
983
+ }
984
+ conflicts.push(conflictForDisallowedCall(call, allowed));
985
+ };
986
+ const gatedDefaultBucket = [];
987
+ const gatedRecipeBucket = [];
988
+ const gatedBucketableBucket = [];
989
+ defaultCalls.forEach(keepIfAllowed(gatedDefaultBucket));
990
+ recipeCalls.forEach(keepIfAllowed(gatedRecipeBucket));
991
+ bucketablePatternCalls.forEach(keepIfAllowed(gatedBucketableBucket));
992
+ gatedDefault = gatedDefaultBucket;
993
+ gatedRecipe = gatedRecipeBucket;
994
+ gatedBucketable = gatedBucketableBucket;
995
+ }
996
+ if (conflicts.length > 0) return notOk(conflicts);
997
+ const combinedBucketable = [...gatedDefault, ...gatedBucketable];
998
+ const byCategory = (cat) => combinedBucketable.filter((c) => classifyCall(c) === cat);
999
+ return ok({ calls: [
1000
+ ...byCategory("dep"),
1001
+ ...byCategory("drop"),
1002
+ ...byCategory("dropType"),
1003
+ ...byCategory("table"),
1004
+ ...byCategory("column"),
1005
+ ...gatedRecipe,
1006
+ ...byCategory("alter"),
1007
+ ...byCategory("primaryKey"),
1008
+ ...byCategory("unique"),
1009
+ ...byCategory("index"),
1010
+ ...byCategory("foreignKey"),
1011
+ ...byCategory("rlsEnable")
1012
+ ] });
1013
+ }
1014
+ /**
1015
+ * Factory calls that create a whole, previously-absent top-level storage
1016
+ * object. Used to decide whether `tolerated` permits a call (it only allows
1017
+ * creating absent objects, never modifying existing ones).
1018
+ *
1019
+ * Deliberately an explicit, closed set rather than a `factoryName`
1020
+ * create/alter/drop classification: it answers exactly one yes/no question
1021
+ * and is fail-closed. Any call not listed here — including future or
1022
+ * extension-contributed factories — is treated as NOT object-creation, so it
1023
+ * is suppressed under `tolerated` rather than permissively emitted.
1024
+ *
1025
+ * Lists the creation factories that actually reach the call-side resolver
1026
+ * (`resolvePostgresCallControlPolicySubject`) — today only RLS policy
1027
+ * creation, from `planPostgresSchemaDiff`. Every other whole-object create
1028
+ * (table, schema, native enum, and RLS enablement) is constructed inside
1029
+ * `planIssues` and graded on the node side by
1030
+ * `resolvePostgresNodeIssueCreationFactoryName`, so none of them are listed
1031
+ * here.
1032
+ */
1033
+ const OBJECT_CREATION_FACTORIES = /* @__PURE__ */ new Set(["createRlsPolicy"]);
1034
+ function createsNewTopLevelObject(call) {
1035
+ return OBJECT_CREATION_FACTORIES.has(call.factoryName);
1036
+ }
1037
+ function ddlSchemaNameForNamespace(contract, namespaceId) {
1038
+ const namespace = contract.storage.namespaces[namespaceId];
1039
+ return isPostgresSchema(namespace) ? namespace.ddlSchemaName(contract.storage) : namespaceId;
1040
+ }
1041
+ /**
1042
+ * Resolve the namespace a declared storage entity lives in by walking every
1043
+ * namespace for one whose `entries` map actually contains the coordinate —
1044
+ * a table by its name, a native enum by its physical type name (see
1045
+ * {@link postgresNodeStorageCoordinate}). When `ddlSchemaName` is given, the
1046
+ * match must also land in that DDL schema (disambiguates same-named entities
1047
+ * declared under different namespaces); when omitted, the first namespace
1048
+ * that declares the entity wins. Falls back to {@link UNBOUND_NAMESPACE_ID}
1049
+ * when no namespace declares it — e.g. an extra/dropped entity the contract
1050
+ * doesn't claim at all.
1051
+ */
1052
+ function resolveNamespaceIdForEntity(contract, coordinate, ddlSchemaName) {
1053
+ for (const namespaceId of Object.keys(contract.storage.namespaces)) {
1054
+ if (!entityAt(contract.storage, {
1055
+ namespaceId,
1056
+ ...coordinate
1057
+ })) continue;
1058
+ if (ddlSchemaName === void 0 || ddlSchemaNameForNamespace(contract, namespaceId) === ddlSchemaName) return namespaceId;
1059
+ }
1060
+ return UNBOUND_NAMESPACE_ID;
1061
+ }
1062
+ function resolveNamespaceIdForTable(contract, tableName, ddlSchemaName) {
1063
+ return resolveNamespaceIdForEntity(contract, {
1064
+ entityKind: "table",
1065
+ entityName: tableName
1066
+ }, ddlSchemaName);
1067
+ }
1068
+ function resolveNamespaceIdForDdlSchema(contract, ddlSchemaName) {
1069
+ for (const namespaceId of Object.keys(contract.storage.namespaces)) {
1070
+ const ns = contract.storage.namespaces[namespaceId];
1071
+ if (isPostgresSchema(ns) && ns.ddlSchemaName(contract.storage) === ddlSchemaName) return namespaceId;
1072
+ if (namespaceId === ddlSchemaName) return namespaceId;
1073
+ }
1074
+ return UNBOUND_NAMESPACE_ID;
1075
+ }
1076
+ function postgresCallFields(call) {
1077
+ return {
1078
+ ...ifDefined("schemaName", "schemaName" in call ? call.schemaName : void 0),
1079
+ ...ifDefined("tableName", "tableName" in call ? call.tableName : void 0),
1080
+ ...ifDefined("columnName", "columnName" in call ? call.columnName : void 0)
1081
+ };
1082
+ }
1083
+ function formatSuppressionSubjectLabel(subject, contract) {
1084
+ if (subject === void 0) return "unknown";
1085
+ const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);
1086
+ if (subject.entityKind !== void 0 && subject.entityName !== void 0) {
1087
+ const entityLabel = `${subject.entityKind} "${ddlSchema}.${subject.entityName}"`;
1088
+ return subject.rlsPolicy !== void 0 ? `RLS policy "${subject.rlsPolicy}" on ${entityLabel}` : entityLabel;
1089
+ }
1090
+ return `namespace "${ddlSchema}"`;
1091
+ }
1092
+ function postgresSuppressionSummary(subjectLabel, subject, policy) {
1093
+ const namespace = subject?.namespaceId ?? "unknown";
1094
+ const declared = subject?.explicitNodeControlPolicy;
1095
+ if (policy === "external" && declared === "managed") return `control policy suppressed: ${subjectLabel} — namespace '${namespace}' has effective control 'external' but declared 'managed'`;
1096
+ return `control policy suppressed: ${subjectLabel} — namespace '${namespace}' has effective control '${policy}'${declared ? ` but declared '${declared}'` : ""}`;
1097
+ }
1098
+ /**
1099
+ * Render one family {@link SuppressionRecord} into a target `SqlPlannerConflict`.
1100
+ * The family decides *that* a subject is suppressed and hands over the raw
1101
+ * coordinate + policy; the label, message, and location are rendered here,
1102
+ * driven entirely by the subject's own `(entityKind, entityName)` coordinate
1103
+ * — no target-owned table-vs-enum vocabulary.
1104
+ */
1105
+ function renderPostgresSuppression(record, contract) {
1106
+ const subject = record.subject;
1107
+ return {
1108
+ kind: "controlPolicySuppressedCall",
1109
+ summary: postgresSuppressionSummary(formatSuppressionSubjectLabel(subject, contract), subject, record.policy),
1110
+ location: {
1111
+ ...ifDefined("namespaceId", subject?.namespaceId),
1112
+ ...ifDefined("entityKind", subject?.entityKind),
1113
+ ...ifDefined("entityName", subject?.entityName),
1114
+ ...ifDefined("column", subject?.column),
1115
+ ...ifDefined("rlsPolicy", subject?.rlsPolicy)
1116
+ },
1117
+ meta: {
1118
+ controlPolicy: record.policy,
1119
+ ...ifDefined("factoryName", record.factoryName),
1120
+ ...ifDefined("rlsPolicy", subject?.rlsPolicy),
1121
+ ...ifDefined("declaredControlPolicy", subject?.explicitNodeControlPolicy)
1122
+ }
1123
+ };
1124
+ }
1125
+ function resolvePostgresCallControlPolicySubject(call, contract) {
1126
+ const callFields = postgresCallFields(call);
1127
+ const createsNewObject = createsNewTopLevelObject(call);
1128
+ if (call.factoryName === "createSchema" && callFields.schemaName) return {
1129
+ namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),
1130
+ createsNewObject
1131
+ };
1132
+ if (callFields.tableName) {
1133
+ const namespaceId = resolveNamespaceIdForTable(contract, callFields.tableName, callFields.schemaName);
1134
+ const tableControlPolicy = entityAt(contract.storage, {
1135
+ namespaceId,
1136
+ entityKind: "table",
1137
+ entityName: callFields.tableName
1138
+ })?.control;
1139
+ return {
1140
+ namespaceId,
1141
+ entityKind: "table",
1142
+ entityName: callFields.tableName,
1143
+ ...ifDefined("column", callFields.columnName),
1144
+ ...ifDefined("explicitNodeControlPolicy", tableControlPolicy),
1145
+ createsNewObject
1146
+ };
1147
+ }
1148
+ if (callFields.schemaName) return {
1149
+ namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),
1150
+ createsNewObject
1151
+ };
1152
+ }
1153
+ /**
1154
+ * Node kinds whose *absence* is the creation of a whole, top-level Postgres
1155
+ * object: a namespace, a table, or a native enum. Used by
1156
+ * {@link resolvePostgresNodeIssueCreationFactoryName} to decide whether a
1157
+ * `tolerated` subject permits the issue to flow into the planner
1158
+ * (create-if-absent) and to seed the suppressed-subject warning's
1159
+ * `factoryName` when the planner is skipped. RLS policy creation is not
1160
+ * listed here — policy issues never reach this issue-based partition (they
1161
+ * are routed to `planPostgresSchemaDiff` and gated via the call-based
1162
+ * {@link resolvePostgresCallControlPolicySubject} instead).
1163
+ */
1164
+ const POSTGRES_NODE_CREATION_FACTORY = Object.freeze({
1165
+ [PostgresSchemaNodeKind.namespace]: "createSchema",
1166
+ [PostgresSchemaNodeKind.table]: "createTable",
1167
+ [PostgresSchemaNodeKind.nativeEnum]: "createNativeEnumType"
1168
+ });
1169
+ /**
1170
+ * A table `not-equal` issue whose `rlsEnabled` flips OFF→ON (expected on,
1171
+ * actual off) is enablement toward `ENABLE ROW LEVEL SECURITY`. It is
1172
+ * creation-class on the node side because `isEnablementCreationIssue` and
1173
+ * {@link resolvePostgresNodeIssueCreationFactoryName} treat this OFF→ON delta
1174
+ * as a creation: enabling RLS establishes the fail-closed guard the declared
1175
+ * policy set attaches to, the same grant `tolerated` extends to creating the
1176
+ * policies themselves. The opposite direction (`DISABLE`) is a modification
1177
+ * and stays managed-only. Keying on the actual delta (not just the expected
1178
+ * bit) keeps this correct if a second table attribute ever joins
1179
+ * `isEqualTo`: a not-equal with no `rlsEnabled` delta is not enablement, so
1180
+ * it is not admitted as creation-class here.
1181
+ */
1182
+ function isEnablementCreationIssue(issue) {
1183
+ if (issueOutcome(issue) !== "not-equal") return false;
1184
+ const { expected, actual } = issue;
1185
+ return expected !== void 0 && actual !== void 0 && PostgresTableSchemaNode.is(expected) && PostgresTableSchemaNode.is(actual) && expected.rlsEnabled === true && actual.rlsEnabled === false;
1186
+ }
1187
+ function resolvePostgresNodeIssueCreationFactoryName(issue) {
1188
+ if (isEnablementCreationIssue(issue)) return "enableRowLevelSecurity";
1189
+ if (issueOutcome(issue) !== "not-found") return void 0;
1190
+ const node = issue.expected ?? issue.actual;
1191
+ if (node === void 0) return void 0;
1192
+ return POSTGRES_NODE_CREATION_FACTORY[node.nodeKind];
1193
+ }
1194
+ /**
1195
+ * Resolves the control-policy subject for a node-typed {@link SchemaDiffIssue}
1196
+ * (the issue-side mirror of `resolvePostgresCallControlPolicySubject`).
1197
+ * Storage entities resolve off their node coordinate; a sub-entity issue
1198
+ * resolves off the enclosing table read from the issue path; an unclaimed
1199
+ * extra falls back to the unbound coordinate. A role always resolves
1200
+ * `'external'` — roles are referenced, never owned.
1201
+ */
1202
+ function resolvePostgresNodeIssueControlPolicySubject(issue, contract) {
1203
+ const node = issue.expected ?? issue.actual;
1204
+ if (node === void 0) return void 0;
1205
+ if (node.nodeKind === PostgresSchemaNodeKind.namespace) return {
1206
+ namespaceId: resolveNamespaceIdForDdlSchema(contract, blindCast(node).schemaName),
1207
+ createsNewObject: issueOutcome(issue) === "not-found"
1208
+ };
1209
+ if (node.nodeKind === PostgresSchemaNodeKind.role) {
1210
+ const roleName = issue.path[1];
1211
+ return {
1212
+ namespaceId: UNBOUND_NAMESPACE_ID,
1213
+ explicitNodeControlPolicy: (roleName === void 0 ? void 0 : entityAt(contract.storage, {
1214
+ namespaceId: UNBOUND_NAMESPACE_ID,
1215
+ entityKind: "role",
1216
+ entityName: roleName
1217
+ }))?.control ?? "external",
1218
+ createsNewObject: false
1219
+ };
1220
+ }
1221
+ const coordinate = postgresNodeStorageCoordinate(node);
1222
+ if (coordinate !== void 0) {
1223
+ const namespaceId = resolveNamespaceIdForEntity(contract, coordinate, issue.path[1]);
1224
+ const entityControl = entityAt(contract.storage, {
1225
+ namespaceId,
1226
+ ...coordinate
1227
+ })?.control;
1228
+ return {
1229
+ namespaceId,
1230
+ ...coordinate,
1231
+ ...ifDefined("column", issueColumnName(issue)),
1232
+ ...ifDefined("explicitNodeControlPolicy", entityControl),
1233
+ createsNewObject: resolvePostgresNodeIssueCreationFactoryName(issue) !== void 0
1234
+ };
1235
+ }
1236
+ const tableName = issue.path[2];
1237
+ if (tableName === void 0) return void 0;
1238
+ const ddlSchemaName = issue.path[1];
1239
+ const namespaceId = resolveNamespaceIdForTable(contract, tableName, ddlSchemaName);
1240
+ const table = entityAt(contract.storage, {
1241
+ namespaceId,
1242
+ entityKind: "table",
1243
+ entityName: tableName
1244
+ });
1245
+ return {
1246
+ namespaceId,
1247
+ entityKind: "table",
1248
+ entityName: tableName,
1249
+ ...ifDefined("column", issueColumnName(issue)),
1250
+ ...ifDefined("explicitNodeControlPolicy", table?.control),
1251
+ createsNewObject: resolvePostgresNodeIssueCreationFactoryName(issue) !== void 0
1252
+ };
1253
+ }
1254
+ //#endregion
1255
+ export { planIssues as a, renderPostgresSuppression as c, resolvePostgresNodeIssueControlPolicySubject as d, resolvePostgresNodeIssueCreationFactoryName as f, issueSchemaName as i, resolveNamespaceIdForDdlSchema as l, conflictForDisallowedCall as n, postgresNodeStorageCoordinate as o, issueNode as r, postgresPlannerStrategies as s, coalesceSubtreeIssues as t, resolvePostgresCallControlPolicySubject as u };
1256
+
1257
+ //# sourceMappingURL=control-policy-Cl3RRSPg-CT3QGpR3.mjs.map