@prisma/orm-target-postgres 8.0.0-rc.2-dev.2 → 8.0.0-rc.20

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 (501) hide show
  1. package/README.md +4 -6
  2. package/dist/adapter-5qylEP__.d.mts +403 -0
  3. package/dist/adapter-5qylEP__.d.mts.map +1 -0
  4. package/dist/{adapter-B0xsc80z-sYcF0RVF.mjs → adapter-svGTIjA2-1p-Iw8D2.mjs} +24 -30
  5. package/dist/adapter-svGTIjA2-1p-Iw8D2.mjs.map +1 -0
  6. package/dist/adapter.d.mts +11 -13
  7. package/dist/adapter.mjs +7 -8
  8. package/dist/adapter__adapter.d.mts +2 -2
  9. package/dist/adapter__adapter.mjs +3 -2
  10. package/dist/adapter__column-types.d.mts +2 -2
  11. package/dist/adapter__column-types.mjs +2 -2
  12. package/dist/adapter__control.d.mts +4 -5
  13. package/dist/adapter__control.mjs +11 -423
  14. package/dist/adapter__control.mjs.map +1 -1
  15. package/dist/adapter__runtime.d.mts +1 -1
  16. package/dist/adapter__runtime.mjs +29 -19
  17. package/dist/adapter__runtime.mjs.map +1 -1
  18. package/dist/adapter__sql-renderer.d.mts +1 -1
  19. package/dist/adapter__sql-renderer.mjs +1 -1
  20. package/dist/adapter__types.d.mts +4 -3
  21. package/dist/aggregates-CEqqEg8k.d.mts +318 -0
  22. package/dist/aggregates-CEqqEg8k.d.mts.map +1 -0
  23. package/dist/{aggregates-Dh6HPdvC.mjs → aggregates-Dw-lAutX.mjs} +105 -40
  24. package/dist/aggregates-Dw-lAutX.mjs.map +1 -0
  25. package/dist/authoring-DWd5pnnV-BBX7P1wT.d.mts +52 -0
  26. package/dist/authoring-DWd5pnnV-BBX7P1wT.d.mts.map +1 -0
  27. package/dist/authoring-SbdvmVJh-nQ7YliD_.mjs +1342 -0
  28. package/dist/authoring-SbdvmVJh-nQ7YliD_.mjs.map +1 -0
  29. package/dist/autoincrement-widths-DonNJgfS-CCvZ4u1W.mjs +58 -0
  30. package/dist/autoincrement-widths-DonNJgfS-CCvZ4u1W.mjs.map +1 -0
  31. package/dist/{canonicalize-CQlxSR4D-MnrT5gtW.d.mts → canonicalize-B-xvDOdd-G3yUeKj4.d.mts} +7 -3
  32. package/dist/canonicalize-B-xvDOdd-G3yUeKj4.d.mts.map +1 -0
  33. package/dist/{canonicalize-CrN3u_xM-D4MrOqcB.mjs → canonicalize-RdxoUHao-FTTkizfe.mjs} +15 -3
  34. package/dist/canonicalize-RdxoUHao-FTTkizfe.mjs.map +1 -0
  35. package/dist/check-expressions-7uCCP01t-DtX2Vak9.mjs +48 -0
  36. package/dist/check-expressions-7uCCP01t-DtX2Vak9.mjs.map +1 -0
  37. package/dist/{check-expressions-DRgG8RN5-DiA-22aC.d.mts → check-expressions-CtTzM58x-LloO-5Vf.d.mts} +14 -13
  38. package/dist/check-expressions-CtTzM58x-LloO-5Vf.d.mts.map +1 -0
  39. package/dist/{codec-descriptor-LT7BpQta-BaDM8UQQ.mjs → codec-descriptor-DoR-cTFZ-BlG5Gj-X.mjs} +12 -21
  40. package/dist/codec-descriptor-DoR-cTFZ-BlG5Gj-X.mjs.map +1 -0
  41. package/dist/codec-descriptor-Fb3UoQGb.d.mts +1 -0
  42. package/dist/codec-descriptor-d1ByNBEk-DhrtS_5y.d.mts +47 -0
  43. package/dist/codec-descriptor-d1ByNBEk-DhrtS_5y.d.mts.map +1 -0
  44. package/dist/codec-ids-BMhEpFwv-B8Zh0s_Q.mjs +41 -0
  45. package/dist/codec-ids-BMhEpFwv-B8Zh0s_Q.mjs.map +1 -0
  46. package/dist/codec-ids-C6II64Wy-CPYTqDTT.d.mts +41 -0
  47. package/dist/codec-ids-C6II64Wy-CPYTqDTT.d.mts.map +1 -0
  48. package/dist/codec-ids-CcB5uBNf.d.mts +1 -0
  49. package/dist/codec-registry-D7XslgPe-DTZnVB8W.mjs +61 -0
  50. package/dist/codec-registry-D7XslgPe-DTZnVB8W.mjs.map +1 -0
  51. package/dist/codec-type-map-Fj5xCgwT-BeCXgfuR.d.mts +53 -0
  52. package/dist/codec-type-map-Fj5xCgwT-BeCXgfuR.d.mts.map +1 -0
  53. package/dist/codec-types-BBACckHa.d.mts +2 -0
  54. package/dist/codec-types-Ct_4iTVc-3tFJcIBo.d.mts +84 -0
  55. package/dist/codec-types-Ct_4iTVc-3tFJcIBo.d.mts.map +1 -0
  56. package/dist/codecs-CADK7dCR-C8WToYQb.d.mts +724 -0
  57. package/dist/codecs-CADK7dCR-C8WToYQb.d.mts.map +1 -0
  58. package/dist/codecs-CRl9-i_r-Co-bgYl3.mjs +1743 -0
  59. package/dist/codecs-CRl9-i_r-Co-bgYl3.mjs.map +1 -0
  60. package/dist/codecs-CoEpEqjM.d.mts +31 -0
  61. package/dist/codecs-CoEpEqjM.d.mts.map +1 -0
  62. package/dist/column-types-B4zsV-u3.mjs +106 -0
  63. package/dist/column-types-B4zsV-u3.mjs.map +1 -0
  64. package/dist/column-types-Bs2V0j8T.d.mts +164 -0
  65. package/dist/column-types-Bs2V0j8T.d.mts.map +1 -0
  66. package/dist/{control-adapter-DFr4gS-r-DM3KcZdQ.mjs → contract-contributions-Xz2FpyfI-CeQZqHKf.mjs} +489 -292
  67. package/dist/contract-contributions-Xz2FpyfI-CeQZqHKf.mjs.map +1 -0
  68. package/dist/{contract-free-DzpGxLfb.d.mts → contract-free-B6-wuc6M.d.mts} +36 -6
  69. package/dist/contract-free-B6-wuc6M.d.mts.map +1 -0
  70. package/dist/{contract-free-aQ4nT-_R.mjs → contract-free-o7olebm9.mjs} +13 -9
  71. package/dist/contract-free-o7olebm9.mjs.map +1 -0
  72. package/dist/control--HupSPoV.d.mts +847 -0
  73. package/dist/control--HupSPoV.d.mts.map +1 -0
  74. package/dist/{control-BaUpALVp.d.mts → control-CQEjh4P7.d.mts} +2 -2
  75. package/dist/control-CQEjh4P7.d.mts.map +1 -0
  76. package/dist/{control-DLTOAEHj.d.mts → control-D4cTcpcJ.d.mts} +22 -48
  77. package/dist/control-D4cTcpcJ.d.mts.map +1 -0
  78. package/dist/{control-Y6FxMu3o.mjs → control-DZQwENIP.mjs} +21 -9
  79. package/dist/control-DZQwENIP.mjs.map +1 -0
  80. package/dist/{control-policy-B53lnBCT-B9K9Cj1x.mjs → control-policy-DtU5u9Dm-44r_OF94.mjs} +444 -218
  81. package/dist/control-policy-DtU5u9Dm-44r_OF94.mjs.map +1 -0
  82. package/dist/{data-transform-ChZzy2dP-CxVCat_8.mjs → data-transform-h9agBu_c-RlC5A7aY.mjs} +12 -5
  83. package/dist/data-transform-h9agBu_c-RlC5A7aY.mjs.map +1 -0
  84. package/dist/{data-transform-Ck5FbyNO-BNE7QlAo.d.mts → data-transform-nGy9rz87-CE3DGlgn.d.mts} +15 -4
  85. package/dist/data-transform-nGy9rz87-CE3DGlgn.d.mts.map +1 -0
  86. package/dist/data-transform-nqkqNIb8.d.mts +1 -0
  87. package/dist/data-type-entries-gQW3-KSb-BIl8vgus.mjs +128 -0
  88. package/dist/data-type-entries-gQW3-KSb-BIl8vgus.mjs.map +1 -0
  89. package/dist/data-types--7V9yY1G.d.mts +99 -0
  90. package/dist/data-types--7V9yY1G.d.mts.map +1 -0
  91. package/dist/data-types-Chx0mjTP-DczU4S9b.mjs +950 -0
  92. package/dist/data-types-Chx0mjTP-DczU4S9b.mjs.map +1 -0
  93. package/dist/date-time-now-generators-CMkXVbMG-C-GjhReE.d.mts +45 -0
  94. package/dist/date-time-now-generators-CMkXVbMG-C-GjhReE.d.mts.map +1 -0
  95. package/dist/ddl-B7Rqlz6D-B7dRDgYb.mjs +647 -0
  96. package/dist/ddl-B7Rqlz6D-B7dRDgYb.mjs.map +1 -0
  97. package/dist/ddl-B8nQZTWN.d.mts +1 -0
  98. package/dist/default-constraint-names-Cz9Yoeim-sUzOGvIm.mjs +18 -0
  99. package/dist/default-constraint-names-Cz9Yoeim-sUzOGvIm.mjs.map +1 -0
  100. package/dist/default-normalizer-BqK6XxdC-2OUb2ybG.mjs +311 -0
  101. package/dist/default-normalizer-BqK6XxdC-2OUb2ybG.mjs.map +1 -0
  102. package/dist/default-normalizer-DO-cH75Q.d.mts +25 -0
  103. package/dist/default-normalizer-DO-cH75Q.d.mts.map +1 -0
  104. package/dist/descriptor-meta-BkD3nXF_-CZaNqC6r.mjs +36 -0
  105. package/dist/descriptor-meta-BkD3nXF_-CZaNqC6r.mjs.map +1 -0
  106. package/dist/descriptor-meta-DaFDNnHQ-QjiiAEtC.mjs +64 -0
  107. package/dist/descriptor-meta-DaFDNnHQ-QjiiAEtC.mjs.map +1 -0
  108. package/dist/descriptor-meta-runtime-Dft1L7eE-D8vpOz_Z.mjs +15 -0
  109. package/dist/descriptor-meta-runtime-Dft1L7eE-D8vpOz_Z.mjs.map +1 -0
  110. package/dist/{diff-database-schema-DsoNznGC.d.mts → diff-database-schema-BxzhZaVN.d.mts} +12 -7
  111. package/dist/diff-database-schema-BxzhZaVN.d.mts.map +1 -0
  112. package/dist/{diff-database-schema-DKq76rCk-uehceHYz.mjs → diff-database-schema-DAEzWtzU-DoyVgKqh.mjs} +38 -18
  113. package/dist/diff-database-schema-DAEzWtzU-DoyVgKqh.mjs.map +1 -0
  114. package/dist/driver.d.mts +3 -3
  115. package/dist/driver.mjs +3 -2
  116. package/dist/driver__control.d.mts +1 -1
  117. package/dist/driver__control.mjs +1 -1
  118. package/dist/driver__runtime.d.mts +2 -2
  119. package/dist/driver__runtime.mjs +2 -639
  120. package/dist/errors-BrhQYgdL-IvZHPjwL.mjs +103 -0
  121. package/dist/errors-BrhQYgdL-IvZHPjwL.mjs.map +1 -0
  122. package/dist/{errors-CU4xIwwk.d.mts → errors-D3Mj-x0o.d.mts} +3 -3
  123. package/dist/errors-D3Mj-x0o.d.mts.map +1 -0
  124. package/dist/full-text-BYg7EVX2.mjs +39 -0
  125. package/dist/full-text-BYg7EVX2.mjs.map +1 -0
  126. package/dist/full-text-SDbfxrE_.d.mts +26 -0
  127. package/dist/full-text-SDbfxrE_.d.mts.map +1 -0
  128. package/dist/full-text-collection-method-BFd2u2cs-Ba3OiWM3.d.mts +27 -0
  129. package/dist/full-text-collection-method-BFd2u2cs-Ba3OiWM3.d.mts.map +1 -0
  130. package/dist/full-text-index-authoring-CN1L9C1k.d.mts +7 -0
  131. package/dist/full-text-index-authoring-CN1L9C1k.d.mts.map +1 -0
  132. package/dist/full-text-index-definition-BPxQQBuC-VLyQ1kEL.mjs +195 -0
  133. package/dist/full-text-index-definition-BPxQQBuC-VLyQ1kEL.mjs.map +1 -0
  134. package/dist/full-text-index-definition-D5iBWLss-BEpqiucV.d.mts +71 -0
  135. package/dist/full-text-index-definition-D5iBWLss-BEpqiucV.d.mts.map +1 -0
  136. package/dist/full-text-parsers-CFFxiOrp-CrZ7VI1m.mjs +139 -0
  137. package/dist/full-text-parsers-CFFxiOrp-CrZ7VI1m.mjs.map +1 -0
  138. package/dist/full-text-search-document-Doy5TF7c-aMWM_1KB.mjs +54 -0
  139. package/dist/full-text-search-document-Doy5TF7c-aMWM_1KB.mjs.map +1 -0
  140. package/dist/index-types-BihjrAAq-C2VnfAyF.mjs +14 -0
  141. package/dist/index-types-BihjrAAq-C2VnfAyF.mjs.map +1 -0
  142. package/dist/indexes-BYf6nXVv-BXwLw7fO.d.mts +60 -0
  143. package/dist/indexes-BYf6nXVv-BXwLw7fO.d.mts.map +1 -0
  144. package/dist/infer-psl-contract-BSSHcuRi-ChdFSviw.mjs +1143 -0
  145. package/dist/infer-psl-contract-BSSHcuRi-ChdFSviw.mjs.map +1 -0
  146. package/dist/{issue-planner-Biq9Ls7e.d.mts → issue-planner-D-On52xP.d.mts} +39 -9
  147. package/dist/issue-planner-D-On52xP.d.mts.map +1 -0
  148. package/dist/list-decoder-BcrLExnx-DlCwavhu.d.mts +7 -0
  149. package/dist/list-decoder-BcrLExnx-DlCwavhu.d.mts.map +1 -0
  150. package/dist/marker-lock-BviIbusV.d.mts +11 -0
  151. package/dist/marker-lock-BviIbusV.d.mts.map +1 -0
  152. package/dist/marker-lock-DFc1Tfv5-BkBKBRE3.mjs +11 -0
  153. package/dist/marker-lock-DFc1Tfv5-BkBKBRE3.mjs.map +1 -0
  154. package/dist/{migration-PTHAY9Cv.mjs → migration-Be_iuIpn.mjs} +5 -4
  155. package/dist/migration-Be_iuIpn.mjs.map +1 -0
  156. package/dist/migration-D4lMmLVj.d.mts +26 -0
  157. package/dist/migration-D4lMmLVj.d.mts.map +1 -0
  158. package/dist/{namespace-ids-xtp_ZY86-Cpp8PTxD.mjs → namespace-ids-xtp_ZY86-Cxc0dBbO.mjs} +2 -2
  159. package/dist/namespace-ids-xtp_ZY86-Cxc0dBbO.mjs.map +1 -0
  160. package/dist/native-type-normalizer-BaGa9eeb.d.mts +30 -0
  161. package/dist/native-type-normalizer-BaGa9eeb.d.mts.map +1 -0
  162. package/dist/native-type-normalizer-Cn-RGt_E.mjs +24 -0
  163. package/dist/native-type-normalizer-Cn-RGt_E.mjs.map +1 -0
  164. package/dist/{nodes-DAvDJLvJ-BBdvFXNa.mjs → nodes-G8VTh4PM-DNvIhHag.mjs} +78 -7
  165. package/dist/nodes-G8VTh4PM-DNvIhHag.mjs.map +1 -0
  166. package/dist/{nodes-BU-V-aZA-RqwPH68u.d.mts → nodes-s0Oe37jT-Cw3BU2gL.d.mts} +82 -29
  167. package/dist/nodes-s0Oe37jT-Cw3BU2gL.d.mts.map +1 -0
  168. package/dist/op-factory-call-CRaVUOb_.d.mts +1 -0
  169. package/dist/{op-factory-call-H6zeDGLe-_1pAftJk.mjs → op-factory-call-gGX-mZu--0QUG5xH4.mjs} +1014 -258
  170. package/dist/op-factory-call-gGX-mZu--0QUG5xH4.mjs.map +1 -0
  171. package/dist/{op-factory-call-BAeyLFYf-BAgG1h1C.d.mts → op-factory-call-nLHvNx0O-BTBhGbOF.d.mts} +169 -111
  172. package/dist/op-factory-call-nLHvNx0O-BTBhGbOF.d.mts.map +1 -0
  173. package/dist/operation-types--Wa_cv45-RoRnL1Dn.d.mts +192 -0
  174. package/dist/operation-types--Wa_cv45-RoRnL1Dn.d.mts.map +1 -0
  175. package/dist/operation-types-OXILTAOX.d.mts +1 -0
  176. package/dist/pack-2CYw2w-b.d.mts +1573 -0
  177. package/dist/pack-2CYw2w-b.d.mts.map +1 -0
  178. package/dist/{planner-CT-7zSfk.d.mts → planner-AD3Dt57t.d.mts} +23 -51
  179. package/dist/planner-AD3Dt57t.d.mts.map +1 -0
  180. package/dist/planner-VuR6URu3-CCUT2Osx.mjs +954 -0
  181. package/dist/planner-VuR6URu3-CCUT2Osx.mjs.map +1 -0
  182. package/dist/planner-ddl-builders-CPM3y7cQ.d.mts +16 -0
  183. package/dist/planner-ddl-builders-CPM3y7cQ.d.mts.map +1 -0
  184. package/dist/planner-ddl-builders-cYnH52gC-BWifb_M6.mjs +28 -0
  185. package/dist/planner-ddl-builders-cYnH52gC-BWifb_M6.mjs.map +1 -0
  186. package/dist/planner-identity-values-Dsq989Lh.d.mts +26 -0
  187. package/dist/planner-identity-values-Dsq989Lh.d.mts.map +1 -0
  188. package/dist/planner-identity-values-QstrMJ2U-CcpaRVPY.mjs +70 -0
  189. package/dist/planner-identity-values-QstrMJ2U-CcpaRVPY.mjs.map +1 -0
  190. package/dist/planner-produced-postgres-migration-BBUwtjA_.d.mts +1 -0
  191. package/dist/{planner-produced-postgres-migration-D5m8nK6s-CbZ4hlbv.mjs → planner-produced-postgres-migration-BZclL_xO-uflxtYuP.mjs} +5 -5
  192. package/dist/planner-produced-postgres-migration-BZclL_xO-uflxtYuP.mjs.map +1 -0
  193. package/dist/{planner-produced-postgres-migration-BaviT8KK-Yo9kw6rs.d.mts → planner-produced-postgres-migration-DyIXJ3MR-DHO5wn_X.d.mts} +4 -4
  194. package/dist/planner-produced-postgres-migration-DyIXJ3MR-DHO5wn_X.d.mts.map +1 -0
  195. package/dist/{planner-schema-lookup-kMIVP2y--CdO4VlnF.mjs → planner-schema-lookup-BbUY9oVy.mjs} +2 -2
  196. package/dist/planner-schema-lookup-BbUY9oVy.mjs.map +1 -0
  197. package/dist/{planner-schema-lookup-C4DHAddq.d.mts → planner-schema-lookup-ceCNOGFf.d.mts} +2 -2
  198. package/dist/planner-schema-lookup-ceCNOGFf.d.mts.map +1 -0
  199. package/dist/planner-sql-checks-D-K44J19-CzvrqzNB.mjs +151 -0
  200. package/dist/planner-sql-checks-D-K44J19-CzvrqzNB.mjs.map +1 -0
  201. package/dist/planner-sql-checks-Ed-WGtge-D9ByMrW4.d.mts +37 -0
  202. package/dist/planner-sql-checks-Ed-WGtge-D9ByMrW4.d.mts.map +1 -0
  203. package/dist/planner-sql-checks-rEjFx_Jv.d.mts +1 -0
  204. package/dist/planner-target-details-CUEF0s90-6g-mOgTI.mjs +14 -0
  205. package/dist/planner-target-details-CUEF0s90-6g-mOgTI.mjs.map +1 -0
  206. package/dist/{planner-target-details-HkP4RrRO-_xPQVPF0.d.mts → planner-target-details-HkP4RrRO-D6VtK0jY.d.mts} +2 -2
  207. package/dist/planner-target-details-HkP4RrRO-D6VtK0jY.d.mts.map +1 -0
  208. package/dist/postgres-codec-traits-CnP5Bjxp-Dxdgv0TI.mjs +11 -0
  209. package/dist/postgres-codec-traits-CnP5Bjxp-Dxdgv0TI.mjs.map +1 -0
  210. package/dist/{postgres-contract-view-2OP5JnXl-D2fpy4-8.d.mts → postgres-contract-view-BFzIDwwN-hL3QLe_b.d.mts} +2 -2
  211. package/dist/postgres-contract-view-BFzIDwwN-hL3QLe_b.d.mts.map +1 -0
  212. package/dist/{postgres-contract-view-B8ykf2cO-T2LvWVFZ.mjs → postgres-contract-view-BO2elRMz-BqMBzJoJ.mjs} +27 -14
  213. package/dist/postgres-contract-view-BO2elRMz-BqMBzJoJ.mjs.map +1 -0
  214. package/dist/{postgres-database-schema-node-CyfpHXDr-BqyozkQE.d.mts → postgres-database-schema-node-Cv8usVNX-BmvGozi4.d.mts} +4 -4
  215. package/dist/postgres-database-schema-node-Cv8usVNX-BmvGozi4.d.mts.map +1 -0
  216. package/dist/postgres-migration-BSWmeRLo-CUfVTUf0.mjs +1312 -0
  217. package/dist/postgres-migration-BSWmeRLo-CUfVTUf0.mjs.map +1 -0
  218. package/dist/{postgres-migration-BNsrwlxh-CwI5BqAu.d.mts → postgres-migration-C5deJ3Ne-C4Jxu-e6.d.mts} +135 -15
  219. package/dist/postgres-migration-C5deJ3Ne-C4Jxu-e6.d.mts.map +1 -0
  220. package/dist/{postgres-native-enum-CdP3b_-R-Cgz9KEKx.mjs → postgres-native-enum-CdP3b_-R-DgG3pi5p.mjs} +2 -2
  221. package/dist/postgres-native-enum-CdP3b_-R-DgG3pi5p.mjs.map +1 -0
  222. package/dist/postgres-object-name-FPikIvOw-B8FfJI7z.mjs +23 -0
  223. package/dist/postgres-object-name-FPikIvOw-B8FfJI7z.mjs.map +1 -0
  224. package/dist/{postgres-rls-policy-CnDxf3z9-C3LIHAIG.d.mts → postgres-rls-policy-CnDxf3z9-BjpVyUnK.d.mts} +2 -2
  225. package/dist/postgres-rls-policy-CnDxf3z9-BjpVyUnK.d.mts.map +1 -0
  226. package/dist/{postgres-role-schema-node-B8Z5i5D--PObwlU2Z.mjs → postgres-role-schema-node-B8Z5i5D--BzOKm4N1.mjs} +3 -3
  227. package/dist/postgres-role-schema-node-B8Z5i5D--BzOKm4N1.mjs.map +1 -0
  228. package/dist/{postgres-schema-CF0yHESb-D7n2X21R.mjs → postgres-schema-C6w1rzOF-D1fdwqRx.mjs} +14 -12
  229. package/dist/postgres-schema-C6w1rzOF-D1fdwqRx.mjs.map +1 -0
  230. package/dist/{postgres-schema-Xsjt3RKO-Buv2X8ai.d.mts → postgres-schema-Xsjt3RKO-bis-SVSB.d.mts} +4 -4
  231. package/dist/postgres-schema-Xsjt3RKO-bis-SVSB.d.mts.map +1 -0
  232. package/dist/{postgres-table-schema-node-BBkitBQh-DT1T5VWU.mjs → postgres-table-schema-node-BBkitBQh-Dll8iaZT.mjs} +2 -2
  233. package/dist/postgres-table-schema-node-BBkitBQh-Dll8iaZT.mjs.map +1 -0
  234. package/dist/prisma7-binding-BjiLA9F7.mjs +307 -0
  235. package/dist/prisma7-binding-BjiLA9F7.mjs.map +1 -0
  236. package/dist/prisma7-binding-a56klfkc.d.mts +1651 -0
  237. package/dist/prisma7-binding-a56klfkc.d.mts.map +1 -0
  238. package/dist/{render-ops-DOsRP0Po-BKn_c_Ia.mjs → render-ops-BgqtCw9Z-T8BPTX85.mjs} +17 -10
  239. package/dist/render-ops-BgqtCw9Z-T8BPTX85.mjs.map +1 -0
  240. package/dist/{render-ops-DPwhZt2W.d.mts → render-ops-Bl84i7ut.d.mts} +3 -3
  241. package/dist/render-ops-Bl84i7ut.d.mts.map +1 -0
  242. package/dist/{render-typescript-6sCFvMBh.d.mts → render-typescript-BysdXYpH.d.mts} +2 -2
  243. package/dist/render-typescript-BysdXYpH.d.mts.map +1 -0
  244. package/dist/{render-typescript-Dqp1Spgn-B128r1qw.mjs → render-typescript-Dqp1Spgn-B4mJhuVr.mjs} +2 -2
  245. package/dist/render-typescript-Dqp1Spgn-B4mJhuVr.mjs.map +1 -0
  246. package/dist/resolve-ddl-schema-D3VNPMSm-BuB6NyOI.mjs +34 -0
  247. package/dist/resolve-ddl-schema-D3VNPMSm-BuB6NyOI.mjs.map +1 -0
  248. package/dist/{runtime-lHBKgjB9.d.mts → runtime-C0VXuM0b.d.mts} +4 -3
  249. package/dist/runtime-C0VXuM0b.d.mts.map +1 -0
  250. package/dist/runtime-CXfxy5ED.mjs +660 -0
  251. package/dist/runtime-CXfxy5ED.mjs.map +1 -0
  252. package/dist/{runtime-_TfO66h5.d.mts → runtime-Ci_toEDZ.d.mts} +12 -4
  253. package/dist/runtime-Ci_toEDZ.d.mts.map +1 -0
  254. package/dist/{runtime-DOXznQe0.d.mts → runtime-DtjW0GP_.d.mts} +4 -4
  255. package/dist/runtime-DtjW0GP_.d.mts.map +1 -0
  256. package/dist/{schema-ir-annotations-DuuYh0gl.d.mts → schema-ir-annotations-BygaWBiC.d.mts} +2 -2
  257. package/dist/schema-ir-annotations-BygaWBiC.d.mts.map +1 -0
  258. package/dist/{schema-node-kinds-qlnURWJy-Bo30pwTM.d.mts → schema-node-kinds-C52Bb1ve-DmxQRPPS.d.mts} +2 -2
  259. package/dist/schema-node-kinds-C52Bb1ve-DmxQRPPS.d.mts.map +1 -0
  260. package/dist/{normalize-error-CNjgVO71-CLlZ3CuJ.mjs → server-text-types-DeNPQpv5-DqX0h8WF.mjs} +45 -3
  261. package/dist/server-text-types-DeNPQpv5-DqX0h8WF.mjs.map +1 -0
  262. package/dist/{sql-renderer-ComgusFq-BBlqM1fw.mjs → sql-renderer-BdWJPa5F-Ct0CPlXc.mjs} +113 -123
  263. package/dist/sql-renderer-BdWJPa5F-Ct0CPlXc.mjs.map +1 -0
  264. package/dist/{sql-renderer-BgC0ZgLS.d.mts → sql-renderer-BiBhge7D.d.mts} +9 -7
  265. package/dist/sql-renderer-BiBhge7D.d.mts.map +1 -0
  266. package/dist/{sql-utils-DuzN3JZg-DiXy4Vah.mjs → sql-utils-Bnw3JbWf-BN0gcjZB.mjs} +31 -8
  267. package/dist/sql-utils-Bnw3JbWf-BN0gcjZB.mjs.map +1 -0
  268. package/dist/{sql-utils-DW6fkczF.d.mts → sql-utils-CnnGiZBc.d.mts} +12 -4
  269. package/dist/sql-utils-CnnGiZBc.d.mts.map +1 -0
  270. package/dist/{table-source-ikHOZmhD-DriY1Lcr.d.mts → table-source-ikHOZmhD-vYcblBYv.d.mts} +2 -2
  271. package/dist/table-source-ikHOZmhD-vYcblBYv.d.mts.map +1 -0
  272. package/dist/target.d.mts +61 -49
  273. package/dist/target.mjs +45 -36
  274. package/dist/target__aggregates.d.mts +1 -1
  275. package/dist/target__aggregates.mjs +1 -1
  276. package/dist/target__codec-descriptor.d.mts +2 -2
  277. package/dist/target__codec-descriptor.mjs +1 -1
  278. package/dist/target__codec-ids.d.mts +3 -3
  279. package/dist/target__codec-ids.mjs +2 -2
  280. package/dist/target__codec-types.d.mts +4 -4
  281. package/dist/target__codecs.d.mts +4 -3
  282. package/dist/target__codecs.mjs +3 -3
  283. package/dist/target__contract-free.d.mts +3 -3
  284. package/dist/target__contract-free.mjs +4 -4
  285. package/dist/target__control.d.mts +4 -2
  286. package/dist/target__control.mjs +2501 -2
  287. package/dist/target__control.mjs.map +1 -0
  288. package/dist/target__data-transform.d.mts +2 -2
  289. package/dist/target__data-transform.mjs +1 -1
  290. package/dist/target__data-types.d.mts +2 -0
  291. package/dist/target__data-types.mjs +3 -0
  292. package/dist/target__ddl.d.mts +4 -4
  293. package/dist/target__ddl.mjs +2 -2
  294. package/dist/target__default-normalizer.d.mts +2 -2
  295. package/dist/target__default-normalizer.mjs +2 -2
  296. package/dist/target__diff-database-schema.d.mts +1 -1
  297. package/dist/target__diff-database-schema.mjs +1 -1
  298. package/dist/target__errors.d.mts +1 -1
  299. package/dist/target__errors.mjs +1 -1
  300. package/dist/target__full-text-index-authoring.d.mts +3 -0
  301. package/dist/target__full-text-index-authoring.mjs +3 -0
  302. package/dist/target__full-text.d.mts +4 -0
  303. package/dist/target__full-text.mjs +3 -0
  304. package/dist/target__issue-planner.d.mts +1 -1
  305. package/dist/target__issue-planner.mjs +1 -1
  306. package/dist/target__marker-lock.d.mts +2 -0
  307. package/dist/target__marker-lock.mjs +2 -0
  308. package/dist/target__migration.d.mts +4 -4
  309. package/dist/target__migration.mjs +5 -5
  310. package/dist/target__native-type-normalizer.d.mts +2 -2
  311. package/dist/target__native-type-normalizer.mjs +2 -2
  312. package/dist/target__op-factory-call.d.mts +3 -3
  313. package/dist/target__op-factory-call.mjs +2 -2
  314. package/dist/target__operation-types.d.mts +4 -0
  315. package/dist/target__pack.d.mts +3 -2
  316. package/dist/target__pack.mjs +1 -1
  317. package/dist/target__planner-ddl-builders.d.mts +2 -2
  318. package/dist/target__planner-ddl-builders.mjs +2 -2
  319. package/dist/target__planner-identity-values.d.mts +1 -1
  320. package/dist/target__planner-identity-values.mjs +1 -1
  321. package/dist/target__planner-produced-postgres-migration.d.mts +2 -2
  322. package/dist/target__planner-produced-postgres-migration.mjs +1 -1
  323. package/dist/target__planner-schema-lookup.d.mts +1 -1
  324. package/dist/target__planner-schema-lookup.mjs +1 -1
  325. package/dist/target__planner-sql-checks.d.mts +3 -2
  326. package/dist/target__planner-sql-checks.mjs +2 -2
  327. package/dist/target__planner-target-details.d.mts +1 -1
  328. package/dist/target__planner.d.mts +1 -1
  329. package/dist/target__planner.mjs +2 -2
  330. package/dist/target__prisma7-binding.d.mts +2 -0
  331. package/dist/target__prisma7-binding.mjs +2 -0
  332. package/dist/target__render-ops.d.mts +1 -1
  333. package/dist/target__render-ops.mjs +1 -1
  334. package/dist/target__render-typescript.d.mts +1 -1
  335. package/dist/target__render-typescript.mjs +1 -1
  336. package/dist/target__rls-canonicalize.d.mts +2 -2
  337. package/dist/target__rls-canonicalize.mjs +2 -2
  338. package/dist/target__runtime.d.mts +6 -3
  339. package/dist/target__runtime.mjs +193 -4
  340. package/dist/target__runtime.mjs.map +1 -1
  341. package/dist/target__schema-ir-annotations.d.mts +1 -1
  342. package/dist/target__schema-ir-annotations.mjs +1 -1
  343. package/dist/target__sql-utils.d.mts +3 -2
  344. package/dist/target__sql-utils.mjs +4 -2
  345. package/dist/target__types.d.mts +7 -7
  346. package/dist/target__types.mjs +5 -5
  347. package/dist/types-AvjnIUna.d.mts +2 -0
  348. package/dist/types-D6lgKhE5-D1J9YJnd.d.mts +28 -0
  349. package/dist/types-D6lgKhE5-D1J9YJnd.d.mts.map +1 -0
  350. package/dist/{types-CjGjPLr5.d.mts → types-DOmgp_12.d.mts} +8 -8
  351. package/dist/types-DOmgp_12.d.mts.map +1 -0
  352. package/dist/{types-ue6jkJyF-BQJzjx1P.d.mts → types-ue6jkJyF-D79DmBTl.d.mts} +2 -2
  353. package/dist/types-ue6jkJyF-D79DmBTl.d.mts.map +1 -0
  354. package/package.json +22 -14
  355. package/dist/adapter-B0xsc80z-sYcF0RVF.mjs.map +0 -1
  356. package/dist/adapter-CPesdzv0.d.mts +0 -26
  357. package/dist/adapter-CPesdzv0.d.mts.map +0 -1
  358. package/dist/adapter__operation-types.d.mts +0 -2
  359. package/dist/aggregates-CgqNfj2O.d.mts +0 -10
  360. package/dist/aggregates-CgqNfj2O.d.mts.map +0 -1
  361. package/dist/aggregates-Dh6HPdvC.mjs.map +0 -1
  362. package/dist/authoring-BOpdZa2N-ClrLFiXw.mjs +0 -773
  363. package/dist/authoring-BOpdZa2N-ClrLFiXw.mjs.map +0 -1
  364. package/dist/canonicalize-CQlxSR4D-MnrT5gtW.d.mts.map +0 -1
  365. package/dist/canonicalize-CrN3u_xM-D4MrOqcB.mjs.map +0 -1
  366. package/dist/check-expressions-5vhxWaFy-CBcjFeur.mjs +0 -41
  367. package/dist/check-expressions-5vhxWaFy-CBcjFeur.mjs.map +0 -1
  368. package/dist/check-expressions-DRgG8RN5-DiA-22aC.d.mts.map +0 -1
  369. package/dist/codec-descriptor-Bec_zukr-BfvtUqhm.d.mts +0 -37
  370. package/dist/codec-descriptor-Bec_zukr-BfvtUqhm.d.mts.map +0 -1
  371. package/dist/codec-descriptor-Bg-_412t.d.mts +0 -1
  372. package/dist/codec-descriptor-LT7BpQta-BaDM8UQQ.mjs.map +0 -1
  373. package/dist/codec-ids-Bqu_IwO0-DKOdPizQ.d.mts +0 -35
  374. package/dist/codec-ids-Bqu_IwO0-DKOdPizQ.d.mts.map +0 -1
  375. package/dist/codec-ids-C5Rkltkw-DMf87l9s.mjs +0 -35
  376. package/dist/codec-ids-C5Rkltkw-DMf87l9s.mjs.map +0 -1
  377. package/dist/codec-ids-DJ6j6pZc.d.mts +0 -1
  378. package/dist/codec-types-BRU4F-7t-BaJbKF_i.d.mts +0 -84
  379. package/dist/codec-types-BRU4F-7t-BaJbKF_i.d.mts.map +0 -1
  380. package/dist/codec-types-bX63JRLf.d.mts +0 -2
  381. package/dist/codecs-B1HgsJZ2.mjs +0 -15
  382. package/dist/codecs-B1HgsJZ2.mjs.map +0 -1
  383. package/dist/codecs-BmPCJWqb-DveZGJvm.mjs +0 -1680
  384. package/dist/codecs-BmPCJWqb-DveZGJvm.mjs.map +0 -1
  385. package/dist/codecs-D8tLswBi-_nbo-Z8x.d.mts +0 -638
  386. package/dist/codecs-D8tLswBi-_nbo-Z8x.d.mts.map +0 -1
  387. package/dist/codecs-DmCKO7dg.d.mts +0 -15
  388. package/dist/codecs-DmCKO7dg.d.mts.map +0 -1
  389. package/dist/column-types-BH-MU6uU.d.mts +0 -108
  390. package/dist/column-types-BH-MU6uU.d.mts.map +0 -1
  391. package/dist/column-types-Bh92dNjD.mjs +0 -126
  392. package/dist/column-types-Bh92dNjD.mjs.map +0 -1
  393. package/dist/contract-free-DzpGxLfb.d.mts.map +0 -1
  394. package/dist/contract-free-aQ4nT-_R.mjs.map +0 -1
  395. package/dist/control-2F195jJk.d.mts +0 -11
  396. package/dist/control-2F195jJk.d.mts.map +0 -1
  397. package/dist/control-BaUpALVp.d.mts.map +0 -1
  398. package/dist/control-DLTOAEHj.d.mts.map +0 -1
  399. package/dist/control-V7OkAC55.mjs +0 -1459
  400. package/dist/control-V7OkAC55.mjs.map +0 -1
  401. package/dist/control-Y6FxMu3o.mjs.map +0 -1
  402. package/dist/control-adapter-DFr4gS-r-DM3KcZdQ.mjs.map +0 -1
  403. package/dist/control-policy-B53lnBCT-B9K9Cj1x.mjs.map +0 -1
  404. package/dist/data-transform-BSM7TQpE.d.mts +0 -1
  405. package/dist/data-transform-ChZzy2dP-CxVCat_8.mjs.map +0 -1
  406. package/dist/data-transform-Ck5FbyNO-BNE7QlAo.d.mts.map +0 -1
  407. package/dist/ddl-B4Rh8ntj.d.mts +0 -1
  408. package/dist/ddl-CNQJds-C-WfZ3y4y8.mjs +0 -395
  409. package/dist/ddl-CNQJds-C-WfZ3y4y8.mjs.map +0 -1
  410. package/dist/default-normalizer-B36TOul4.d.mts +0 -31
  411. package/dist/default-normalizer-B36TOul4.d.mts.map +0 -1
  412. package/dist/default-normalizer-Ba5ZebHM-isV86rjy.mjs +0 -253
  413. package/dist/default-normalizer-Ba5ZebHM-isV86rjy.mjs.map +0 -1
  414. package/dist/descriptor-meta-KVX21fsl-DBDoB4eg.mjs +0 -354
  415. package/dist/descriptor-meta-KVX21fsl-DBDoB4eg.mjs.map +0 -1
  416. package/dist/descriptor-meta-rilAH3ep-dAmiVLpe.mjs +0 -30
  417. package/dist/descriptor-meta-rilAH3ep-dAmiVLpe.mjs.map +0 -1
  418. package/dist/descriptor-meta-runtime-UwYdV8fD-B_m_Ha8r.mjs +0 -13
  419. package/dist/descriptor-meta-runtime-UwYdV8fD-B_m_Ha8r.mjs.map +0 -1
  420. package/dist/diff-database-schema-DKq76rCk-uehceHYz.mjs.map +0 -1
  421. package/dist/diff-database-schema-DsoNznGC.d.mts.map +0 -1
  422. package/dist/driver__runtime.mjs.map +0 -1
  423. package/dist/errors-CU4xIwwk.d.mts.map +0 -1
  424. package/dist/errors-DKjQzNaN-DFcF1thx.mjs +0 -39
  425. package/dist/errors-DKjQzNaN-DFcF1thx.mjs.map +0 -1
  426. package/dist/issue-planner-Biq9Ls7e.d.mts.map +0 -1
  427. package/dist/migration-PTHAY9Cv.mjs.map +0 -1
  428. package/dist/migration-aFeTWTOJ.d.mts +0 -25
  429. package/dist/migration-aFeTWTOJ.d.mts.map +0 -1
  430. package/dist/namespace-ids-xtp_ZY86-Cpp8PTxD.mjs.map +0 -1
  431. package/dist/native-type-normalizer-DqJlOTeX.d.mts +0 -19
  432. package/dist/native-type-normalizer-DqJlOTeX.d.mts.map +0 -1
  433. package/dist/native-type-normalizer-yvd3tqv-.mjs +0 -38
  434. package/dist/native-type-normalizer-yvd3tqv-.mjs.map +0 -1
  435. package/dist/nodes-BU-V-aZA-RqwPH68u.d.mts.map +0 -1
  436. package/dist/nodes-DAvDJLvJ-BBdvFXNa.mjs.map +0 -1
  437. package/dist/normalize-error-CNjgVO71-CLlZ3CuJ.mjs.map +0 -1
  438. package/dist/op-factory-call-BAeyLFYf-BAgG1h1C.d.mts.map +0 -1
  439. package/dist/op-factory-call-BTU8I_x0.d.mts +0 -1
  440. package/dist/op-factory-call-H6zeDGLe-_1pAftJk.mjs.map +0 -1
  441. package/dist/operation-types-BfRocNI8.d.mts +0 -22
  442. package/dist/operation-types-BfRocNI8.d.mts.map +0 -1
  443. package/dist/pack-CySS3DQU.d.mts +0 -626
  444. package/dist/pack-CySS3DQU.d.mts.map +0 -1
  445. package/dist/planner-CT-7zSfk.d.mts.map +0 -1
  446. package/dist/planner-D0uogzvT-1WyGIC5p.mjs +0 -671
  447. package/dist/planner-D0uogzvT-1WyGIC5p.mjs.map +0 -1
  448. package/dist/planner-ddl-builders-Chxh-LEQ-DXvwOeeA.mjs +0 -102
  449. package/dist/planner-ddl-builders-Chxh-LEQ-DXvwOeeA.mjs.map +0 -1
  450. package/dist/planner-ddl-builders-ijp60-JO.d.mts +0 -19
  451. package/dist/planner-ddl-builders-ijp60-JO.d.mts.map +0 -1
  452. package/dist/planner-identity-values-BmHn5C6U-BYBbUAyR.mjs +0 -90
  453. package/dist/planner-identity-values-BmHn5C6U-BYBbUAyR.mjs.map +0 -1
  454. package/dist/planner-identity-values-TfEhnoWa.d.mts +0 -25
  455. package/dist/planner-identity-values-TfEhnoWa.d.mts.map +0 -1
  456. package/dist/planner-produced-postgres-migration-BaviT8KK-Yo9kw6rs.d.mts.map +0 -1
  457. package/dist/planner-produced-postgres-migration-D5m8nK6s-CbZ4hlbv.mjs.map +0 -1
  458. package/dist/planner-produced-postgres-migration-D6C0T2xV.d.mts +0 -1
  459. package/dist/planner-schema-lookup-C4DHAddq.d.mts.map +0 -1
  460. package/dist/planner-schema-lookup-kMIVP2y--CdO4VlnF.mjs.map +0 -1
  461. package/dist/planner-sql-checks-CFgbRTJw.d.mts +0 -20
  462. package/dist/planner-sql-checks-CFgbRTJw.d.mts.map +0 -1
  463. package/dist/planner-sql-checks-ftgzvIO9-BTtBg2Vz.mjs +0 -152
  464. package/dist/planner-sql-checks-ftgzvIO9-BTtBg2Vz.mjs.map +0 -1
  465. package/dist/planner-target-details-HkP4RrRO-_xPQVPF0.d.mts.map +0 -1
  466. package/dist/planner-type-resolution-Bt2f_q-F-C4T6YTae.mjs +0 -15
  467. package/dist/planner-type-resolution-Bt2f_q-F-C4T6YTae.mjs.map +0 -1
  468. package/dist/postgres-contract-view-2OP5JnXl-D2fpy4-8.d.mts.map +0 -1
  469. package/dist/postgres-contract-view-B8ykf2cO-T2LvWVFZ.mjs.map +0 -1
  470. package/dist/postgres-database-schema-node-CyfpHXDr-BqyozkQE.d.mts.map +0 -1
  471. package/dist/postgres-migration-BNsrwlxh-CwI5BqAu.d.mts.map +0 -1
  472. package/dist/postgres-migration-Dbq3RGfZ-aMnwfEAb.mjs +0 -205
  473. package/dist/postgres-migration-Dbq3RGfZ-aMnwfEAb.mjs.map +0 -1
  474. package/dist/postgres-native-enum-CdP3b_-R-Cgz9KEKx.mjs.map +0 -1
  475. package/dist/postgres-rls-policy-CnDxf3z9-C3LIHAIG.d.mts.map +0 -1
  476. package/dist/postgres-role-schema-node-B8Z5i5D--PObwlU2Z.mjs.map +0 -1
  477. package/dist/postgres-schema-CF0yHESb-D7n2X21R.mjs.map +0 -1
  478. package/dist/postgres-schema-Xsjt3RKO-Buv2X8ai.d.mts.map +0 -1
  479. package/dist/postgres-table-schema-node-BBkitBQh-DT1T5VWU.mjs.map +0 -1
  480. package/dist/render-ops-DOsRP0Po-BKn_c_Ia.mjs.map +0 -1
  481. package/dist/render-ops-DPwhZt2W.d.mts.map +0 -1
  482. package/dist/render-typescript-6sCFvMBh.d.mts.map +0 -1
  483. package/dist/render-typescript-Dqp1Spgn-B128r1qw.mjs.map +0 -1
  484. package/dist/resolve-ddl-schema-CoaeNP35-C-UZldpj.mjs +0 -22
  485. package/dist/resolve-ddl-schema-CoaeNP35-C-UZldpj.mjs.map +0 -1
  486. package/dist/runtime-DOXznQe0.d.mts.map +0 -1
  487. package/dist/runtime-_TfO66h5.d.mts.map +0 -1
  488. package/dist/runtime-lHBKgjB9.d.mts.map +0 -1
  489. package/dist/schema-ir-annotations-DuuYh0gl.d.mts.map +0 -1
  490. package/dist/schema-node-kinds-qlnURWJy-Bo30pwTM.d.mts.map +0 -1
  491. package/dist/sql-renderer-BgC0ZgLS.d.mts.map +0 -1
  492. package/dist/sql-renderer-ComgusFq-BBlqM1fw.mjs.map +0 -1
  493. package/dist/sql-utils-DW6fkczF.d.mts.map +0 -1
  494. package/dist/sql-utils-DuzN3JZg-DiXy4Vah.mjs.map +0 -1
  495. package/dist/table-source-ikHOZmhD-DriY1Lcr.d.mts.map +0 -1
  496. package/dist/types-B-4d5_4a.d.mts +0 -1
  497. package/dist/types-CjGjPLr5.d.mts.map +0 -1
  498. package/dist/types-CkryN1AS-BcQRGsDn.d.mts +0 -27
  499. package/dist/types-CkryN1AS-BcQRGsDn.d.mts.map +0 -1
  500. package/dist/types-ue6jkJyF-BQJzjx1P.d.mts.map +0 -1
  501. /package/dist/{adapter__operation-types.mjs → target__operation-types.mjs} +0 -0
@@ -1,2 +1,2501 @@
1
- import { n as postgresTargetDescriptor, t as postgresRenderDefault } from "./control-V7OkAC55.mjs";
2
- export { postgresTargetDescriptor as default, postgresRenderDefault };
1
+ import { S as PG_TEXT_CODEC_ID, s as PG_ENUM_CODEC_ID } from "./codec-ids-BMhEpFwv-B8Zh0s_Q.mjs";
2
+ import { c as postgresError } from "./errors-BrhQYgdL-IvZHPjwL.mjs";
3
+ import { i as quoteIdentifier } from "./sql-utils-Bnw3JbWf-BN0gcjZB.mjs";
4
+ import { t as DEFAULT_NAMESPACE_ID } from "./namespace-ids-xtp_ZY86-Cxc0dBbO.mjs";
5
+ import { t as PostgresNativeEnum } from "./postgres-native-enum-CdP3b_-R-DgG3pi5p.mjs";
6
+ import { P as setFallbackTemporal, i as decodePostgresListText, o as parsePostgresListText } from "./codecs-CRl9-i_r-Co-bgYl3.mjs";
7
+ import { s as fullTextIndexDefinitionOf } from "./full-text-index-definition-BPxQQBuC-VLyQ1kEL.mjs";
8
+ import { i as PostgresRlsPolicy, n as PostgresRlsEnablement, o as PostgresRole } from "./postgres-schema-C6w1rzOF-D1fdwqRx.mjs";
9
+ import { r as computeContentHash } from "./canonicalize-RdxoUHao-FTTkizfe.mjs";
10
+ import { c as postgresNativeAuthoringTypes, f as postgresScalarAndNativeTypeConstructors, l as postgresNowGeneratorControlDescriptors, p as postgresScalarAuthoringTypes, t as POLICY_BLOCK_KEYWORDS } from "./authoring-SbdvmVJh-nQ7YliD_.mjs";
11
+ import { t as postgresRenderCheckExpressions } from "./check-expressions-7uCCP01t-DtX2Vak9.mjs";
12
+ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-DaFDNnHQ-QjiiAEtC.mjs";
13
+ import { a as postgresDiffSubjectGranularity, i as postgresDiffSubjectEntityKind } from "./postgres-table-schema-node-BBkitBQh-Dll8iaZT.mjs";
14
+ import { t as PostgresDatabaseSchemaNode } from "./postgres-role-schema-node-B8Z5i5D--BzOKm4N1.mjs";
15
+ import { i as qualifyTableName } from "./planner-sql-checks-D-K44J19-CzvrqzNB.mjs";
16
+ import { I as SCHEMA_OBJECTS_SQL, J as schemaContentsOf, Y as schemaObjectsSummary, q as schemaBlockingObjects } from "./op-factory-call-gGX-mZu--0QUG5xH4.mjs";
17
+ import { r as diffPostgresSchema } from "./diff-database-schema-DAEzWtzU-DoyVgKqh.mjs";
18
+ import { t as PostgresContractSerializer } from "./postgres-contract-view-BO2elRMz-BqMBzJoJ.mjs";
19
+ import { o as postgresContractToSchema } from "./postgres-migration-BSWmeRLo-CUfVTUf0.mjs";
20
+ import { t as createPostgresMigrationPlanner } from "./planner-VuR6URu3-CCUT2Osx.mjs";
21
+ import { n as MARKER_LOCK_SQL, t as MARKER_LOCK_KEY } from "./marker-lock-DFc1Tfv5-BkBKBRE3.mjs";
22
+ import { a as buildIndexAttribute, c as buildNativeEnumBlock, d as inferPostgresPslContract, f as namedArg, g as positionalArg, h as parseDefaultAttributeString, i as buildFullTextIndexAttribute, n as buildAttribute, o as buildMapAttribute, r as buildCheckAttribute, s as buildModelConstraintAttribute, t as SYNTHETIC_SPAN } from "./infer-psl-contract-BSSHcuRi-ChdFSviw.mjs";
23
+ import { dataTypeParams, requiredParamKeys, validateCodecTypeParams } from "@prisma/orm-framework/components/codec";
24
+ import { blindCast } from "@prisma/orm-framework/utils/casts";
25
+ import { InternalError } from "@prisma/orm-framework/utils/internal-error";
26
+ import { isSqlDataType, sqlCodecColumnLength, unquotedSqlBaseName } from "@prisma/orm-family-sql/contract/data-type";
27
+ import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
28
+ import { StorageColumn, nonEmptyTypeParams } from "@prisma/orm-family-sql/contract/types";
29
+ import { APP_SPACE_ID, failedPostcheckWhy, failedPrecheckWhy, schemaCheckWhy, withDatabaseUnchanged, withFailingSpace } from "@prisma/orm-framework/components/control";
30
+ import { assertDefined, invariant } from "@prisma/orm-framework/utils/assertions";
31
+ import { composeCheckWirePrefix, computeCheckContentHash, computeIndexContentHash, formatWireName, parseNaming } from "@prisma/orm-family-sql/schema-ir/naming";
32
+ import { ifDefined } from "@prisma/orm-framework/utils/defined";
33
+ import { authoringTypeConstructorArguments, findAuthoringTypeConstructorCall, getAuthoringTypeConstructor } from "@prisma/orm-framework/components/authoring";
34
+ import { NAME_THE_PSL_SOURCE_LOSES, isPslIdentifier } from "@prisma/orm-framework/psl-parser";
35
+ import { printSqlExpressionLiteral, sqlTextsReadBack } from "@prisma/orm-family-sql/contract/sql-expression";
36
+ import { convertedColumnOf, requiredColumnOf, requiredColumnsOfMigration, rowsWithoutValueFailure, runnerFailure, runnerSuccess, unconvertedFieldOf } from "@prisma/orm-family-sql/family/control";
37
+ import { notOk, ok, okVoid } from "@prisma/orm-framework/utils/result";
38
+ import { SqlSchemaVerifierBase } from "@prisma/orm-family-sql/family/ir";
39
+ import { effectiveControlPolicy } from "@prisma/orm-framework/contract/types";
40
+ import { generatorCallsFor, inferredTypeConstructors, mapDefault, writeDefaultLiteral, writtenTypeArguments } from "@prisma/orm-family-sql/family/psl-build";
41
+ import { UNBOUND_PSL_NAMESPACE_NAME, UNSPECIFIED_PSL_NAMESPACE_ID, makePslNamespace, makePslNamespaceEntries } from "@prisma/orm-framework/components/psl-ast";
42
+ import { escapePslString } from "@prisma/orm-family-sql/contract/data-type-support";
43
+ import { Temporal } from "temporal-polyfill/full/implementation";
44
+ import { SqlQueryError } from "@prisma/orm-family-sql/errors";
45
+ import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
46
+ import { pslFieldMapName, pslModelMapName } from "@prisma/orm-family-sql/contract-psl/map-names";
47
+ import { defaultForeignKeyIndex } from "@prisma/orm-family-sql/contract/foreign-key-materialization";
48
+ //#region ../../../3-targets/postgres/1-target/dist/control.mjs
49
+ /**
50
+ * Postgres target `SchemaVerifier` concretion. Plugs into the
51
+ * SQL-shared verification surface; production verification today still
52
+ * routes through the family verify verdict (`verifySqlSchemaByDiff` over
53
+ * `diffPostgresSchema`), which carries options (codec hooks,
54
+ * normalizers, framework components) that the framework-level
55
+ * `SchemaVerifyOptions` shape does not yet surface.
56
+ *
57
+ * The hooks return the empty list pending the call-site migration that
58
+ * routes the existing verifier behaviour through the SPI — at that
59
+ * point `verifyCommonSqlSchema` will likely lift onto the family base
60
+ * (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`
61
+ * will house Postgres-only kinds (functions, RLS policies in a future
62
+ * project).
63
+ */
64
+ var PostgresSchemaVerifier = class extends SqlSchemaVerifierBase {
65
+ verifyCommonSqlSchema(_options) {
66
+ return [];
67
+ }
68
+ verifyTargetExtensions(_options) {
69
+ return [];
70
+ }
71
+ };
72
+ const DEPENDENCY_LINE = /^(.+) (\S+) depends on /;
73
+ /** The objects Postgres's error detail says depend on what the statement removes. */
74
+ function dependentsOf(detail) {
75
+ return (detail ?? "").split("\n").flatMap((line) => {
76
+ const [, kind, name] = DEPENDENCY_LINE.exec(line.trim()) ?? [];
77
+ return kind === void 0 || name === void 0 ? [] : [{
78
+ kind,
79
+ name
80
+ }];
81
+ });
82
+ }
83
+ function listed(items) {
84
+ if (items.length === 1) return items[0] ?? "";
85
+ return `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
86
+ }
87
+ /** What a runner failure says when objects the contract does not know depend on what an operation removes. */
88
+ function dependentsSummary(details, label, dependents) {
89
+ const named = listed(dependents.map(({ kind, name }) => `${kind} ${name}`));
90
+ const depend = dependents.length === 1 ? "depends" : "depend";
91
+ return details.objectType === "table" && details.table === void 0 ? `Table "${details.schema}"."${details.name}" cannot be dropped while ${named} ${depend} on it.` : `${label} cannot run while ${named} ${depend} on what it changes.`;
92
+ }
93
+ /**
94
+ * Deep clones and freezes a record object to prevent mutation.
95
+ * Recursively clones nested objects and arrays to ensure complete isolation.
96
+ */
97
+ function cloneAndFreezeRecord(value) {
98
+ const cloned = {};
99
+ for (const [key, val] of Object.entries(value)) if (val === null || val === void 0) cloned[key] = val;
100
+ else if (Array.isArray(val)) cloned[key] = Object.freeze([...val]);
101
+ else if (typeof val === "object") cloned[key] = cloneAndFreezeRecord(blindCast(val));
102
+ else cloned[key] = val;
103
+ return blindCast(Object.freeze(cloned));
104
+ }
105
+ /**
106
+ * SQLSTATE classes of failures that come from the connection or the server, not from the SQL a step
107
+ * runs: connection exceptions, transaction rollbacks, resources, operator intervention, system and
108
+ * internal errors.
109
+ */
110
+ const NOT_THE_STEPS_SQL = [
111
+ "08",
112
+ "40",
113
+ "53",
114
+ "57",
115
+ "58",
116
+ "XX"
117
+ ];
118
+ /**
119
+ * The type change a failed step carries out. For the database's cast, a data exception (class 22)
120
+ * is a value it could not convert, and 42846 (`cannot_coerce`) a pair of types with no cast. For
121
+ * the migration's own conversion, every error of the step's SQL is the conversion's: a data
122
+ * exception is a value, an integrity violation (class 23) a value the new type cannot hold, and
123
+ * anything else an error in its expression.
124
+ */
125
+ function failedTypeChangeOf(step, sqlState, plan) {
126
+ const converted = convertedColumnOf(step);
127
+ const field = unconvertedFieldOf(step, plan.contract);
128
+ if (converted === void 0 || field === void 0 || sqlState === void 0) return void 0;
129
+ const { operationIndex } = plan;
130
+ if (converted.by === "conversion") {
131
+ if (NOT_THE_STEPS_SQL.some((sqlClass) => sqlState.startsWith(sqlClass))) return void 0;
132
+ return {
133
+ field,
134
+ by: "conversion",
135
+ reason: sqlState.startsWith("22") ? "value" : sqlState.startsWith("23") ? "invalidResult" : "expressionError",
136
+ operationIndex
137
+ };
138
+ }
139
+ const reason = sqlState === "42846" ? "noCast" : sqlState.startsWith("22") ? "value" : void 0;
140
+ return reason === void 0 ? void 0 : {
141
+ field,
142
+ by: "cast",
143
+ reason,
144
+ operationIndex
145
+ };
146
+ }
147
+ function createPostgresMigrationRunner(family) {
148
+ return new PostgresMigrationRunner(family);
149
+ }
150
+ var PostgresMigrationRunner = class {
151
+ family;
152
+ constructor(family) {
153
+ this.family = family;
154
+ }
155
+ /**
156
+ * Body of the migration runner without transaction management. The
157
+ * caller ({@link PostgresMigrationRunner.execute}) owns the
158
+ * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.
159
+ */
160
+ async executeOnConnection(options) {
161
+ const driver = options.driver;
162
+ if (options.space !== void 0 && options.space !== options.plan.spaceId) throw postgresError("MIGRATION.CONTRACT_SPACE_VIOLATION", `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`, { meta: {
163
+ space: options.space,
164
+ planSpaceId: options.plan.spaceId
165
+ } });
166
+ const space = options.plan.spaceId;
167
+ const planOps = blindCast(await Promise.all(options.plan.operations));
168
+ const destinationCheck = this.ensurePlanMatchesDestinationContract(options.plan.destination, options.destinationContract);
169
+ if (!destinationCheck.ok) return destinationCheck;
170
+ const policyCheck = this.enforcePolicyCompatibility(options.policy, planOps);
171
+ if (!policyCheck.ok) return policyCheck;
172
+ await this.acquireLock(driver);
173
+ const ensureResult = await this.ensureControlTables(driver, options.destinationContract);
174
+ if (!ensureResult.ok) return ensureResult;
175
+ const existingMarker = await this.family.readMarker({
176
+ driver,
177
+ space
178
+ });
179
+ const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
180
+ if (!markerCheck.ok) return markerCheck;
181
+ const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
182
+ const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;
183
+ const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;
184
+ let applyValue;
185
+ if (skipOperations) applyValue = {
186
+ operationsExecuted: 0,
187
+ executedOperations: []
188
+ };
189
+ else {
190
+ const applyResult = await this.applyPlan(driver, options, planOps);
191
+ if (!applyResult.ok) return applyResult;
192
+ applyValue = applyResult.value;
193
+ }
194
+ if (space === APP_SPACE_ID) {
195
+ const schemaNode = await this.family.introspect({
196
+ driver,
197
+ contract: options.destinationContract
198
+ });
199
+ const schemaVerifyResult = this.family.verifySchema({
200
+ contract: options.destinationContract,
201
+ schema: schemaNode,
202
+ strict: options.strictVerification ?? true,
203
+ frameworkComponents: options.frameworkComponents
204
+ });
205
+ if (!schemaVerifyResult.ok) return runnerFailure("MIGRATION.SCHEMA_VERIFY_FAILED", schemaVerifyResult.summary, {
206
+ why: schemaCheckWhy(schemaVerifyResult.schema.issues),
207
+ meta: { schemaIssues: schemaVerifyResult.schema.issues }
208
+ });
209
+ }
210
+ const incomingInvariants = options.plan.providedInvariants ?? [];
211
+ const existingInvariants = new Set(existingMarker?.invariants ?? []);
212
+ const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));
213
+ if (!(isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting)) {
214
+ const markerResult = await this.upsertMarker(driver, options, existingMarker, space);
215
+ if (!markerResult.ok) return markerResult;
216
+ await this.recordLedgerEntries(driver, options, applyValue.executedOperations, planOps.length);
217
+ }
218
+ return runnerSuccess({
219
+ operationsPlanned: planOps.length,
220
+ operationsExecuted: applyValue.operationsExecuted
221
+ });
222
+ }
223
+ async execute(options) {
224
+ const driver = options.driver;
225
+ const perSpaceOptions = options.perSpaceOptions;
226
+ if (perSpaceOptions.length === 0) return ok({ perSpaceResults: [] });
227
+ await this.beginTransaction(driver);
228
+ let committed = false;
229
+ try {
230
+ const result = await this.executeSpaces(driver, perSpaceOptions);
231
+ if (!result.ok) return notOk(withDatabaseUnchanged(result.failure, true));
232
+ await this.commitTransaction(driver);
233
+ committed = true;
234
+ return result;
235
+ } finally {
236
+ if (!committed) await this.rollbackTransaction(driver);
237
+ }
238
+ }
239
+ async executeSpaces(driver, perSpaceOptions) {
240
+ const perSpaceResults = [];
241
+ for (const spaceOptions of perSpaceOptions) {
242
+ const space = spaceOptions.space ?? spaceOptions.plan.spaceId;
243
+ const result = await this.executeOnConnection({
244
+ ...spaceOptions,
245
+ driver,
246
+ space
247
+ });
248
+ if (!result.ok) return notOk(withFailingSpace(result.failure, space));
249
+ perSpaceResults.push({
250
+ space,
251
+ value: result.value
252
+ });
253
+ }
254
+ return ok({ perSpaceResults });
255
+ }
256
+ async applyPlan(driver, options, ops) {
257
+ const checks = options.executionChecks;
258
+ const runPrechecks = checks?.prechecks !== false;
259
+ const runPostchecks = checks?.postchecks !== false;
260
+ const runIdempotency = checks?.idempotencyChecks !== false;
261
+ let operationsExecuted = 0;
262
+ const executedOperations = [];
263
+ for (const operation of ops) {
264
+ options.callbacks?.onOperationStart?.(operation);
265
+ try {
266
+ if (runPostchecks && runIdempotency) {
267
+ if (await this.expectationsAreSatisfied(driver, operation.postcheck)) {
268
+ executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));
269
+ continue;
270
+ }
271
+ }
272
+ const position = {
273
+ contract: options.destinationContract,
274
+ operationIndex: ops.indexOf(operation),
275
+ operations: ops,
276
+ edges: options.migrationEdges
277
+ };
278
+ if (runPrechecks) {
279
+ const precheckResult = await this.runExpectationSteps(driver, operation.precheck, operation, "precheck", position);
280
+ if (!precheckResult.ok) return precheckResult;
281
+ }
282
+ const executeResult = await this.runExecuteSteps(driver, operation, position);
283
+ if (!executeResult.ok) return executeResult;
284
+ if (runPostchecks) {
285
+ const postcheckResult = await this.runExpectationSteps(driver, operation.postcheck, operation, "postcheck", position);
286
+ if (!postcheckResult.ok) return postcheckResult;
287
+ }
288
+ executedOperations.push(operation);
289
+ operationsExecuted += 1;
290
+ } finally {
291
+ options.callbacks?.onOperationComplete?.(operation);
292
+ }
293
+ }
294
+ return ok({
295
+ operationsExecuted,
296
+ executedOperations
297
+ });
298
+ }
299
+ async ensureControlTables(driver, contract) {
300
+ const lowererContext = { contract };
301
+ const [schemaQuery, ...tableQueries] = this.family.bootstrapControlTableQueries();
302
+ if (schemaQuery === void 0) throw new InternalError("Postgres control-table bootstrap must include CREATE SCHEMA");
303
+ await this.executeStatement(driver, await this.family.lowerAst(schemaQuery, lowererContext));
304
+ for (const query of tableQueries) await this.executeStatement(driver, await this.family.lowerAst(query, lowererContext));
305
+ return okVoid();
306
+ }
307
+ async runExpectationSteps(driver, steps, operation, phase, plan) {
308
+ for (const step of steps) {
309
+ const result = await driver.query(step.sql, step.params ?? []);
310
+ if (!this.stepResultIsTrue(result.rows)) {
311
+ const code = phase === "precheck" ? "MIGRATION.PRECHECK_FAILED" : "MIGRATION.POSTCHECK_FAILED";
312
+ const failed = `Operation ${operation.id} failed during ${phase}: ${step.description}`;
313
+ const blockedSchema = schemaContentsOf(step);
314
+ const objects = blockedSchema === void 0 ? void 0 : await driver.query(SCHEMA_OBJECTS_SQL, [blockedSchema]);
315
+ if (blockedSchema !== void 0 && objects !== void 0 && objects.rows.length > 0) {
316
+ const blockingObjects = schemaBlockingObjects(blockedSchema, objects.rows);
317
+ return runnerFailure(code, schemaObjectsSummary(blockedSchema, blockingObjects), {
318
+ why: failed,
319
+ meta: {
320
+ failedCheck: {
321
+ operationId: operation.id,
322
+ phase,
323
+ description: step.description
324
+ },
325
+ blockingObjects
326
+ }
327
+ });
328
+ }
329
+ const required = requiredColumnOf(step);
330
+ const rowsWithoutValue = required === void 0 ? void 0 : await this.rowsWithoutValue(driver, operation, required, plan);
331
+ const failedCheck = {
332
+ operationId: operation.id,
333
+ phase,
334
+ description: step.description,
335
+ ...ifDefined("expectation", step.expectation)
336
+ };
337
+ return runnerFailure(code, rowsWithoutValue?.summary ?? failed, {
338
+ ...ifDefined("why", rowsWithoutValue !== void 0 ? failed : phase === "precheck" ? failedPrecheckWhy(failedCheck) : failedPostcheckWhy(failedCheck)),
339
+ meta: {
340
+ failedCheck,
341
+ ...ifDefined("rowsWithoutValue", rowsWithoutValue?.reports)
342
+ }
343
+ });
344
+ }
345
+ }
346
+ return okVoid();
347
+ }
348
+ /**
349
+ * Counts the rows the failed step's column has no value in, then those of every other column the
350
+ * failed operation's migration makes required.
351
+ */
352
+ rowsWithoutValue(driver, operation, required, plan) {
353
+ return rowsWithoutValueFailure({
354
+ failed: [{
355
+ operation,
356
+ operationIndex: plan.operationIndex,
357
+ required
358
+ }],
359
+ others: requiredColumnsOfMigration(plan.operations, plan.edges, plan.operationIndex),
360
+ count: async ({ operation: marked, required: column }) => {
361
+ const schema = marked.target.details?.schema;
362
+ if (schema === void 0) return 0;
363
+ const where = column.reason !== "newField" ? ` WHERE ${quoteIdentifier(column.column)} IS NULL` : "";
364
+ return (await driver.query(`SELECT COUNT(*)::int AS rows FROM ${qualifyTableName(schema, column.table)}${where}`)).rows[0]?.rows ?? 0;
365
+ },
366
+ contract: plan.contract
367
+ });
368
+ }
369
+ async runExecuteSteps(driver, operation, plan) {
370
+ for (const step of operation.execute) try {
371
+ await driver.query(step.sql, step.params ?? []);
372
+ } catch (error) {
373
+ if (SqlQueryError.is(error)) {
374
+ const dependents = error.sqlState === "2BP01" ? dependentsOf(error.detail) : [];
375
+ const details = operation.target.details;
376
+ return runnerFailure("MIGRATION.EXECUTION_FAILED", dependents.length > 0 && details !== void 0 ? dependentsSummary(details, operation.label, dependents) : `Operation ${operation.id} failed during execution: ${step.description}`, {
377
+ why: error.message,
378
+ meta: {
379
+ ...ifDefined("failedTypeChange", failedTypeChangeOf(step, error.sqlState, plan)),
380
+ ...ifDefined("blockingObjects", dependents.length > 0 ? dependents : void 0),
381
+ operationId: operation.id,
382
+ stepDescription: step.description,
383
+ sql: step.sql,
384
+ sqlState: error.sqlState,
385
+ constraint: error.constraint,
386
+ table: error.table,
387
+ column: error.column,
388
+ detail: error.detail
389
+ }
390
+ });
391
+ }
392
+ throw error;
393
+ }
394
+ return okVoid();
395
+ }
396
+ stepResultIsTrue(rows) {
397
+ if (!rows || rows.length === 0) return false;
398
+ const firstRow = rows[0];
399
+ const firstValue = firstRow ? Object.values(firstRow)[0] : void 0;
400
+ if (typeof firstValue === "boolean") return firstValue;
401
+ if (typeof firstValue === "number") return firstValue !== 0;
402
+ if (typeof firstValue === "string") {
403
+ const lower = firstValue.toLowerCase();
404
+ if (lower === "t" || lower === "true" || lower === "1") return true;
405
+ if (lower === "f" || lower === "false" || lower === "0") return false;
406
+ return firstValue.length > 0;
407
+ }
408
+ return Boolean(firstValue);
409
+ }
410
+ async expectationsAreSatisfied(driver, steps) {
411
+ if (steps.length === 0) return false;
412
+ for (const step of steps) {
413
+ const result = await driver.query(step.sql, step.params ?? []);
414
+ if (!this.stepResultIsTrue(result.rows)) return false;
415
+ }
416
+ return true;
417
+ }
418
+ createPostcheckPreSatisfiedSkipRecord(operation) {
419
+ const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : void 0;
420
+ const runnerMeta = Object.freeze({
421
+ skipped: true,
422
+ reason: "postcheck_pre_satisfied"
423
+ });
424
+ const mergedMeta = Object.freeze({
425
+ ...clonedMeta ?? {},
426
+ runner: runnerMeta
427
+ });
428
+ const frozenPostcheck = Object.freeze([...operation.postcheck]);
429
+ return Object.freeze({
430
+ id: operation.id,
431
+ label: operation.label,
432
+ ...ifDefined("summary", operation.summary),
433
+ operationClass: operation.operationClass,
434
+ target: operation.target,
435
+ precheck: Object.freeze([]),
436
+ execute: Object.freeze([]),
437
+ postcheck: frozenPostcheck,
438
+ ...ifDefined("meta", operation.meta || mergedMeta ? mergedMeta : void 0)
439
+ });
440
+ }
441
+ markerMatchesDestination(marker, plan) {
442
+ if (!marker) return false;
443
+ if (marker.storageHash !== plan.destination.storageHash) return false;
444
+ if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) return false;
445
+ return true;
446
+ }
447
+ enforcePolicyCompatibility(policy, operations) {
448
+ const allowedClasses = new Set(policy.allowedOperationClasses);
449
+ for (const operation of operations) if (!allowedClasses.has(operation.operationClass)) return runnerFailure("MIGRATION.POLICY_VIOLATION", `Operation ${operation.id} has class "${operation.operationClass}" which is not allowed by policy.`, {
450
+ why: `Policy only allows: ${policy.allowedOperationClasses.join(", ")}.`,
451
+ meta: {
452
+ operationId: operation.id,
453
+ operationClass: operation.operationClass,
454
+ allowedClasses: policy.allowedOperationClasses
455
+ }
456
+ });
457
+ return okVoid();
458
+ }
459
+ ensureMarkerCompatibility(marker, plan) {
460
+ const origin = plan.origin ?? null;
461
+ if (!origin) return okVoid();
462
+ if (!marker) return runnerFailure("MIGRATION.MARKER_ORIGIN_MISMATCH", `Missing contract marker: expected origin storage hash ${origin.storageHash}.`, { meta: { expectedOriginStorageHash: origin.storageHash } });
463
+ if (marker.storageHash !== origin.storageHash) return runnerFailure("MIGRATION.MARKER_ORIGIN_MISMATCH", `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`, { meta: {
464
+ markerStorageHash: marker.storageHash,
465
+ expectedOriginStorageHash: origin.storageHash
466
+ } });
467
+ if (origin.profileHash && marker.profileHash !== origin.profileHash) return runnerFailure("MIGRATION.MARKER_ORIGIN_MISMATCH", `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`, { meta: {
468
+ markerProfileHash: marker.profileHash,
469
+ expectedOriginProfileHash: origin.profileHash
470
+ } });
471
+ return okVoid();
472
+ }
473
+ ensurePlanMatchesDestinationContract(destination, contract) {
474
+ if (destination.storageHash !== contract.storage.storageHash) return runnerFailure("MIGRATION.DESTINATION_CONTRACT_MISMATCH", `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`, { meta: {
475
+ planStorageHash: destination.storageHash,
476
+ contractStorageHash: contract.storage.storageHash
477
+ } });
478
+ if (destination.profileHash && contract.profileHash && destination.profileHash !== contract.profileHash) return runnerFailure("MIGRATION.DESTINATION_CONTRACT_MISMATCH", `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`, { meta: {
479
+ planProfileHash: destination.profileHash,
480
+ contractProfileHash: contract.profileHash
481
+ } });
482
+ return okVoid();
483
+ }
484
+ async upsertMarker(driver, options, existingMarker, space) {
485
+ const destination = {
486
+ storageHash: options.plan.destination.storageHash,
487
+ profileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
488
+ invariants: options.plan.providedInvariants ?? []
489
+ };
490
+ if (!existingMarker) {
491
+ await this.family.initMarker({
492
+ driver,
493
+ space,
494
+ destination
495
+ });
496
+ return okVoid();
497
+ }
498
+ if (!await this.family.updateMarker({
499
+ driver,
500
+ space,
501
+ expectedFrom: existingMarker.storageHash,
502
+ destination
503
+ })) {
504
+ const found = await this.family.readMarker({
505
+ driver,
506
+ space
507
+ });
508
+ return runnerFailure("MIGRATION.MARKER_CAS_FAILURE", "Marker was modified by another process during migration execution.", { meta: {
509
+ space,
510
+ expectedStorageHash: existingMarker.storageHash,
511
+ foundStorageHash: found?.storageHash ?? null,
512
+ destinationStorageHash: options.plan.destination.storageHash
513
+ } });
514
+ }
515
+ return okVoid();
516
+ }
517
+ async recordLedgerEntries(driver, options, executedOperations, planOpsLength) {
518
+ const space = options.plan.spaceId;
519
+ const edges = options.migrationEdges;
520
+ const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);
521
+ if (totalEdgeOps !== planOpsLength) throw new InternalError(`Ledger write: plan.operations length (${planOpsLength}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`);
522
+ let offset = 0;
523
+ for (const edge of edges) {
524
+ const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);
525
+ offset += edge.operationCount;
526
+ await this.family.writeLedgerEntry({
527
+ driver,
528
+ space,
529
+ entry: {
530
+ edgeId: `${edge.from}->${edge.to}`,
531
+ from: edge.from,
532
+ to: edge.to,
533
+ migrationName: edge.dirName,
534
+ migrationHash: edge.migrationHash,
535
+ operations: edgeOps,
536
+ ...ifDefined("destinationContractJson", edge.destinationContractJson)
537
+ }
538
+ });
539
+ }
540
+ }
541
+ async acquireLock(driver) {
542
+ await driver.query(MARKER_LOCK_SQL, [MARKER_LOCK_KEY]);
543
+ }
544
+ async beginTransaction(driver) {
545
+ await driver.query("BEGIN");
546
+ }
547
+ async commitTransaction(driver) {
548
+ await driver.query("COMMIT");
549
+ }
550
+ async rollbackTransaction(driver) {
551
+ await driver.query("ROLLBACK");
552
+ }
553
+ async executeStatement(driver, statement) {
554
+ await driver.query(statement.sql, statement.params);
555
+ }
556
+ };
557
+ /** The name a contract namespace is written under in PSL. */
558
+ function pslNamespaceName(namespaceId) {
559
+ return namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_PSL_NAMESPACE_NAME : namespaceId;
560
+ }
561
+ function modelCoordinate(namespaceId, modelName) {
562
+ return JSON.stringify([namespaceId, modelName]);
563
+ }
564
+ /**
565
+ * Every domain model of the contract, in declaration order, with its storage table. Contract
566
+ * validation has checked that each model's table exists, in the namespace of the model.
567
+ */
568
+ function indexContractModels(contract) {
569
+ const entries = [];
570
+ for (const [namespaceId, domainNamespace] of Object.entries(contract.domain.namespaces)) for (const [name, model] of Object.entries(domainNamespace.models)) {
571
+ const storage = blindCast(model.storage);
572
+ const table = contract.storage.namespaces[storage.namespaceId]?.entries.table?.[storage.table];
573
+ assertDefined(table, `model "${namespaceId}.${name}" is stored in table "${storage.namespaceId}"."${storage.table}", which the storage does not declare`);
574
+ const fields = Object.entries(storage.fields);
575
+ entries.push({
576
+ namespaceId: storage.namespaceId,
577
+ name,
578
+ tableName: storage.table,
579
+ storage,
580
+ model,
581
+ table,
582
+ fieldNamesByColumn: new Map(fields.map(([fieldName, field]) => [field.column, fieldName])),
583
+ ownColumns: new Set(fields.map(([, field]) => field.column))
584
+ });
585
+ }
586
+ return entries;
587
+ }
588
+ /** Models keyed by their `(namespace, model)` coordinate. */
589
+ function modelsByCoordinate(entries) {
590
+ return new Map(entries.map((entry) => [modelCoordinate(entry.namespaceId, entry.name), entry]));
591
+ }
592
+ /** A cross reference's coordinate; one into another contract space never matches a model of this contract. */
593
+ function crossReferenceCoordinate(reference) {
594
+ return reference.space === void 0 ? modelCoordinate(reference.namespace, reference.model) : JSON.stringify([
595
+ reference.space,
596
+ reference.namespace,
597
+ reference.model
598
+ ]);
599
+ }
600
+ /** The base a variant model extends, with the discriminator value it is stored under. */
601
+ function variantInfo(entry, byCoordinate) {
602
+ if (entry.model.base === void 0) return void 0;
603
+ const base = byCoordinate.get(crossReferenceCoordinate(entry.model.base));
604
+ const value = Object.entries(base?.model.variants ?? {}).find(([, reference]) => reference.namespace === entry.namespaceId && reference.model === entry.name)?.[0];
605
+ assertDefined(base, `model "${entry.namespaceId}.${entry.name}" extends a base the contract does not declare`);
606
+ assertDefined(value, `model "${entry.namespaceId}.${entry.name}" extends base "${base.name}", which does not list it as a variant`);
607
+ return {
608
+ base,
609
+ value,
610
+ singleTable: base.namespaceId === entry.namespaceId && base.tableName === entry.tableName
611
+ };
612
+ }
613
+ /** The columns the PSL source adds to a multi-table variant's table: its base's primary key. */
614
+ function variantLinkColumns(entry, variant) {
615
+ if (variant === void 0 || variant.singleTable) return [];
616
+ return (variant.base.table.primaryKey?.columns ?? []).filter((column) => !entry.ownColumns.has(column));
617
+ }
618
+ /**
619
+ * The foreign key the PSL source synthesizes from a multi-table variant to its base: unnamed, over
620
+ * the base's primary key columns, cascading on delete.
621
+ */
622
+ function isVariantLinkForeignKey(fk, variant) {
623
+ if (variant === void 0 || variant.singleTable) return false;
624
+ const baseKey = canonicalizeJson(variant.base.table.primaryKey?.columns ?? []);
625
+ return fk.target.namespaceId === variant.base.namespaceId && fk.target.tableName === variant.base.tableName && fk.target.spaceId === void 0 && canonicalizeJson(fk.source.columns) === baseKey && canonicalizeJson(fk.target.columns) === baseKey && fk.name === void 0 && fk.onDelete === "cascade" && fk.onUpdate === void 0;
626
+ }
627
+ const KEEP_SOURCE = "Keep authoring this contract in its current source.";
628
+ function unsupported(message, why, fix, meta) {
629
+ return postgresError("CONTRACT.PRINT_UNSUPPORTED", `contract print: ${message}`, {
630
+ why,
631
+ fix,
632
+ meta
633
+ });
634
+ }
635
+ function sameJson(left, right) {
636
+ return canonicalizeJson(left) === canonicalizeJson(right);
637
+ }
638
+ function sameValues$1(left, right) {
639
+ return left.length === right.length && left.every((value, index) => value === right[index]);
640
+ }
641
+ function refuseColumnWithoutPslType(column, coordinate) {
642
+ throw unsupported(`column ${coordinate} has data type "${column.dataType}" with codec "${column.codecId}", and no PSL type in the configured stack produces that pair.`, "A column is written as a PSL type that reads back with its codec and data type, and none of the types the target, adapter and extensions contribute does.", "Add the extension that contributes this type to the config, or keep authoring this contract in its current source.", {
643
+ coordinate,
644
+ dataType: column.dataType,
645
+ codecId: column.codecId
646
+ });
647
+ }
648
+ /**
649
+ * Refuses a type constructor call whose arguments no PSL literal writes: an argument that is not a value of a data type, or a value no literal of its data type reads back as.
650
+ */
651
+ function refuseUnwritableTypeArgument(call, coordinate) {
652
+ throw unsupported(`column ${coordinate} is written ${`${call.path.join(".")}(${call.args.map((arg) => JSON.stringify(arg)).join(", ")})`}, and an argument has no PSL literal that reads back as it.`, "Each argument of a type constructor is written as a literal of its data type, and contract print writes it only when the literal reads back as the same value.", KEEP_SOURCE, {
653
+ coordinate,
654
+ path: call.path.join("."),
655
+ arguments: call.args
656
+ });
657
+ }
658
+ function refuseDefaultOutsideEnum(input) {
659
+ throw unsupported(`column ${input.coordinate} defaults to ${JSON.stringify(input.value)}, which is not a member of enum ${input.pslTypeName}.`, "A default on a domain enum column is written as the member name, and no member carries this value.", "Give the column a default that is one of the enum members, or drop it.", {
660
+ coordinate: input.coordinate,
661
+ pslTypeName: input.pslTypeName
662
+ });
663
+ }
664
+ function refuseUnwritableEnumMember(input) {
665
+ throw unsupported(`enum "${input.enumName}" member "${input.member}" stores ${JSON.stringify(input.value)}, which no Prisma 8 PSL literal of the enum's data type writes.`, "Writing the value in any other form would parse, but the PSL source would read it back as a different value.", "Type the enum with a codec whose values PSL writes, such as pg/text@1, before printing.", {
666
+ enumName: input.enumName,
667
+ member: input.member
668
+ });
669
+ }
670
+ function refuseUnwritableLiteralDefault(input) {
671
+ throw unsupported(`column ${input.coordinate} has a default that cannot be written in Prisma 8 PSL: no data type the ${input.pslTypeName} type takes writes ${input.written}.`, "Writing the value in any other form would parse, but the PSL source would read it back as a different value.", "Replace the default with a database expression default, or drop the default before printing.", {
672
+ coordinate: input.coordinate,
673
+ pslTypeName: input.pslTypeName
674
+ });
675
+ }
676
+ const PHASE_TEXT = {
677
+ onCreate: "on create",
678
+ onUpdate: "on update"
679
+ };
680
+ function describeGenerator(generator) {
681
+ if (generator === void 0) return "no generator";
682
+ const params = generator.params ?? {};
683
+ return Object.keys(params).length === 0 ? `"${generator.id}"` : `"${generator.id}" with params ${canonicalizeJson(params)}`;
684
+ }
685
+ function refuseGeneratorOnList(input) {
686
+ throw unsupported(`column ${input.coordinate} is a list and generates "${input.generatorId}" ${PHASE_TEXT[input.phase]}, which cannot be written in Prisma 8 PSL.`, "Prisma 8 PSL refuses `@onCreate(…)` and `@onUpdate(…)` on a list field, since a list has no generated value per element.", KEEP_SOURCE, {
687
+ coordinate: input.coordinate,
688
+ phase: input.phase,
689
+ generatorId: input.generatorId
690
+ });
691
+ }
692
+ function refuseGeneratorWithoutPslFunction(input) {
693
+ const { coordinate, phase, generatorId, codecId, registeredBy } = input;
694
+ const meta = {
695
+ coordinate,
696
+ phase,
697
+ generatorId,
698
+ codecId
699
+ };
700
+ if (registeredBy === void 0) throw unsupported(`column ${coordinate} is generated by "${generatorId}" ${PHASE_TEXT[phase]}, which no component in the configured stack registers.`, `The printer writes each generator as \`@${phase}(fn(…))\` with the generator function the configured stack binds to the column's codec, and no component in the stack registers this generator.`, "Add the extension that registers the generator and its generator function to the config, or keep authoring this contract in its current source.", meta);
701
+ const { componentId } = registeredBy;
702
+ const registrant = componentId === void 0 ? "a configured component" : `"${componentId}"`;
703
+ throw unsupported(`column ${coordinate} is generated by "${generatorId}" ${PHASE_TEXT[phase]}, which ${registrant} registers, but no generator function in the configured stack writes it for codec "${codecId}".`, `The printer writes each generator as \`@${phase}(fn(…))\` with the generator function the configured stack binds to the column's codec, and no function bound to "${codecId}" produces this generator.`, `If ${componentId === void 0 ? `the component that registers "${generatorId}"` : `"${componentId}"`} declares a generator function that produces it, its author must bind that function to codec "${codecId}", as the upgrade instructions "default-generators-to-on-create" for extension authors describe. Until then, keep authoring this contract in its current source.`, {
704
+ ...meta,
705
+ ...ifDefined("componentId", componentId)
706
+ });
707
+ }
708
+ function refuseGeneratorReadingBackDifferently(input) {
709
+ const readBack = input.refusedBecause === void 0 ? `reads back as ${describeGenerator(input.readBack)}` : `is refused: ${input.refusedBecause}`;
710
+ throw unsupported(`column ${input.coordinate} generates ${describeGenerator(input.stored)} ${PHASE_TEXT[input.phase]}, but @${input.phase}(${input.call}) ${readBack.endsWith(".") ? readBack.slice(0, -1) : readBack}.`, "The printer writes each generator as the call of the generator function the configured stack binds to the column's codec, and that call must resolve back to the stored generator and params on the column.", KEEP_SOURCE, {
711
+ coordinate: input.coordinate,
712
+ phase: input.phase,
713
+ call: input.call,
714
+ stored: input.stored,
715
+ readBack: input.readBack,
716
+ refusedBecause: input.refusedBecause
717
+ });
718
+ }
719
+ /**
720
+ * The value-set references the PSL source gives a field typed by a domain enum, one per plane: the
721
+ * domain names the enum and the storage column names the enum's value set, both in the default
722
+ * namespace. A field with no domain enum has neither.
723
+ */
724
+ function derivedValueSetRefs(enumName) {
725
+ if (enumName === void 0) return {
726
+ domain: void 0,
727
+ storage: void 0
728
+ };
729
+ const common = {
730
+ namespaceId: DEFAULT_NAMESPACE_ID,
731
+ entityName: enumName
732
+ };
733
+ return {
734
+ domain: {
735
+ plane: "domain",
736
+ entityKind: "enum",
737
+ ...common
738
+ },
739
+ storage: {
740
+ plane: "storage",
741
+ entityKind: "valueSet",
742
+ ...common
743
+ }
744
+ };
745
+ }
746
+ /**
747
+ * Refuses a field whose column the PSL source would not derive from it: PSL writes the field once,
748
+ * and the PSL source derives the column's nullability, list marker, codec and type parameters from
749
+ * what is written.
750
+ */
751
+ function refuseFieldColumnMismatch(input) {
752
+ const { field, column, coordinate } = input;
753
+ const fix = "Make the field and its column agree, or keep authoring this contract in its current source.";
754
+ const fixForEarlierRelease = `If an earlier release emitted this contract, emit it again. ${fix}`;
755
+ if (input.singleTableVariant && !column.nullable) throw unsupported(`column ${coordinate} of single-table variant "${input.modelName}" is not nullable, which cannot be written in Prisma 8 PSL.`, "The PSL source makes every column of a single-table variant nullable, because the base's other rows leave it empty.", fix, { coordinate });
756
+ if (!input.singleTableVariant && field.nullable !== column.nullable) throw unsupported(`field ${coordinate} is ${field.nullable ? "optional" : "required"} but its column is ${column.nullable ? "nullable" : "not nullable"}, which cannot be written in Prisma 8 PSL.`, "PSL writes `?` once, and the PSL source derives the column from the field.", fix, { coordinate });
757
+ if ((field.type.kind === "scalar" && !!field.many) !== (column.many !== false)) throw unsupported(`field ${coordinate} is ${field.many ? "a list" : "not a list"} but its column is ${column.many !== false ? "a list" : "not a list"}, which cannot be written in Prisma 8 PSL.`, "PSL writes `[]` once: the PSL source stores a list of scalars in a list column, and a list of value objects in one JSON column.", fix, { coordinate });
758
+ if (field.type.kind === "scalar" && (field.type.codecId !== column.codecId || !sameJson(nonEmptyTypeParams(field.type.typeParams), nonEmptyTypeParams(column.typeParams)))) throw unsupported(`field ${coordinate} has a different codec or type parameters from its column, which cannot be written in Prisma 8 PSL.`, "The PSL source derives a scalar field's codec and type parameters from its column.", fixForEarlierRelease, { coordinate });
759
+ if (field.type.kind !== "scalar" || column.codecId === "pg/enum@1") return;
760
+ const enumName = column.valueSet?.entityName;
761
+ const derived = derivedValueSetRefs(enumName);
762
+ if (!sameJson(field.valueSet, derived.domain) || !sameJson(column.valueSet, derived.storage) || enumName !== void 0 && !input.domainEnumNames.has(enumName)) throw unsupported(`field ${coordinate} and its column do not name the enum of the default namespace and its value set that the PSL source derives for a field typed by an enum, which cannot be written in Prisma 8 PSL.`, "PSL types the field by the enum name, and the PSL source then points the column at the value set of that enum in the default namespace, and the field at the enum.", fixForEarlierRelease, { coordinate });
763
+ }
764
+ /**
765
+ * Refuses a field PSL has no form for: one whose type is a union of types, or one that is a
766
+ * dictionary. Runs for model fields and value-object members alike.
767
+ */
768
+ function refuseUnwritableFieldShape(field, coordinate) {
769
+ if (field.type.kind === "union") throw unsupported(`field ${coordinate} has a ${field.type.kind} type, which cannot be written in Prisma 8 PSL.`, "A PSL field names one scalar, enum, or value-object type; a union of types has no PSL form.", "Give the field a single type, or keep authoring this contract in its current source.", {
770
+ coordinate,
771
+ kind: field.type.kind
772
+ });
773
+ if (field.dict !== true) return;
774
+ throw unsupported(`field ${coordinate} is a dictionary, which cannot be written in Prisma 8 PSL.`, "PSL writes a field as one value or a list; it has no form for a keyed dictionary.", KEEP_SOURCE, { coordinate });
775
+ }
776
+ /**
777
+ * Refuses a value-object member with a value set other than the one the PSL source derives for a member typed by an enum: the enum of the default namespace, with the enum's codec and no type parameters.
778
+ */
779
+ function refuseUnderivedMemberValueSet(input) {
780
+ const { field, type, coordinate } = input;
781
+ const { valueSet } = field;
782
+ if (valueSet === void 0) return;
783
+ const domainEnum = input.domainEnums[valueSet.entityName];
784
+ if (sameJson(valueSet, derivedValueSetRefs(valueSet.entityName).domain) && domainEnum?.codecId === type.codecId && type.typeParams === void 0) return;
785
+ throw unsupported(`value-object member ${coordinate} carries a value set other than an enum of the default namespace with that enum's codec and no type parameters, which cannot be written in Prisma 8 PSL.`, "PSL types the member by the enum name, and the PSL source then points the member at that enum in the default namespace and gives it the enum's codec.", KEEP_SOURCE, { coordinate });
786
+ }
787
+ function refuseMemberCodecWithoutNativeType(codecId, coordinate) {
788
+ throw unsupported(`value-object member ${coordinate} uses codec "${codecId}", which no Postgres codec in the configured stack names a native type for.`, "A value-object member has no storage column, so its PSL type is derived from the native type its codec names.", KEEP_SOURCE, {
789
+ coordinate,
790
+ codecId
791
+ });
792
+ }
793
+ function refuseMemberCodecNeedingTypeParameters(codecId, coordinate) {
794
+ throw unsupported(`value-object member ${coordinate} uses codec "${codecId}", which names a native type only from type parameters the member does not carry.`, "A value-object member has no storage column, so its PSL type is derived from the native type its codec names for its type parameters.", KEEP_SOURCE, {
795
+ coordinate,
796
+ codecId
797
+ });
798
+ }
799
+ /** Refuses a column a model stores under a field name the model does not declare. */
800
+ function refuseStorageOfUndeclaredField(input) {
801
+ const { entry, fieldName } = input;
802
+ throw unsupported(`model "${entry.namespaceId}.${entry.name}" stores "${fieldName}" in column ${input.coordinate}, but the model has no field of that name, so it cannot be written in Prisma 8 PSL.`, "PSL declares a field together with the column it is stored in.", "Declare the field on the model, or keep authoring this contract in its current source.", {
803
+ namespaceId: entry.namespaceId,
804
+ modelName: entry.name,
805
+ field: fieldName
806
+ });
807
+ }
808
+ function refuseColumnControl(column, coordinate) {
809
+ if (column.control === void 0) return;
810
+ throw unsupported(`column ${coordinate} carries its own control policy "${column.control}", which cannot be written in Prisma 8 PSL.`, "PSL declares a control policy per model with `@@control`; a field has no control attribute.", "Move the policy to the model, or keep authoring this contract in its current source.", {
811
+ coordinate,
812
+ control: column.control
813
+ });
814
+ }
815
+ /** Refuses a storage table no model is stored in, and a column no field or variant link stores. */
816
+ function refuseUnmodelledTablesAndColumns(contract, models, variants) {
817
+ const tableKey = (namespaceId, tableName) => JSON.stringify([namespaceId, tableName]);
818
+ const coveredColumns = /* @__PURE__ */ new Map();
819
+ for (const entry of models) {
820
+ const key = tableKey(entry.namespaceId, entry.tableName);
821
+ const columns = coveredColumns.get(key) ?? /* @__PURE__ */ new Set();
822
+ for (const column of entry.ownColumns) columns.add(column);
823
+ for (const column of variantLinkColumns(entry, variants.get(entry))) columns.add(column);
824
+ coveredColumns.set(key, columns);
825
+ }
826
+ for (const [namespaceId, namespace] of Object.entries(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(namespace.entries.table ?? {})) {
827
+ const covered = coveredColumns.get(tableKey(namespaceId, tableName));
828
+ if (covered === void 0) throw unsupported(`table "${namespaceId}"."${tableName}" has no model stored in it, so it cannot be written in Prisma 8 PSL.`, "PSL declares a table through the model stored in it.", "Declare a model for the table, or keep authoring this contract in its current source.", {
829
+ namespaceId,
830
+ table: tableName
831
+ });
832
+ for (const column of Object.keys(table.columns)) {
833
+ if (covered.has(column)) continue;
834
+ throw unsupported(`column "${namespaceId}"."${tableName}"."${column}" is not stored by any field, so it cannot be written in Prisma 8 PSL.`, "PSL declares a column through the field stored in it; the only columns the PSL source adds are the primary key columns that link a multi-table variant to its base.", "Add a field for the column, or keep authoring this contract in its current source.", {
835
+ namespaceId,
836
+ table: tableName,
837
+ column
838
+ });
839
+ }
840
+ }
841
+ }
842
+ function refuseModelOwner(entry) {
843
+ if (entry.model.owner === void 0) return;
844
+ throw unsupported(`model "${entry.namespaceId}.${entry.name}" is owned by "${entry.model.owner}", which cannot be written in Prisma 8 PSL.`, "`owner` names the model this model is embedded in, and SQL PSL has no syntax for an owned model.", KEEP_SOURCE, {
845
+ namespaceId: entry.namespaceId,
846
+ modelName: entry.name,
847
+ owner: entry.model.owner
848
+ });
849
+ }
850
+ /**
851
+ * Refuses a multi-table variant whose link to its base differs from the one the PSL source derives:
852
+ * the base's primary key columns copied into the variant's table as its unnamed primary key, and
853
+ * the link foreign key.
854
+ */
855
+ function refuseUnderivedVariantLink(entry, variant) {
856
+ const baseKey = variant.base.table.primaryKey?.columns ?? [];
857
+ const derivedKey = baseKey.length === 0 ? void 0 : { columns: baseKey };
858
+ const linkColumnsMatch = variantLinkColumns(entry, variant).every((column) => {
859
+ const base = variant.base.table.columns[column];
860
+ const expected = base === void 0 ? void 0 : new StorageColumn({
861
+ dataType: base.dataType,
862
+ codecId: base.codecId,
863
+ nullable: false,
864
+ ...ifDefined("typeParams", base.typeParams)
865
+ });
866
+ return sameJson(entry.table.columns[column], expected);
867
+ });
868
+ const linkForeignKeys = entry.table.foreignKeys.filter((fk) => isVariantLinkForeignKey(fk, variant));
869
+ if (linkColumnsMatch && sameJson(entry.table.primaryKey, derivedKey) && linkForeignKeys.length === (baseKey.length === 0 ? 0 : 1)) return;
870
+ throw unsupported(`multi-table variant "${entry.namespaceId}.${entry.name}" is linked to its base "${variant.base.name}" differently from the link the PSL source derives, so it cannot be written in Prisma 8 PSL.`, "The PSL source links a multi-table variant to its base itself: it copies the base's primary key columns into the variant's table as its unnamed primary key, and adds an unnamed foreign key over them to the base that cascades on delete.", KEEP_SOURCE, {
871
+ namespaceId: entry.namespaceId,
872
+ modelName: entry.name
873
+ });
874
+ }
875
+ /**
876
+ * The PSL source groups relations by bare model name, so two models with the same name in
877
+ * different namespaces would get each other's relations.
878
+ */
879
+ function refuseDuplicateModelNames(models) {
880
+ const namespacesByName = /* @__PURE__ */ new Map();
881
+ for (const entry of models) {
882
+ const namespaces = namespacesByName.get(entry.name) ?? [];
883
+ namespaces.push(entry.namespaceId);
884
+ namespacesByName.set(entry.name, namespaces);
885
+ }
886
+ for (const [name, namespaces] of namespacesByName) {
887
+ if (namespaces.length <= 1) continue;
888
+ throw unsupported(`model "${name}" is declared in more than one namespace (${namespaces.join(", ")}), which Prisma 8 PSL cannot carry: the PSL source groups relations by bare model name.`, "The PSL source groups relations by bare model name, so when the file is read back the two models would get each other's relations.", "Rename one of the models, then print again.", {
889
+ modelName: name,
890
+ namespaces
891
+ });
892
+ }
893
+ }
894
+ /**
895
+ * A PSL `enum` block is declared at the top level and lands in the default namespace, so only the
896
+ * default namespace's domain enums have a PSL form.
897
+ */
898
+ function refuseEnumsOutsideDefaultNamespace(contract) {
899
+ for (const [namespaceId, domainNamespace] of Object.entries(contract.domain.namespaces)) {
900
+ const names = Object.keys(domainNamespace.enum ?? {});
901
+ if (namespaceId === "public" || names.length === 0) continue;
902
+ throw unsupported(`namespace "${namespaceId}" declares the enum${names.length === 1 ? "" : "s"} ${names.join(", ")}, which cannot be written in Prisma 8 PSL: an enum block is declared at the top level and belongs to the default namespace.`, "The PSL source refuses an enum block inside a namespace block, so an enum outside the default namespace has no PSL form.", "Move the enum to the default namespace, or keep authoring this contract in its current source.", {
903
+ namespaceId,
904
+ names
905
+ });
906
+ }
907
+ }
908
+ /** The PSL source reads every `type` block into the default namespace. */
909
+ function refuseValueObjectsOutsideDefaultNamespace(contract, namespaceId) {
910
+ const names = Object.keys(contract.domain.namespaces[namespaceId]?.valueObjects ?? {});
911
+ if (namespaceId === "public" || names.length === 0) return;
912
+ throw unsupported(`namespace "${namespaceId}" declares the value object${names.length === 1 ? "" : "s"} ${names.join(", ")}, which cannot be written in Prisma 8 PSL: the PSL source reads every value object into the default namespace.`, "A `type` block written in any namespace reads back into the default namespace, so the value object would move.", "Move the value object to the default namespace, or keep authoring this contract in its current source.", {
913
+ namespaceId,
914
+ names
915
+ });
916
+ }
917
+ /**
918
+ * Refuses a check or index whose name is neither its prefix followed by the hash of its content,
919
+ * which `name:` derives, nor free of a prefix, which `map:` needs.
920
+ */
921
+ function refuseUnwritableObjectName(input) {
922
+ const { kind, entry, name, prefix } = input;
923
+ throw unsupported(`${kind} "${name}" on "${entry.namespaceId}"."${entry.tableName}" has the prefix "${prefix}", but its name is not that prefix followed by the hash of its ${kind === "check" ? "expression" : "content"}, so it cannot be written in Prisma 8 PSL.`, `\`name:\` makes the PSL source derive the name from the prefix and that hash, and \`map:\` writes an exact name with no prefix, so neither reads back as this ${kind}.`, KEEP_SOURCE, {
924
+ namespaceId: entry.namespaceId,
925
+ table: entry.tableName,
926
+ name,
927
+ prefix
928
+ });
929
+ }
930
+ /**
931
+ * Refuses a table whose checks differ from the derived ones where they overlap: a derived check the
932
+ * table lacks, or a check with a derived check's name but not its prefix and expression. The PSL
933
+ * source adds the derived checks itself, so they are never written.
934
+ */
935
+ function refuseUnderivedChecks(entry, derived) {
936
+ const checks = new Map((entry.table.checks ?? []).map((check) => [check.name, check]));
937
+ for (const [name, expected] of derived) {
938
+ const check = checks.get(name);
939
+ if (check?.prefix === expected.prefix && check.expression === expected.expression) continue;
940
+ throw unsupported(`table "${entry.namespaceId}"."${entry.tableName}" ${check === void 0 ? "lacks" : "changes"} the check "${name}" the PSL source derives, so it cannot be written in Prisma 8 PSL.`, "The PSL source derives a membership check for each column of a managed table typed by an enum, and an element-not-null check for each list column whose elements are not nullable.", KEEP_SOURCE, {
941
+ namespaceId: entry.namespaceId,
942
+ table: entry.tableName,
943
+ name
944
+ });
945
+ }
946
+ }
947
+ /**
948
+ * Refuses index options PSL cannot write: `options:` takes string values under identifier keys,
949
+ * and requires a `type`.
950
+ */
951
+ function refuseUnwritableIndexOptions(entry, index) {
952
+ const meta = {
953
+ namespaceId: entry.namespaceId,
954
+ table: entry.tableName,
955
+ index: index.name
956
+ };
957
+ if (index.options !== void 0 && index.type === void 0) throw unsupported(`index "${index.name}" on "${entry.namespaceId}"."${entry.tableName}" has options but no type, which cannot be written in Prisma 8 PSL.`, "The PSL source reads `options:` on an index only together with `type:`.", "Give the index a type, or keep authoring this contract in its current source.", meta);
958
+ for (const [key, value] of Object.entries(index.options ?? {})) {
959
+ refuseUnwritableName("index option", key);
960
+ if (typeof value === "string") continue;
961
+ throw unsupported(`index "${index.name}" on "${entry.namespaceId}"."${entry.tableName}" has option "${key}" whose value is not a string, which cannot be written in Prisma 8 PSL.`, "The PSL `options:` argument takes string values only, and reads every value back as a string.", "Write the option value as a string, or keep authoring this contract in its current source.", {
962
+ ...meta,
963
+ key
964
+ });
965
+ }
966
+ }
967
+ function describeSqlTextOwner(owner) {
968
+ if (owner.kind === "default") return {
969
+ subject: `default of column ${owner.coordinate}`,
970
+ meta: { coordinate: owner.coordinate }
971
+ };
972
+ const { kind, namespaceId, table, name } = owner;
973
+ return {
974
+ subject: `${kind} "${name}" on "${namespaceId}"."${table}"`,
975
+ meta: kind === "policy" ? {
976
+ namespaceId,
977
+ table,
978
+ policy: name
979
+ } : {
980
+ namespaceId,
981
+ table,
982
+ name
983
+ }
984
+ };
985
+ }
986
+ /** Refuses an index, check, policy or column default whose SQL a `sql` literal cannot write back unchanged, because reading the literal canonicalizes it into different text. */
987
+ function refuseSqlTextThatDoesNotReadBack(input) {
988
+ if (sqlTextsReadBack(input.texts)) return;
989
+ const { subject, meta } = describeSqlTextOwner(input);
990
+ throw unsupported(`${subject} holds SQL that a sql literal cannot write back unchanged, so it cannot be written in Prisma 8 PSL.`, "A sql literal is canonicalized when it is read: indentation shared by every line, blank lines at the start or end, a carriage return and a whitespace-only line are removed, so this text would read back as different SQL.", "Write the SQL in that canonical form in the contract's source, or keep authoring this contract in its current source.", meta);
991
+ }
992
+ function refuseToOneRelationWithoutForeignKey(modelName, fieldName) {
993
+ throw unsupported(`relation "${modelName}.${fieldName}" has no foreign key in storage, which Prisma 8 PSL cannot express.`, "A to-one relation is authored as `@relation(fields:…, references:…)`, which always lowers to a foreign key.", "Declare a foreign key for the relation, or keep authoring this contract in its current source.", {
994
+ model: modelName,
995
+ field: fieldName
996
+ });
997
+ }
998
+ /**
999
+ * A foreign key backed by a primary key or unique constraint that only starts with its columns is written as the relation's `index: "<name>"`, which needs the key's name; the contract states none.
1000
+ */
1001
+ function refuseUnnamedForeignKeyBacking(modelName, fieldName) {
1002
+ throw unsupported(`relation "${modelName}.${fieldName}" is backed by a key with no name, which its @relation cannot name.`, "The key's first columns are the foreign key's, but it has more columns, so a relation that names nothing would get its own backing index instead.", "Give the key a name, or keep authoring this contract in its current source.", {
1003
+ model: modelName,
1004
+ field: fieldName
1005
+ });
1006
+ }
1007
+ /**
1008
+ * A foreign key no relation travels has no PSL form: the PSL source derives every foreign key from
1009
+ * a `@relation`, so this one would be lost.
1010
+ */
1011
+ function refuseUntravelledForeignKeys(entry, variant, travelled) {
1012
+ for (const fk of entry.table.foreignKeys) {
1013
+ if (travelled.has(fk) || isVariantLinkForeignKey(fk, variant)) continue;
1014
+ if (variant?.singleTable === true && !fk.source.columns.every((c) => entry.ownColumns.has(c))) continue;
1015
+ throw unsupported(`table "${entry.namespaceId}"."${entry.tableName}" has a foreign key on (${fk.source.columns.join(", ")}) that no relation of model "${entry.name}" travels, which cannot be written in Prisma 8 PSL.`, "The PSL source derives every foreign key from a `@relation` field; a foreign key without one has no PSL form.", "Declare a relation over the foreign key, or keep authoring this contract in its current source.", {
1016
+ namespaceId: entry.namespaceId,
1017
+ table: entry.tableName,
1018
+ columns: fk.source.columns
1019
+ });
1020
+ }
1021
+ }
1022
+ function refuseRelationToOtherContractSpace(input) {
1023
+ if (input.space === void 0) return;
1024
+ throw unsupported(`relation "${input.modelName}.${input.fieldName}" targets model "${input.targetModel}" in contract space "${input.space}", which contract print cannot write yet.`, "The printer writes relations between models of this contract only.", KEEP_SOURCE, {
1025
+ model: input.modelName,
1026
+ field: input.fieldName,
1027
+ space: input.space
1028
+ });
1029
+ }
1030
+ function refuseManyToManyWithoutJunctionRelation(modelName, fieldName) {
1031
+ throw unsupported(`many-to-many relation "${modelName}.${fieldName}" goes through a table whose model has no relation back to "${modelName}", so it cannot be written in Prisma 8 PSL.`, "PSL writes a many-to-many list field through the relations of the junction model, one to each side.", "Declare a model for the junction table with a relation to each side, or keep authoring this contract in its current source.", {
1032
+ model: modelName,
1033
+ field: fieldName
1034
+ });
1035
+ }
1036
+ function refuseBackRelationWithoutOwningRelation(input) {
1037
+ throw unsupported(`relation "${input.modelName}.${input.fieldName}" has no foreign key of its own, and model "${input.targetModel}" has no relation back to "${input.modelName}" over the same columns, so it cannot be written in Prisma 8 PSL.`, "The PSL source reads a relation field without `fields:` and `references:` only as the other side of a relation field that has them.", `Declare the relation on "${input.targetModel}" that holds the foreign key, or keep authoring this contract in its current source.`, {
1038
+ model: input.modelName,
1039
+ field: input.fieldName
1040
+ });
1041
+ }
1042
+ function refuseRelationWithoutJoin(modelName, fieldName) {
1043
+ throw unsupported(`relation "${modelName}.${fieldName}" names no fields to join on, which cannot be written in Prisma 8 PSL.`, "The PSL source reads every relation as a join between fields of the two models; a relation with no `on` part has no PSL form.", KEEP_SOURCE, {
1044
+ model: modelName,
1045
+ field: fieldName
1046
+ });
1047
+ }
1048
+ /**
1049
+ * Refuses a namespace whose value sets differ from the ones the PSL source derives from the enum
1050
+ * and `native_enum` blocks the printer writes for it.
1051
+ */
1052
+ function refuseUnderivedValueSets(input) {
1053
+ const { namespaceId } = input;
1054
+ for (const [name, values] of input.actual) {
1055
+ const derived = input.derived.get(name);
1056
+ if (derived !== void 0 && sameValues$1(derived, values)) continue;
1057
+ throw unsupported(`value set "${name}" in namespace "${namespaceId}" is not the value set of an enum or native enum of that name holding exactly its values, so it cannot be written in Prisma 8 PSL.`, "The PSL source derives each value set from an `enum` or `native_enum` block, named after the block and holding its members.", KEEP_SOURCE, {
1058
+ namespaceId,
1059
+ name
1060
+ });
1061
+ }
1062
+ for (const name of input.derived.keys()) {
1063
+ if (input.actual.has(name)) continue;
1064
+ throw unsupported(`enum "${name}" in namespace "${namespaceId}" has no value set holding its members, which cannot be written in Prisma 8 PSL.`, "The PSL source derives a value set from every enum, so the file would read back with a value set this contract does not have.", KEEP_SOURCE, {
1065
+ namespaceId,
1066
+ name
1067
+ });
1068
+ }
1069
+ }
1070
+ function refuseEnumAndNativeEnumSharingName(namespaceId, name) {
1071
+ throw unsupported(`enum "${name}" and a native enum written under the same name both derive the value set "${name}" in namespace "${namespaceId}", which cannot be written in Prisma 8 PSL.`, "The PSL source refuses one name declared both as an enum and as a native enum.", KEEP_SOURCE, {
1072
+ namespaceId,
1073
+ name
1074
+ });
1075
+ }
1076
+ function refuseNativeEnumWithoutValueSet(namespaceId, nativeEnum) {
1077
+ throw unsupported(`native enum "${nativeEnum.typeName}" in namespace "${namespaceId}" has no value set holding its members, which cannot be written in Prisma 8 PSL.`, "The PSL source derives a value set from every `native_enum` block, named after the block and holding its members, so the file would read back with a value set this contract does not have.", KEEP_SOURCE, {
1078
+ namespaceId,
1079
+ typeName: nativeEnum.typeName
1080
+ });
1081
+ }
1082
+ function refuseNativeEnumControl(namespaceId, nativeEnum) {
1083
+ if (nativeEnum.control === void 0) return;
1084
+ throw unsupported(`native enum "${nativeEnum.typeName}" in namespace "${namespaceId}" carries its own control policy "${nativeEnum.control}", which cannot be written in Prisma 8 PSL.`, "A `native_enum` block has no control attribute.", "Drop the policy from the enum, or keep authoring this contract in its current source.", {
1085
+ namespaceId,
1086
+ typeName: nativeEnum.typeName,
1087
+ control: nativeEnum.control
1088
+ });
1089
+ }
1090
+ /**
1091
+ * Refuses a storage or domain namespace the PSL source would not create again: one holding nothing
1092
+ * the printer writes. The PSL source creates the default namespace in both planes, a storage
1093
+ * namespace for every namespace block it writes into, and a domain namespace for each namespace
1094
+ * with models.
1095
+ */
1096
+ function refuseUnwrittenNamespaces(input) {
1097
+ const { contract } = input;
1098
+ const storageNamespaces = /* @__PURE__ */ new Set([DEFAULT_NAMESPACE_ID, ...input.writtenStorageNamespaces]);
1099
+ const defaultDomain = contract.domain.namespaces[DEFAULT_NAMESPACE_ID];
1100
+ const domainNamespaces = new Set(input.models.map((entry) => entry.namespaceId));
1101
+ if (domainNamespaces.size === 0 || Object.keys(defaultDomain?.valueObjects ?? {}).length > 0 || Object.keys(defaultDomain?.enum ?? {}).length > 0) domainNamespaces.add(DEFAULT_NAMESPACE_ID);
1102
+ const planes = [{
1103
+ plane: "storage",
1104
+ expected: storageNamespaces,
1105
+ actual: Object.keys(contract.storage.namespaces)
1106
+ }, {
1107
+ plane: "domain",
1108
+ expected: domainNamespaces,
1109
+ actual: Object.keys(contract.domain.namespaces)
1110
+ }];
1111
+ for (const { plane, expected, actual } of planes) {
1112
+ for (const namespaceId of actual) {
1113
+ if (expected.has(namespaceId)) continue;
1114
+ throw unsupported(`${plane} namespace "${namespaceId}" holds nothing Prisma 8 PSL writes, so it would not read back.`, "The PSL source creates a namespace only for what is written in it.", "Remove the empty namespace, or keep authoring this contract in its current source.", {
1115
+ plane,
1116
+ namespaceId
1117
+ });
1118
+ }
1119
+ for (const namespaceId of expected) {
1120
+ if (actual.includes(namespaceId)) continue;
1121
+ throw unsupported(`the contract has no ${plane} namespace "${namespaceId}", which the PSL source would create.`, "The PSL source always creates the default namespace, and a namespace for everything it writes.", KEEP_SOURCE, {
1122
+ plane,
1123
+ namespaceId
1124
+ });
1125
+ }
1126
+ }
1127
+ }
1128
+ /**
1129
+ * Refuses a namespace named `unbound` that is not the late-binding namespace: PSL writes the
1130
+ * late-binding namespace as `namespace unbound`, so a block of that name reads back as it.
1131
+ */
1132
+ function refuseNamespaceNamedUnbound(namespaceId) {
1133
+ if (namespaceId !== UNBOUND_PSL_NAMESPACE_NAME) return;
1134
+ throw unsupported(`namespace "${namespaceId}" cannot be written in Prisma 8 PSL, because \`namespace ${UNBOUND_PSL_NAMESPACE_NAME}\` is how PSL writes the late-binding namespace.`, `The PSL source reads \`namespace ${UNBOUND_PSL_NAMESPACE_NAME}\` as the late-binding namespace "${UNBOUND_NAMESPACE_ID}", so everything in this namespace would move there.`, "Rename the namespace, or keep authoring this contract in its current source.", { namespaceId });
1135
+ }
1136
+ /** Refuses top-level `meta` entries: the PSL source reads back an empty `meta`. */
1137
+ /** Refuses a contract that registers database types in `storage.types`: only an extension's contract space does, and PSL has no syntax to declare one. */
1138
+ function refuseRegisteredDatabaseTypes(contract) {
1139
+ const types = Object.keys(contract.storage.types ?? {}).sort();
1140
+ if (types.length === 0) return;
1141
+ throw unsupported(`This contract registers the database types ${types.join(", ")}, which PSL cannot declare. It is an extension's contract space, written in TypeScript.`, "Printing it would drop the registered types and change its storage hash.", "Keep authoring this contract space in TypeScript.", { types });
1142
+ }
1143
+ function refuseContractMeta(contract) {
1144
+ const keys = Object.keys(contract.meta);
1145
+ if (keys.length === 0) return;
1146
+ throw unsupported(`the contract carries meta entries (${keys.join(", ")}), which cannot be written in Prisma 8 PSL.`, "The PSL source writes no top-level meta, so the file would read back with an empty meta.", KEEP_SOURCE, { keys });
1147
+ }
1148
+ /**
1149
+ * Refuses roots that differ from the ones the PSL source derives: one per model that is not a
1150
+ * variant, keyed by its table name, or by `<namespace>.<table>` when two such models share a table
1151
+ * name.
1152
+ */
1153
+ function refuseUnderivedRoots(contract, models, variants) {
1154
+ const tableEntries = models.filter((entry) => variants.get(entry)?.singleTable !== true);
1155
+ const tableNameCounts = /* @__PURE__ */ new Map();
1156
+ for (const entry of tableEntries) tableNameCounts.set(entry.tableName, (tableNameCounts.get(entry.tableName) ?? 0) + 1);
1157
+ const derived = /* @__PURE__ */ new Map();
1158
+ for (const entry of tableEntries) {
1159
+ if (variants.get(entry) !== void 0) continue;
1160
+ const key = (tableNameCounts.get(entry.tableName) ?? 0) > 1 ? `${entry.namespaceId}.${entry.tableName}` : entry.tableName;
1161
+ derived.set(key, entry);
1162
+ }
1163
+ const refuse = (root) => unsupported(`root "${root}" is not a root the PSL source derives, so the contract's roots cannot be written in Prisma 8 PSL.`, "The PSL source derives one root per model that is not a variant, keyed by its table name.", KEEP_SOURCE, { root });
1164
+ for (const [root, reference] of Object.entries(contract.roots)) {
1165
+ const entry = derived.get(root);
1166
+ if (entry === void 0 || reference.space !== void 0 || reference.namespace !== entry.namespaceId || reference.model !== entry.name) throw refuse(root);
1167
+ }
1168
+ for (const root of derived.keys()) if (!Object.hasOwn(contract.roots, root)) throw refuse(root);
1169
+ }
1170
+ function refuseRlsWithoutModel(namespaceId, tableName) {
1171
+ throw unsupported(`table "${namespaceId}"."${tableName}" has row-level security enabled but no model, so it cannot be written in Prisma 8 PSL.`, "Row-level security is written as `@@rls` on the model stored in the table.", "Declare a model for the table, or keep authoring this contract in its current source.", {
1172
+ namespaceId,
1173
+ table: tableName
1174
+ });
1175
+ }
1176
+ function unwritablePolicy(policy, why, fix) {
1177
+ return unsupported(`policy "${policy.name}" on "${policy.namespaceId}"."${policy.tableName}" cannot be written in Prisma 8 PSL.`, why, fix, {
1178
+ namespaceId: policy.namespaceId,
1179
+ table: policy.tableName,
1180
+ name: policy.name
1181
+ });
1182
+ }
1183
+ function refusePolicyWithoutModel(policy) {
1184
+ throw unwritablePolicy(policy, "A policy block names its table through the model stored there, and no model is stored in this table.", "Declare a model for the table, or keep authoring this contract in its current source.");
1185
+ }
1186
+ function refusePolicyWithoutRls(policy) {
1187
+ throw unwritablePolicy(policy, "The PSL source reads a policy only on a model that declares `@@rls`, and this table does not have row-level security enabled.", "Enable row-level security on the table, or keep authoring this contract in its current source.");
1188
+ }
1189
+ function refusePolicyNameNotDerived(policy) {
1190
+ throw unwritablePolicy(policy, "The PSL source names a wire-named policy by its block name and the hash of its content, and this name is not that.", KEEP_SOURCE);
1191
+ }
1192
+ /** Refuses a role outside the unbound namespace: the PSL source reads a `role` block only there. */
1193
+ function refuseRoleOutsideUnbound(namespaceId, name) {
1194
+ if (namespaceId === UNBOUND_NAMESPACE_ID) return;
1195
+ throw unsupported(`role "${name}" is declared in namespace "${namespaceId}", and Prisma 8 PSL declares a role only in the unbound namespace.`, "The PSL source reads a `role` block only inside `namespace unbound`, because roles belong to the whole database.", "Declare the role in the unbound namespace, or keep authoring this contract in its current source.", {
1196
+ namespaceId,
1197
+ name
1198
+ });
1199
+ }
1200
+ const FILED_UNDER = {
1201
+ rls: "The PSL source files the row-level security setting written as `@@rls` under the name of the table.",
1202
+ role: "The PSL source files a role under the name its block is written with."
1203
+ };
1204
+ /** Refuses a row-level security setting or role filed under a key the PSL source would not use. */
1205
+ function refuseEntryFiledUnderAnotherName(input) {
1206
+ if (input.name === input.readsBackAs) return;
1207
+ throw unsupported(`namespace "${input.namespaceId}" has a "${input.kind}" entry "${input.name}" that would read back as "${input.readsBackAs}", so it cannot be written in Prisma 8 PSL.`, FILED_UNDER[input.kind], KEEP_SOURCE, {
1208
+ namespaceId: input.namespaceId,
1209
+ kind: input.kind,
1210
+ name: input.name
1211
+ });
1212
+ }
1213
+ /** Refuses an entry that records a namespace other than the one it is stored in. */
1214
+ function refuseEntryInOtherNamespace(input) {
1215
+ if (input.recordedNamespaceId === input.namespaceId) return;
1216
+ throw unsupported(`the "${input.kind}" entry "${input.name}" is stored in namespace "${input.namespaceId}" but records namespace "${input.recordedNamespaceId}", so it cannot be written in Prisma 8 PSL.`, "The PSL source records the namespace a block is written in, so the entry would read back with the namespace it is stored in.", "The contract source produced an entry that disagrees with its namespace. Fix the entry if the source is a TypeScript contract; otherwise report the bug to the source that produced it.", {
1217
+ namespaceId: input.namespaceId,
1218
+ kind: input.kind,
1219
+ name: input.name
1220
+ });
1221
+ }
1222
+ function refuseNameThePslSourceLoses(kind, name) {
1223
+ if (name !== NAME_THE_PSL_SOURCE_LOSES) return;
1224
+ throw unsupported(`${kind} "${name}" cannot be written in Prisma 8 PSL, because the PSL source loses this name when it reads it.`, "The PSL source keeps names as keys of plain objects, where this name sets the prototype instead of adding a key.", "Rename it, or keep authoring this contract in its current source.", {
1225
+ kind,
1226
+ name
1227
+ });
1228
+ }
1229
+ /**
1230
+ * Refuses a table or column named `__proto__`, which the printer would write inside `@@map` or
1231
+ * `@map` and the PSL source loses when it reads it.
1232
+ */
1233
+ function refuseUnwritableMappedName(kind, name) {
1234
+ refuseNameThePslSourceLoses(kind, name);
1235
+ }
1236
+ /**
1237
+ * Refuses a name the printer writes where PSL reads an identifier: a namespace, model, field, value
1238
+ * object, enum, enum member, native enum, policy, role or index option key.
1239
+ */
1240
+ function refuseUnwritableName(kind, name) {
1241
+ refuseNameThePslSourceLoses(kind, name);
1242
+ if (isPslIdentifier(name)) return;
1243
+ throw unsupported(`${kind} "${name}" is not a PSL identifier, so it cannot be written in Prisma 8 PSL.`, "PSL writes this name as an identifier: a letter or underscore, then letters, ASCII digits, underscores or hyphens, other than the number words `NaN` and `Infinity`.", "Rename it to an identifier, or keep authoring this contract in its current source.", {
1244
+ kind,
1245
+ name
1246
+ });
1247
+ }
1248
+ /** The storage entry kinds the printer writes; any other kind is refused, whichever component defines it. */
1249
+ const PRINTED_ENTRY_KINDS = /* @__PURE__ */ new Set([
1250
+ "table",
1251
+ "valueSet",
1252
+ "native_enum",
1253
+ "rls",
1254
+ "policy",
1255
+ "role"
1256
+ ]);
1257
+ function refuseUnprintedEntryKinds(namespaceId, entries) {
1258
+ for (const [kind, entities] of Object.entries(entries)) {
1259
+ if (PRINTED_ENTRY_KINDS.has(kind)) continue;
1260
+ const names = Object.keys(entities ?? {});
1261
+ if (names.length === 0) continue;
1262
+ throw unsupported(`namespace "${namespaceId}" declares ${names.length} "${kind}" ${names.length === 1 ? "entity" : "entities"} (${names.join(", ")}), which the Postgres printer cannot write.`, "The printer writes tables, value sets, native enums, row-level security settings, policies and roles, and no other entity kind.", KEEP_SOURCE, {
1263
+ namespaceId,
1264
+ kind,
1265
+ names
1266
+ });
1267
+ }
1268
+ }
1269
+ /** The name of the column's data type without parameters. */
1270
+ function baseTypeName(column, dataTypeLookup, coordinate) {
1271
+ const dataType = dataTypeLookup.get(column.dataType);
1272
+ if (dataType === void 0 || !isSqlDataType(dataType)) return refuseColumnWithoutPslType(column, coordinate);
1273
+ return unquotedSqlBaseName(dataType, dataTypeParams(dataType, column.typeParams));
1274
+ }
1275
+ /** The arguments of `call` as PSL writes them, each a literal of its data type that reads back as the argument. */
1276
+ function typeArgumentTexts(call, authoringTypes, dataTypes, coordinate) {
1277
+ const descriptor = getAuthoringTypeConstructor({ type: authoringTypes }, call.path);
1278
+ return (descriptor && writtenTypeArguments(descriptor, call.args, dataTypes)) ?? refuseUnwritableTypeArgument(call, coordinate);
1279
+ }
1280
+ function typeCall(path, args) {
1281
+ const name = path.join(".");
1282
+ const isNamespaced = path.length > 1;
1283
+ if (args.length === 0 && !isNamespaced) return {
1284
+ kind: "dataType",
1285
+ typeName: name
1286
+ };
1287
+ return {
1288
+ kind: "dataType",
1289
+ typeName: name,
1290
+ typeConstructor: {
1291
+ kind: "typeConstructor",
1292
+ path,
1293
+ args: args.map(positionalArg),
1294
+ span: SYNTHETIC_SPAN
1295
+ }
1296
+ };
1297
+ }
1298
+ /**
1299
+ * The call to the constructor marked `inferred` for the column's data type, the one `contract
1300
+ * infer` writes, when it produces exactly the column's codec and type parameters.
1301
+ */
1302
+ function inferredConstructorCall(column, inferredConstructors) {
1303
+ const marked = inferredConstructors.get(column.dataType);
1304
+ const args = marked && authoringTypeConstructorArguments(marked.descriptor, column);
1305
+ return marked && args && {
1306
+ path: marked.path,
1307
+ args
1308
+ };
1309
+ }
1310
+ /**
1311
+ * The PSL type position for a storage column: a call to a type constructor the configured stack
1312
+ * contributes that produces exactly the column's codec, native type and type parameters. The
1313
+ * constructor `contract infer` writes for the column's data type comes first; otherwise
1314
+ * the first one in the stack that produces them, such as `DateTime` for a `timestamptz` column read
1315
+ * as a `Temporal.Instant`, or `pgvector.Vector(3)`. An enum-typed column takes the
1316
+ * `pg.enum(<Block>)` constructor, named after the value set the column points at; a column typed by
1317
+ * a domain enum takes that enum's name. A column no PSL type reads back is refused.
1318
+ */
1319
+ function buildColumnType(input) {
1320
+ const { column, inferredConstructors, authoringTypes, enumBlockNames, coordinate } = input;
1321
+ const baseName = baseTypeName(column, input.dataTypes.lookup, coordinate);
1322
+ const enumBlockName = column.valueSet?.entityName ?? enumBlockNames.get(baseName);
1323
+ if (column.codecId === "pg/enum@1" && enumBlockName !== void 0) return {
1324
+ kind: "enum",
1325
+ typeName: enumBlockName,
1326
+ typeConstructor: {
1327
+ kind: "typeConstructor",
1328
+ path: ["pg", "enum"],
1329
+ args: [positionalArg(column.valueSet !== void 0 && column.valueSet.namespaceId !== input.namespaceId ? `${column.valueSet.namespaceId}.${enumBlockName}` : enumBlockName)],
1330
+ span: SYNTHETIC_SPAN
1331
+ }
1332
+ };
1333
+ const domainEnumName = column.valueSet?.entityName;
1334
+ if (domainEnumName !== void 0) return {
1335
+ kind: "enum",
1336
+ typeName: domainEnumName
1337
+ };
1338
+ const call = inferredConstructorCall(column, inferredConstructors) ?? findAuthoringTypeConstructorCall(authoringTypes, column);
1339
+ if (call !== void 0) return typeCall(call.path, typeArgumentTexts(call, authoringTypes, input.dataTypes, coordinate));
1340
+ refuseColumnWithoutPslType(column, coordinate);
1341
+ }
1342
+ /**
1343
+ * The data type a value-object member's codec represents, after checking the member's type
1344
+ * parameters against it. A member has no column of its own.
1345
+ */
1346
+ function dataTypeOfMember(type, coordinate, context) {
1347
+ const { codecId } = type;
1348
+ const descriptor = context.codecLookup.descriptorFor(codecId);
1349
+ if (descriptor === void 0) refuseMemberCodecWithoutNativeType(codecId, coordinate);
1350
+ const dataType = context.dataTypes.lookup.get(descriptor.dataType);
1351
+ if (dataType === void 0 || !isSqlDataType(dataType)) refuseMemberCodecWithoutNativeType(codecId, coordinate);
1352
+ const typeParams = nonEmptyTypeParams(type.typeParams);
1353
+ if (typeParams === void 0) {
1354
+ if (requiredParamKeys(dataType).length > 0) refuseMemberCodecNeedingTypeParameters(codecId, coordinate);
1355
+ return dataType.id;
1356
+ }
1357
+ validateCodecTypeParams(descriptor, {
1358
+ codecId,
1359
+ typeParams: blindCast(typeParams)
1360
+ });
1361
+ return dataType.id;
1362
+ }
1363
+ /** The PSL type position of a value-object member: a value object or an enum by name, or a scalar as a column would print. */
1364
+ function buildMemberType(input) {
1365
+ const { field, coordinate } = input;
1366
+ refuseUnwritableFieldShape(field, coordinate);
1367
+ const { type } = field;
1368
+ if (type.kind === "valueObject") return {
1369
+ kind: "valueObject",
1370
+ typeName: type.name
1371
+ };
1372
+ refuseUnderivedMemberValueSet({
1373
+ field,
1374
+ type,
1375
+ coordinate,
1376
+ domainEnums: input.domainEnums
1377
+ });
1378
+ if (field.valueSet !== void 0) return {
1379
+ kind: "enum",
1380
+ typeName: field.valueSet.entityName
1381
+ };
1382
+ return buildColumnType({
1383
+ column: new StorageColumn({
1384
+ dataType: dataTypeOfMember(type, coordinate, input.context),
1385
+ codecId: type.codecId,
1386
+ nullable: field.nullable,
1387
+ ...ifDefined("many", field.many),
1388
+ ...ifDefined("typeParams", type.typeParams)
1389
+ }),
1390
+ inferredConstructors: input.inferredConstructors,
1391
+ authoringTypes: input.context.authoringContributions.type,
1392
+ dataTypes: input.context.dataTypes,
1393
+ enumBlockNames: input.enumBlockNames,
1394
+ coordinate
1395
+ });
1396
+ }
1397
+ /** The `type` blocks of one namespace, one per value object the domain declares there. */
1398
+ function buildCompositeTypes(input) {
1399
+ refuseValueObjectsOutsideDefaultNamespace(input.contract, input.namespaceId);
1400
+ const valueObjects = input.contract.domain.namespaces[input.namespaceId]?.valueObjects ?? {};
1401
+ return Object.entries(valueObjects).map(([name, valueObject]) => {
1402
+ refuseUnwritableName("value object", name);
1403
+ return {
1404
+ kind: "compositeType",
1405
+ name,
1406
+ fields: Object.entries(valueObject.fields).map(([fieldName, field]) => {
1407
+ refuseUnwritableName("field", fieldName);
1408
+ const { typeName, typeConstructor } = buildMemberType({
1409
+ field,
1410
+ coordinate: `"${input.namespaceId}".${name}.${fieldName}`,
1411
+ inferredConstructors: input.inferredConstructors,
1412
+ context: input.context,
1413
+ enumBlockNames: input.enumBlockNames,
1414
+ domainEnums: input.domainEnums
1415
+ });
1416
+ return {
1417
+ kind: "field",
1418
+ name: fieldName,
1419
+ typeName,
1420
+ ...ifDefined("typeConstructor", typeConstructor),
1421
+ optional: field.nullable,
1422
+ list: !!field.many,
1423
+ elementOptional: !!field.many && field.many.elementNullable,
1424
+ attributes: [],
1425
+ span: SYNTHETIC_SPAN
1426
+ };
1427
+ }),
1428
+ attributes: [],
1429
+ span: SYNTHETIC_SPAN
1430
+ };
1431
+ });
1432
+ }
1433
+ /**
1434
+ * One `enum <name> { … }` block per domain enum, each member written as `Name = <value>` under
1435
+ * `@@type`. The PSL source reads a member as a written value of the enum codec's data type, so each
1436
+ * member is written as the PSL literal that type reads back as the stored value, as a default is.
1437
+ */
1438
+ function buildDomainEnumBlocks(enums, context) {
1439
+ return Object.entries(enums).map(([name, domainEnum]) => {
1440
+ refuseUnwritableName("enum", name);
1441
+ return {
1442
+ kind: "enum",
1443
+ keyword: "enum",
1444
+ name,
1445
+ parameters: Object.fromEntries(domainEnum.members.map((member) => {
1446
+ refuseUnwritableName("enum member", member.name);
1447
+ const written = writeDefaultLiteral(member.value, {
1448
+ dataTypes: context.dataTypes,
1449
+ columnCodec: context.codecLookup.descriptorFor(domainEnum.codecId)
1450
+ });
1451
+ if (written === void 0) refuseUnwritableEnumMember({
1452
+ enumName: name,
1453
+ member: member.name,
1454
+ value: member.value
1455
+ });
1456
+ return [member.name, {
1457
+ expression: written,
1458
+ span: SYNTHETIC_SPAN
1459
+ }];
1460
+ })),
1461
+ blockAttributes: [{
1462
+ name: "type",
1463
+ args: [{
1464
+ kind: "positional",
1465
+ value: `"${escapePslString(domainEnum.codecId)}"`,
1466
+ span: SYNTHETIC_SPAN
1467
+ }],
1468
+ span: SYNTHETIC_SPAN
1469
+ }],
1470
+ span: SYNTHETIC_SPAN
1471
+ };
1472
+ });
1473
+ }
1474
+ function sameValues(left, right) {
1475
+ return left.length === right.length && left.every((value, index) => value === right[index]);
1476
+ }
1477
+ /**
1478
+ * Builds one `native_enum` block per enum type a namespace declares.
1479
+ *
1480
+ * A contract keys a native enum by its type name and keys the value set it
1481
+ * derives by the name the schema gave the enum, and the PSL source derives
1482
+ * that value set from the block, named after the block. So the block is named
1483
+ * after the enum's value set: the value set a column typed by the enum names;
1484
+ * else, for an enum no column refers to, the unclaimed value set with the
1485
+ * enum's own name that holds exactly its members, or else the first unclaimed
1486
+ * one that does. An enum with no such value set is refused. `@@map` carries
1487
+ * the type name whenever it differs from the block name.
1488
+ */
1489
+ function buildNativeEnumBlocksForNamespace(input) {
1490
+ const valueSetNamesByTypeName = /* @__PURE__ */ new Map();
1491
+ for (const column of input.columns) {
1492
+ const valueSetName = column.valueSet?.entityName;
1493
+ const typeName = column.typeParams?.["typeName"];
1494
+ if (valueSetName === void 0 || typeof typeName !== "string") continue;
1495
+ valueSetNamesByTypeName.set(typeName, valueSetName);
1496
+ }
1497
+ const claimed = new Set(valueSetNamesByTypeName.values());
1498
+ const unreferenced = [];
1499
+ const nameByEntry = /* @__PURE__ */ new Map();
1500
+ for (const [entryName, nativeEnum] of input.nativeEnums) {
1501
+ refuseNativeEnumControl(input.namespaceId, nativeEnum);
1502
+ const { typeName } = nativeEnum;
1503
+ const fromColumn = valueSetNamesByTypeName.get(typeName) ?? valueSetNamesByTypeName.get(`${input.namespaceId}.${typeName}`);
1504
+ if (fromColumn === void 0) {
1505
+ unreferenced.push({
1506
+ entryName,
1507
+ nativeEnum
1508
+ });
1509
+ continue;
1510
+ }
1511
+ nameByEntry.set(entryName, fromColumn);
1512
+ }
1513
+ for (const { entryName, nativeEnum } of unreferenced) {
1514
+ const candidates = [...input.valueSets].filter(([name, values]) => !claimed.has(name) && sameValues(values, nativeEnum.members)).map(([name]) => name);
1515
+ const chosen = candidates.find((name) => name === entryName) ?? candidates[0];
1516
+ if (chosen === void 0) refuseNativeEnumWithoutValueSet(input.namespaceId, nativeEnum);
1517
+ claimed.add(chosen);
1518
+ nameByEntry.set(entryName, chosen);
1519
+ }
1520
+ const blocks = [];
1521
+ const blockNamesByTypeName = /* @__PURE__ */ new Map();
1522
+ const derivedValueSets = /* @__PURE__ */ new Map();
1523
+ for (const [entryName, nativeEnum] of input.nativeEnums) {
1524
+ const { typeName } = nativeEnum;
1525
+ const blockName = nameByEntry.get(entryName) ?? typeName;
1526
+ refuseUnwritableName("native enum", blockName);
1527
+ blocks.push(buildNativeEnumBlock(blockName, typeName, nativeEnum.members));
1528
+ blockNamesByTypeName.set(typeName, blockName);
1529
+ blockNamesByTypeName.set(`${input.namespaceId}.${typeName}`, blockName);
1530
+ derivedValueSets.set(blockName, nativeEnum.members);
1531
+ }
1532
+ return {
1533
+ blocks,
1534
+ blockNamesByTypeName,
1535
+ derivedValueSets
1536
+ };
1537
+ }
1538
+ /**
1539
+ * The checks the PSL source derives itself for a table, keyed by name, so
1540
+ * they are not also written as `@@check`. A table that is not managed derives
1541
+ * none. A managed one derives a membership check for each column typed by a
1542
+ * domain enum and an element-not-null check for each list column whose
1543
+ * elements are not nullable.
1544
+ */
1545
+ function derivedChecks(input) {
1546
+ const checks = /* @__PURE__ */ new Map();
1547
+ if (!input.managed) return checks;
1548
+ for (const [columnName, column] of Object.entries(input.table.columns)) {
1549
+ const enumValues = column.codecId === "pg/enum@1" || column.valueSet === void 0 ? void 0 : input.domainEnumValues.get(column.valueSet.entityName);
1550
+ const memberValues = enumValues?.filter((value) => typeof value === "string" || typeof value === "number");
1551
+ for (const candidate of postgresRenderCheckExpressions({
1552
+ tableName: input.tableName,
1553
+ columnName,
1554
+ many: column.many,
1555
+ memberValues: memberValues?.length === enumValues?.length ? memberValues : void 0
1556
+ })) {
1557
+ const prefix = composeCheckWirePrefix(input.tableName, columnName, candidate.kind);
1558
+ checks.set(formatWireName(prefix, computeCheckContentHash(candidate.expression)), {
1559
+ prefix,
1560
+ expression: candidate.expression
1561
+ });
1562
+ }
1563
+ }
1564
+ return checks;
1565
+ }
1566
+ /**
1567
+ * Whether a table object belongs to this model when several models share the
1568
+ * table: a single-table variant owns what lies within its own columns, and the
1569
+ * base owns the rest.
1570
+ */
1571
+ function ownsTableObject(entry, variant, singleTableVariants, columns) {
1572
+ if (variant?.singleTable === true) return columns?.every((column) => entry.ownColumns.has(column)) === true;
1573
+ return !singleTableVariants.some((other) => columns?.every((column) => other.ownColumns.has(column)) === true);
1574
+ }
1575
+ /**
1576
+ * How a check or index is named in PSL: `name:` with its prefix when the name
1577
+ * is that prefix and the hash of its content, which the PSL source derives
1578
+ * again; `map:` when it has no prefix. A prefix whose name is anything else is
1579
+ * refused, because neither form reads back as it.
1580
+ */
1581
+ function attributeNaming(input) {
1582
+ const { kind, entry, name, prefix } = input;
1583
+ if (prefix === void 0) return { kind: "exact" };
1584
+ if (formatWireName(prefix, input.contentHash()) === name) return {
1585
+ kind: "wire",
1586
+ prefix
1587
+ };
1588
+ refuseUnwritableObjectName({
1589
+ kind,
1590
+ entry,
1591
+ name,
1592
+ prefix
1593
+ });
1594
+ }
1595
+ /**
1596
+ * The `@@` attributes of one model: its polymorphism, its keys, checks and indexes, its control
1597
+ * policy, `@@rls` and `@@map`. A table object several models share goes on the model that owns it.
1598
+ */
1599
+ function buildModelAttributes(input) {
1600
+ const { entry, variant, singleTableVariants, derivedChecksByName } = input;
1601
+ const attributes = [];
1602
+ const fieldNameOf = (column) => entry.fieldNamesByColumn.get(column) ?? column;
1603
+ const owns = (columns) => ownsTableObject(entry, variant, singleTableVariants, columns);
1604
+ if (entry.model.discriminator !== void 0) attributes.push(buildAttribute("model", "discriminator", [positionalArg(entry.model.discriminator.field)]));
1605
+ if (variant !== void 0) attributes.push(buildAttribute("model", "base", [positionalArg(variant.base.namespaceId === entry.namespaceId ? variant.base.name : `${pslNamespaceName(variant.base.namespaceId)}.${variant.base.name}`), positionalArg(`"${escapePslString(variant.value)}"`)]));
1606
+ const primaryKeyColumns = variant === void 0 ? entry.table.primaryKey?.columns ?? [] : [];
1607
+ if (primaryKeyColumns.length > 1) attributes.push(buildModelConstraintAttribute("id", primaryKeyColumns.map(fieldNameOf), entry.table.primaryKey?.name));
1608
+ for (const unique of entry.table.uniques) {
1609
+ if (!owns(unique.columns)) continue;
1610
+ attributes.push(buildModelConstraintAttribute("unique", unique.columns.map(fieldNameOf), unique.name));
1611
+ }
1612
+ for (const check of entry.table.checks ?? []) {
1613
+ if (derivedChecksByName.has(check.name) || !owns(void 0)) continue;
1614
+ refuseSqlTextThatDoesNotReadBack({
1615
+ kind: "check",
1616
+ namespaceId: entry.namespaceId,
1617
+ table: entry.tableName,
1618
+ name: check.name,
1619
+ texts: [check.expression]
1620
+ });
1621
+ attributes.push(buildCheckAttribute(check, attributeNaming({
1622
+ kind: "check",
1623
+ entry,
1624
+ name: check.name,
1625
+ prefix: check.prefix,
1626
+ contentHash: () => computeCheckContentHash(check.expression)
1627
+ })));
1628
+ }
1629
+ for (const index of entry.table.indexes) {
1630
+ if (!owns(index.columns)) continue;
1631
+ const naming = attributeNaming({
1632
+ kind: "index",
1633
+ entry,
1634
+ name: index.name,
1635
+ prefix: index.prefix,
1636
+ contentHash: () => computeIndexContentHash(index)
1637
+ });
1638
+ refuseSqlTextThatDoesNotReadBack({
1639
+ kind: "index",
1640
+ namespaceId: entry.namespaceId,
1641
+ table: entry.tableName,
1642
+ name: index.name,
1643
+ texts: [index.expression, index.where]
1644
+ });
1645
+ const fullText = fullTextIndexDefinitionOf(index);
1646
+ if (fullText !== void 0) {
1647
+ attributes.push(buildFullTextIndexAttribute(index, fullText, fieldNameOf, naming));
1648
+ continue;
1649
+ }
1650
+ refuseUnwritableIndexOptions(entry, index);
1651
+ attributes.push(buildIndexAttribute(index, index.columns?.map(fieldNameOf), naming));
1652
+ }
1653
+ if (entry.table.control !== void 0 && variant?.singleTable !== true) attributes.push(buildAttribute("model", "control", [positionalArg(entry.table.control)]));
1654
+ if (input.rlsEnabled && variant?.singleTable !== true) attributes.push(buildAttribute("model", "rls", []));
1655
+ const mapName = pslModelMapName(entry.name, entry.tableName);
1656
+ if (mapName !== void 0 && variant?.singleTable !== true) attributes.push(buildMapAttribute("model", mapName));
1657
+ return attributes;
1658
+ }
1659
+ const PSL_REFERENTIAL_ACTIONS = {
1660
+ noAction: "NoAction",
1661
+ restrict: "Restrict",
1662
+ cascade: "Cascade",
1663
+ setNull: "SetNull",
1664
+ setDefault: "SetDefault"
1665
+ };
1666
+ function isReferenceRelation(relation) {
1667
+ return "on" in relation && relation.on !== void 0;
1668
+ }
1669
+ function collectRelations(models) {
1670
+ const entries = [];
1671
+ for (const owner of models) for (const [fieldName, relation] of Object.entries(owner.model.relations)) {
1672
+ if (!isReferenceRelation(relation)) refuseRelationWithoutJoin(owner.name, fieldName);
1673
+ entries.push({
1674
+ owner,
1675
+ fieldName,
1676
+ relation,
1677
+ targetCoordinate: crossReferenceCoordinate(relation.to)
1678
+ });
1679
+ }
1680
+ return entries;
1681
+ }
1682
+ /** A relation whose local fields carry the foreign key — the side `@relation(fields:…)` goes on. */
1683
+ function isOwningRelation(entry) {
1684
+ return entry.relation.cardinality === "N:1";
1685
+ }
1686
+ function relationKey(entry) {
1687
+ return JSON.stringify([
1688
+ entry.owner.namespaceId,
1689
+ entry.owner.name,
1690
+ entry.fieldName
1691
+ ]);
1692
+ }
1693
+ /** The relation name a pair is pinned with when the model pair carries more than one relation. */
1694
+ function relationName(entry) {
1695
+ return `${entry.owner.name}_${entry.fieldName}`;
1696
+ }
1697
+ function columnsIn(model, fieldNames) {
1698
+ return fieldNames.map((fieldName) => model.storage.fields[fieldName]?.column ?? fieldName);
1699
+ }
1700
+ function columnsOf(entry, fieldNames) {
1701
+ return columnsIn(entry.owner, fieldNames);
1702
+ }
1703
+ function sameColumns(a, b) {
1704
+ return a.length === b.length && a.every((value, index) => value === b[index]);
1705
+ }
1706
+ /** The foreign key that backs an owning relation. */
1707
+ function foreignKeyFor(entry, target) {
1708
+ const localColumns = columnsOf(entry, entry.relation.on.localFields);
1709
+ const targetColumns = columnsIn(target, entry.relation.on.targetFields);
1710
+ return entry.owner.table.foreignKeys.find((fk) => fk.target.spaceId === void 0 && fk.target.tableName === target.tableName && fk.target.namespaceId === target.namespaceId && sameColumns(fk.source.columns, localColumns) && sameColumns(fk.target.columns, targetColumns));
1711
+ }
1712
+ /**
1713
+ * The owning relation on `target` that pairs with a back-relation `entry`: the
1714
+ * one pointing back at `entry`'s model over the same columns. The
1715
+ * back-relation's target fields name fields of the target model, so they are
1716
+ * resolved to columns through the candidate's own model, not through the
1717
+ * back-relation's.
1718
+ */
1719
+ function owningPartner(entry, relationsByModel) {
1720
+ const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
1721
+ return relationsByModel.get(entry.targetCoordinate)?.find((candidate) => isOwningRelation(candidate) && candidate.targetCoordinate === ownerCoordinate && sameColumns(columnsOf(candidate, candidate.relation.on.localFields), columnsIn(candidate.owner, entry.relation.on.targetFields)));
1722
+ }
1723
+ /**
1724
+ * The junction-side relation that points back at the parent of a many-to-many
1725
+ * relation — the one whose columns are the junction's parent columns.
1726
+ */
1727
+ function junctionParentRelation(entry, relationsByModel) {
1728
+ const through = entry.relation.through;
1729
+ if (through === void 0) return void 0;
1730
+ const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
1731
+ for (const [, relations] of relationsByModel) for (const candidate of relations) {
1732
+ if (candidate.owner.tableName !== through.table || candidate.owner.namespaceId !== through.namespaceId || candidate.targetCoordinate !== ownerCoordinate || !isOwningRelation(candidate)) continue;
1733
+ if (sameColumns(columnsOf(candidate, candidate.relation.on.localFields), through.parentColumns)) return candidate;
1734
+ }
1735
+ }
1736
+ /**
1737
+ * The `index` argument of an owning relation. Every index the contract carries is written as its own `@@index`, and `contract emit` derives a backing index for a relation and drops it again beside an identical index or a key on its columns. So the argument is `false` for a foreign key nothing backs, the written name of an index the derived one would not match, and absent otherwise.
1738
+ */
1739
+ function relationIndexArgument(entry, foreignKey) {
1740
+ const { owner } = entry;
1741
+ const backing = foreignKey.index;
1742
+ if (backing === void 0) return "false";
1743
+ const { table } = owner;
1744
+ const columns = foreignKey.source.columns;
1745
+ const derived = defaultForeignKeyIndex(owner.tableName, columns, {
1746
+ indexes: table.indexes.map(indexInputOf),
1747
+ uniques: table.uniques,
1748
+ primaryKey: table.primaryKey
1749
+ });
1750
+ if (derived !== void 0 && JSON.stringify(derived) === JSON.stringify(backing)) return;
1751
+ const name = backingObjectName(table, backing);
1752
+ if (name === void 0) refuseUnnamedForeignKeyBacking(owner.name, entry.fieldName);
1753
+ return `"${escapePslString(name)}"`;
1754
+ }
1755
+ function indexInputOf(index) {
1756
+ const shape = {
1757
+ naming: parseNaming(index.name, index.prefix),
1758
+ where: index.where,
1759
+ unique: index.unique,
1760
+ type: index.type,
1761
+ options: index.options
1762
+ };
1763
+ return index.expression !== void 0 ? {
1764
+ ...shape,
1765
+ expression: index.expression
1766
+ } : {
1767
+ ...shape,
1768
+ columns: index.columns ?? []
1769
+ };
1770
+ }
1771
+ /** The name the printed source gives what backs a foreign key: the written name of an index, unless another index shares it, or the name of the primary key or of the unique constraint with the stored columns. */
1772
+ function backingObjectName(table, backing) {
1773
+ if ("name" in backing) {
1774
+ const index = table.indexes.find((candidate) => candidate.name === backing.name);
1775
+ if (index === void 0) return backing.name;
1776
+ const written = index.prefix ?? index.name;
1777
+ return table.indexes.some((other) => other !== index && (other.prefix ?? other.name) === written) ? index.name : written;
1778
+ }
1779
+ if ("primaryKey" in backing) return table.primaryKey?.name;
1780
+ return table.uniques.find((unique) => sameColumns(unique.columns, backing.unique))?.name;
1781
+ }
1782
+ /** The PSL field one relation is written as. */
1783
+ function buildRelationField(input) {
1784
+ const { entry, target, name } = input;
1785
+ const { relation } = entry;
1786
+ const typeNamespaceId = target.namespaceId === entry.owner.namespaceId ? void 0 : pslNamespaceName(target.namespaceId);
1787
+ const args = [];
1788
+ if (name !== void 0) args.push(namedArg("name", `"${escapePslString(name)}"`));
1789
+ if (relation.cardinality === "N:1" && input.ownerIsSingleTableVariant) {
1790
+ args.push(namedArg("fields", `[${relation.on.localFields.join(", ")}]`));
1791
+ args.push(namedArg("references", `[${relation.on.targetFields.join(", ")}]`));
1792
+ } else if (relation.cardinality === "N:1") {
1793
+ const foreignKey = foreignKeyFor(entry, target);
1794
+ if (foreignKey === void 0) refuseToOneRelationWithoutForeignKey(entry.owner.name, entry.fieldName);
1795
+ args.push(namedArg("fields", `[${relation.on.localFields.join(", ")}]`));
1796
+ args.push(namedArg("references", `[${relation.on.targetFields.join(", ")}]`));
1797
+ if (foreignKey.onDelete !== void 0) args.push(namedArg("onDelete", PSL_REFERENTIAL_ACTIONS[foreignKey.onDelete]));
1798
+ if (foreignKey.onUpdate !== void 0) args.push(namedArg("onUpdate", PSL_REFERENTIAL_ACTIONS[foreignKey.onUpdate]));
1799
+ if (foreignKey.name !== void 0) args.push(namedArg("map", `"${escapePslString(foreignKey.name)}"`));
1800
+ const indexArgument = relationIndexArgument(entry, foreignKey);
1801
+ if (indexArgument !== void 0) args.push(namedArg("index", indexArgument));
1802
+ }
1803
+ const list = relation.cardinality === "1:N" || relation.cardinality === "N:M";
1804
+ const optional = !list && (relation.cardinality === "1:1" || relation.cardinality === "N:1") && relation.nullable === true;
1805
+ return {
1806
+ kind: "field",
1807
+ name: entry.fieldName,
1808
+ typeName: target.name,
1809
+ ...ifDefined("typeNamespaceId", typeNamespaceId),
1810
+ optional,
1811
+ list,
1812
+ attributes: args.length > 0 ? [buildAttribute("field", "relation", args)] : [],
1813
+ span: SYNTHETIC_SPAN
1814
+ };
1815
+ }
1816
+ /** The relations of each model, keyed by the model's coordinate. */
1817
+ function relationsByModel(relations) {
1818
+ const byModel = /* @__PURE__ */ new Map();
1819
+ for (const entry of relations) {
1820
+ const key = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
1821
+ const bucket = byModel.get(key) ?? [];
1822
+ bucket.push(entry);
1823
+ byModel.set(key, bucket);
1824
+ }
1825
+ return byModel;
1826
+ }
1827
+ /**
1828
+ * The relation names to pin. A pair needs one when either of its models
1829
+ * carries more than one relation to the other; a many-to-many list field
1830
+ * additionally pins the junction-side relation it travels through, so that
1831
+ * relation is named too.
1832
+ */
1833
+ function resolvePinnedRelations(relations, relationsByModel) {
1834
+ const pairCounts = /* @__PURE__ */ new Map();
1835
+ for (const entry of relations) {
1836
+ const key = JSON.stringify([modelCoordinate(entry.owner.namespaceId, entry.owner.name), entry.targetCoordinate]);
1837
+ pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);
1838
+ }
1839
+ const ambiguous = (entry) => {
1840
+ const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
1841
+ const forward = pairCounts.get(JSON.stringify([ownerCoordinate, entry.targetCoordinate])) ?? 0;
1842
+ const backward = pairCounts.get(JSON.stringify([entry.targetCoordinate, ownerCoordinate])) ?? 0;
1843
+ return forward > 1 || backward > 1;
1844
+ };
1845
+ const pinned = /* @__PURE__ */ new Set();
1846
+ for (const entry of relations) {
1847
+ if (!ambiguous(entry)) continue;
1848
+ const owning = isOwningRelation(entry) ? entry : entry.relation.cardinality === "N:M" ? junctionParentRelation(entry, relationsByModel) : owningPartner(entry, relationsByModel);
1849
+ if (owning !== void 0) pinned.add(relationKey(owning));
1850
+ }
1851
+ return pinned;
1852
+ }
1853
+ /**
1854
+ * Relation fields in the order their foreign keys appear in storage, so the
1855
+ * `foreignKeys` the PSL source derives come back in the same order. A relation
1856
+ * that owns no foreign key keeps its place at the end.
1857
+ */
1858
+ function orderedByForeignKey(entry, relations) {
1859
+ const positions = /* @__PURE__ */ new Map();
1860
+ for (const relation of relations) {
1861
+ const target = relation.relation.on.localFields.map((fieldName) => relation.owner.storage.fields[fieldName]?.column ?? fieldName);
1862
+ const position = entry.table.foreignKeys.findIndex((fk) => fk.source.columns.length === target.length && fk.source.columns.every((column, index) => column === target[index]));
1863
+ positions.set(relation, isOwningRelation(relation) && position >= 0 ? position : relations.length);
1864
+ }
1865
+ return [...relations].sort((a, b) => (positions.get(a) ?? 0) - (positions.get(b) ?? 0));
1866
+ }
1867
+ /**
1868
+ * The relation fields of one model, in the order of its foreign keys. Each foreign key an owning
1869
+ * relation travels is added to `travelledForeignKeys`.
1870
+ */
1871
+ function buildRelationFields(input) {
1872
+ const fields = [];
1873
+ for (const modelRelation of orderedByForeignKey(input.entry, input.relations)) {
1874
+ refuseUnwritableName("field", modelRelation.fieldName);
1875
+ const target = relationTarget(modelRelation, input.modelsByCoordinate);
1876
+ const junctionRelation = modelRelation.relation.cardinality === "N:M" ? junctionParentRelation(modelRelation, input.relationsByModel) : void 0;
1877
+ if (modelRelation.relation.cardinality === "N:M" && junctionRelation === void 0) refuseManyToManyWithoutJunctionRelation(modelRelation.owner.name, modelRelation.fieldName);
1878
+ const owning = isOwningRelation(modelRelation) ? modelRelation : modelRelation.relation.cardinality === "N:M" ? junctionRelation : owningPartner(modelRelation, input.relationsByModel);
1879
+ if (owning === void 0) refuseBackRelationWithoutOwningRelation({
1880
+ modelName: modelRelation.owner.name,
1881
+ fieldName: modelRelation.fieldName,
1882
+ targetModel: target.name
1883
+ });
1884
+ const name = input.pinned.has(relationKey(owning)) ? relationName(owning) : void 0;
1885
+ if (isOwningRelation(modelRelation)) {
1886
+ const foreignKey = foreignKeyFor(modelRelation, target);
1887
+ if (foreignKey !== void 0) input.travelledForeignKeys.add(foreignKey);
1888
+ }
1889
+ fields.push(buildRelationField({
1890
+ entry: modelRelation,
1891
+ target,
1892
+ name,
1893
+ ownerIsSingleTableVariant: input.variant?.singleTable === true
1894
+ }));
1895
+ }
1896
+ return fields;
1897
+ }
1898
+ /**
1899
+ * The model a relation points at. A relation into another contract space is
1900
+ * refused: the printer does not write one yet.
1901
+ */
1902
+ function relationTarget(entry, modelsByCoordinate) {
1903
+ const { to } = entry.relation;
1904
+ refuseRelationToOtherContractSpace({
1905
+ modelName: entry.owner.name,
1906
+ fieldName: entry.fieldName,
1907
+ targetModel: to.model,
1908
+ space: to.space
1909
+ });
1910
+ const target = modelsByCoordinate.get(entry.targetCoordinate);
1911
+ assertDefined(target, `relation "${entry.owner.name}.${entry.fieldName}" targets model "${to.namespace}.${to.model}", which the contract does not declare`);
1912
+ return target;
1913
+ }
1914
+ /**
1915
+ * The storage tables of one namespace that have row-level security enabled,
1916
+ * each written as `@@rls` on its model. The PSL source files each one under
1917
+ * its table name, in the namespace of its model.
1918
+ */
1919
+ function rlsEnabledTables(namespaceId, entries) {
1920
+ const tables = /* @__PURE__ */ new Set();
1921
+ for (const [name, entity] of Object.entries(entries ?? {})) {
1922
+ invariant(entity instanceof PostgresRlsEnablement, `"rls" entry "${name}" in namespace "${namespaceId}" is not a row-level security setting`);
1923
+ refuseEntryInOtherNamespace({
1924
+ namespaceId,
1925
+ kind: "rls",
1926
+ name,
1927
+ recordedNamespaceId: entity.namespaceId
1928
+ });
1929
+ refuseEntryFiledUnderAnotherName({
1930
+ namespaceId,
1931
+ kind: "rls",
1932
+ name,
1933
+ readsBackAs: entity.tableName
1934
+ });
1935
+ tables.add(entity.tableName);
1936
+ }
1937
+ return tables;
1938
+ }
1939
+ /**
1940
+ * One `role <name> {}` block per role. The PSL source reads a role block only
1941
+ * inside `namespace unbound`, and files it under its name.
1942
+ */
1943
+ function buildRoleBlocks(namespaceId, entries) {
1944
+ return Object.entries(entries ?? {}).map(([name, entity]) => {
1945
+ invariant(entity instanceof PostgresRole, `"role" entry "${name}" in namespace "${namespaceId}" is not a role`);
1946
+ refuseRoleOutsideUnbound(namespaceId, name);
1947
+ refuseEntryInOtherNamespace({
1948
+ namespaceId,
1949
+ kind: "role",
1950
+ name,
1951
+ recordedNamespaceId: entity.namespaceId
1952
+ });
1953
+ refuseEntryFiledUnderAnotherName({
1954
+ namespaceId,
1955
+ kind: "role",
1956
+ name,
1957
+ readsBackAs: entity.name
1958
+ });
1959
+ refuseUnwritableName("role", entity.name);
1960
+ return {
1961
+ kind: "role",
1962
+ keyword: "role",
1963
+ name: entity.name,
1964
+ parameters: {},
1965
+ blockAttributes: [],
1966
+ span: SYNTHETIC_SPAN
1967
+ };
1968
+ });
1969
+ }
1970
+ /**
1971
+ * Whether the PSL source, reading a policy block named `head`, derives this
1972
+ * policy's name: the block name with the hash of the policy's content for a
1973
+ * wire-named policy, or the `@@map` name for an exact one.
1974
+ */
1975
+ function policyNameReadsBack(head, policy) {
1976
+ if (policy.prefix === void 0) return true;
1977
+ const hash = computeContentHash({
1978
+ ...policy.using === void 0 ? {} : { using: policy.using },
1979
+ ...policy.withCheck === void 0 ? {} : { withCheck: policy.withCheck },
1980
+ roles: policy.roles,
1981
+ operation: policy.operation,
1982
+ permissive: policy.permissive
1983
+ });
1984
+ return policy.prefix === head && policy.name === formatWireName(head, hash);
1985
+ }
1986
+ /**
1987
+ * One `policy_<operation>` block per policy, named by its entry key, which is
1988
+ * the block head it was authored under. A policy with an exact name also
1989
+ * prints `@@map` with that name.
1990
+ */
1991
+ function buildPolicyBlocks(input) {
1992
+ return Object.entries(input.entries ?? {}).map(([head, policy]) => {
1993
+ invariant(policy instanceof PostgresRlsPolicy, `"policy" entry "${head}" in namespace "${input.namespaceId}" is not a policy`);
1994
+ refuseUnwritableName("policy", head);
1995
+ refuseEntryInOtherNamespace({
1996
+ namespaceId: input.namespaceId,
1997
+ kind: "policy",
1998
+ name: head,
1999
+ recordedNamespaceId: policy.namespaceId
2000
+ });
2001
+ const modelName = input.modelNameForTable(policy.tableName);
2002
+ if (modelName === void 0) refusePolicyWithoutModel(policy);
2003
+ if (!input.rlsTables.has(policy.tableName)) refusePolicyWithoutRls(policy);
2004
+ if (!policyNameReadsBack(head, policy)) refusePolicyNameNotDerived(policy);
2005
+ for (const role of policy.roles) refuseUnwritableName("role", role);
2006
+ refuseSqlTextThatDoesNotReadBack({
2007
+ kind: "policy",
2008
+ namespaceId: policy.namespaceId,
2009
+ table: policy.tableName,
2010
+ name: policy.name,
2011
+ texts: [policy.using, policy.withCheck]
2012
+ });
2013
+ return {
2014
+ kind: "policy",
2015
+ keyword: POLICY_BLOCK_KEYWORDS[policy.operation],
2016
+ name: head,
2017
+ parameters: {
2018
+ target: {
2019
+ expression: modelName,
2020
+ span: SYNTHETIC_SPAN
2021
+ },
2022
+ roles: {
2023
+ expression: `[${policy.roles.join(", ")}]`,
2024
+ span: SYNTHETIC_SPAN
2025
+ },
2026
+ ...policy.using !== void 0 ? { using: {
2027
+ expression: printSqlExpressionLiteral(policy.using),
2028
+ span: SYNTHETIC_SPAN
2029
+ } } : {},
2030
+ ...policy.withCheck !== void 0 ? { withCheck: {
2031
+ expression: printSqlExpressionLiteral(policy.withCheck),
2032
+ span: SYNTHETIC_SPAN
2033
+ } } : {},
2034
+ ...policy.permissive ? {} : { permissive: {
2035
+ expression: "false",
2036
+ span: SYNTHETIC_SPAN
2037
+ } }
2038
+ },
2039
+ blockAttributes: policy.prefix === void 0 ? [{
2040
+ name: "map",
2041
+ args: [{
2042
+ kind: "positional",
2043
+ value: `"${escapePslString(policy.name)}"`,
2044
+ span: SYNTHETIC_SPAN
2045
+ }],
2046
+ span: SYNTHETIC_SPAN
2047
+ }] : [],
2048
+ span: SYNTHETIC_SPAN
2049
+ };
2050
+ });
2051
+ }
2052
+ /**
2053
+ * The `@default(…)` attribute for a storage column, or `undefined` when the column carries no
2054
+ * default.
2055
+ *
2056
+ * A literal prints as the PSL literal the data type of the column's codec reads back, through the
2057
+ * stack's data types, with the mapping `contract infer` uses. An enum column's default is a member
2058
+ * name, which reads as text; a domain enum's literal prints as the member name that carries it.
2059
+ * `now()` and `autoincrement()` print by name; every other function default prints as a `sql`
2060
+ * tagged literal.
2061
+ *
2062
+ * A literal is refused when the column's codec has no data type in the stack, or when no PSL
2063
+ * literal of that data type reads back as the stored value. A function default is refused when a
2064
+ * `sql` literal cannot write its text back unchanged.
2065
+ */
2066
+ function buildColumnDefault(input) {
2067
+ const columnDefault = input.column.default;
2068
+ if (columnDefault === void 0) return;
2069
+ const coordinate = `"${input.namespaceId}"."${input.tableName}"."${input.columnName}"`;
2070
+ if (input.domainEnum !== void 0 && columnDefault.kind === "literal") {
2071
+ const memberName = input.domainEnum.members.find((member) => member.value === columnDefault.value)?.name;
2072
+ if (memberName === void 0) refuseDefaultOutsideEnum({
2073
+ coordinate,
2074
+ value: columnDefault.value,
2075
+ pslTypeName: input.pslTypeName
2076
+ });
2077
+ return buildAttribute("field", "default", [positionalArg(memberName)]);
2078
+ }
2079
+ if (columnDefault.kind === "function") refuseSqlTextThatDoesNotReadBack({
2080
+ kind: "default",
2081
+ coordinate,
2082
+ texts: [columnDefault.expression]
2083
+ });
2084
+ const { context } = input;
2085
+ const result = mapDefault(columnDefault, {
2086
+ dataTypes: context.dataTypes,
2087
+ columnCodec: context.codecLookup.descriptorFor(input.isEnum ? PG_TEXT_CODEC_ID : input.column.codecId),
2088
+ typeParams: nonEmptyTypeParams(input.column.typeParams),
2089
+ list: input.column.many !== false
2090
+ });
2091
+ if (result === void 0) refuseUnwritableLiteralDefault({
2092
+ coordinate,
2093
+ written: columnDefault.kind === "literal" ? JSON.stringify(columnDefault.value) : columnDefault.expression,
2094
+ pslTypeName: input.pslTypeName
2095
+ });
2096
+ return parseDefaultAttributeString(result.attribute);
2097
+ }
2098
+ function refuse(refusal, input) {
2099
+ const { coordinate, codecId, context } = input;
2100
+ const { phase, generator } = refusal;
2101
+ switch (refusal.kind) {
2102
+ case "on-list": return refuseGeneratorOnList({
2103
+ coordinate,
2104
+ phase,
2105
+ generatorId: generator.id
2106
+ });
2107
+ case "no-function": return refuseGeneratorWithoutPslFunction({
2108
+ coordinate,
2109
+ phase,
2110
+ generatorId: generator.id,
2111
+ codecId,
2112
+ registeredBy: context.componentIdsByGenerator.has(generator.id) ? { componentId: context.componentIdsByGenerator.get(generator.id) } : void 0
2113
+ });
2114
+ case "reads-back-differently": return refuseGeneratorReadingBackDifferently({
2115
+ coordinate,
2116
+ phase,
2117
+ call: refusal.text,
2118
+ stored: generator,
2119
+ readBack: refusal.readBack,
2120
+ refusedBecause: refusal.refusedBecause
2121
+ });
2122
+ }
2123
+ }
2124
+ /**
2125
+ * The `@onCreate(fn(...))` and `@onUpdate(fn(...))` attributes that write one column's generators. A column whose generators cannot be written as calls that read back the same is refused.
2126
+ */
2127
+ function buildGeneratorAttributes(input) {
2128
+ const result = generatorCallsFor({
2129
+ executionDefault: input.executionDefault,
2130
+ field: {
2131
+ codecId: input.codecId,
2132
+ typeParams: input.typeParams,
2133
+ length: sqlCodecColumnLength(input.context.dataTypes, input.codecId, input.typeParams)
2134
+ },
2135
+ list: input.list,
2136
+ generatorFunctions: input.context.generatorFunctions
2137
+ });
2138
+ if (!result.ok) refuse(result.refusal, input);
2139
+ return result.calls.map(({ phase, text }) => buildAttribute("field", phase, [positionalArg(text)]));
2140
+ }
2141
+ /** The generated values of the contract, keyed by the column they fill. */
2142
+ function executionDefaultsByColumn(contract) {
2143
+ const byColumn = /* @__PURE__ */ new Map();
2144
+ for (const entry of contract.execution?.mutations.defaults ?? []) byColumn.set(JSON.stringify([
2145
+ entry.ref.namespace,
2146
+ entry.ref.entry,
2147
+ entry.ref.field
2148
+ ]), entry);
2149
+ return byColumn;
2150
+ }
2151
+ function scalarFieldAttributes(input) {
2152
+ const attributes = [];
2153
+ if (input.isSingleColumnId) attributes.push(buildAttribute("field", "id", input.primaryKeyName === void 0 ? [] : [namedArg("map", `"${escapePslString(input.primaryKeyName)}"`)]));
2154
+ const columnDefault = buildColumnDefault({
2155
+ column: input.column,
2156
+ pslTypeName: input.pslTypeName,
2157
+ isEnum: input.isEnum,
2158
+ domainEnum: input.domainEnum,
2159
+ namespaceId: input.namespaceId,
2160
+ tableName: input.tableName,
2161
+ columnName: input.columnName,
2162
+ context: input.context
2163
+ });
2164
+ if (columnDefault !== void 0) attributes.push(columnDefault);
2165
+ attributes.push(...input.generatorAttributes);
2166
+ const mapName = pslFieldMapName(input.fieldName, input.columnName);
2167
+ if (mapName !== void 0) attributes.push(buildMapAttribute("field", mapName));
2168
+ return attributes;
2169
+ }
2170
+ /**
2171
+ * The scalar and value-object fields of one model, one per column its storage names.
2172
+ */
2173
+ function buildScalarFields(input) {
2174
+ const { entry, variant, enums, domainEnums, inferredConstructors, context, executionDefaults } = input;
2175
+ const primaryKeyColumns = variant === void 0 ? entry.table.primaryKey?.columns ?? [] : [];
2176
+ const fields = [];
2177
+ for (const [fieldName, fieldStorage] of Object.entries(entry.storage.fields)) {
2178
+ const columnName = fieldStorage.column;
2179
+ const coordinate = `"${entry.namespaceId}"."${entry.tableName}"."${columnName}"`;
2180
+ const column = entry.table.columns[columnName];
2181
+ const field = entry.model.fields[fieldName];
2182
+ assertDefined(column, `column ${coordinate} is not declared by its table`);
2183
+ if (field === void 0) refuseStorageOfUndeclaredField({
2184
+ entry,
2185
+ fieldName,
2186
+ coordinate
2187
+ });
2188
+ refuseUnwritableName("field", fieldName);
2189
+ refuseUnwritableMappedName("column", columnName);
2190
+ refuseUnwritableFieldShape(field, coordinate);
2191
+ refuseColumnControl(column, coordinate);
2192
+ refuseFieldColumnMismatch({
2193
+ field,
2194
+ column,
2195
+ coordinate,
2196
+ modelName: entry.name,
2197
+ singleTableVariant: variant?.singleTable === true,
2198
+ domainEnumNames: input.defaultDomainEnumNames
2199
+ });
2200
+ const columnType = field.type.kind === "valueObject" ? {
2201
+ kind: "valueObject",
2202
+ typeName: field.type.name
2203
+ } : buildColumnType({
2204
+ column,
2205
+ inferredConstructors,
2206
+ authoringTypes: context.authoringContributions.type,
2207
+ dataTypes: context.dataTypes,
2208
+ enumBlockNames: enums.blockNamesByTypeName,
2209
+ coordinate,
2210
+ namespaceId: entry.namespaceId
2211
+ });
2212
+ const { typeName, typeConstructor } = columnType;
2213
+ const execution = executionDefaults.get(JSON.stringify([
2214
+ entry.namespaceId,
2215
+ entry.tableName,
2216
+ columnName
2217
+ ]));
2218
+ const generatorAttributes = execution === void 0 ? [] : buildGeneratorAttributes({
2219
+ executionDefault: execution,
2220
+ codecId: column.codecId,
2221
+ list: !!field.many,
2222
+ typeParams: nonEmptyTypeParams(column.typeParams),
2223
+ coordinate,
2224
+ context
2225
+ });
2226
+ fields.push({
2227
+ kind: "field",
2228
+ name: fieldName,
2229
+ typeName,
2230
+ ...ifDefined("typeConstructor", typeConstructor),
2231
+ optional: field.nullable,
2232
+ list: !!field.many,
2233
+ elementOptional: !!field.many && field.many.elementNullable,
2234
+ attributes: scalarFieldAttributes({
2235
+ column,
2236
+ fieldName,
2237
+ namespaceId: entry.namespaceId,
2238
+ tableName: entry.tableName,
2239
+ columnName,
2240
+ isSingleColumnId: primaryKeyColumns.length === 1 && primaryKeyColumns[0] === columnName,
2241
+ primaryKeyName: entry.table.primaryKey?.name,
2242
+ pslTypeName: columnType.typeName,
2243
+ isEnum: column.codecId === PG_ENUM_CODEC_ID,
2244
+ domainEnum: column.codecId === "pg/enum@1" || column.valueSet === void 0 ? void 0 : domainEnums[column.valueSet.entityName],
2245
+ generatorAttributes,
2246
+ context
2247
+ }),
2248
+ span: SYNTHETIC_SPAN
2249
+ });
2250
+ }
2251
+ return fields;
2252
+ }
2253
+ /** The native enums of one namespace, keyed as the contract keys them. */
2254
+ function nativeEnumsOf(namespaceId, entries) {
2255
+ const nativeEnums = /* @__PURE__ */ new Map();
2256
+ for (const [name, entity] of Object.entries(entries["native_enum"] ?? {})) {
2257
+ invariant(PostgresNativeEnum.is(entity), `"native_enum" entry "${name}" in namespace "${namespaceId}" is not a native enum`);
2258
+ nativeEnums.set(name, entity);
2259
+ }
2260
+ return nativeEnums;
2261
+ }
2262
+ /** The value sets the PSL source derives for a namespace from the enum blocks written for it. */
2263
+ function derivedValueSetsOf(namespaceId, enums, defaultDomainEnums) {
2264
+ const derived = new Map(enums.derivedValueSets);
2265
+ if (namespaceId !== "public") return derived;
2266
+ for (const [name, domainEnum] of Object.entries(defaultDomainEnums)) {
2267
+ if (derived.has(name)) refuseEnumAndNativeEnumSharingName(namespaceId, name);
2268
+ derived.set(name, domainEnum.members.map((member) => member.value));
2269
+ }
2270
+ return derived;
2271
+ }
2272
+ /** One model of a namespace, with its fields and attributes. */
2273
+ function buildModel(all, entry, enums, rlsTables) {
2274
+ const { models, variants, relationsByModel, byCoordinate } = all;
2275
+ refuseUnwritableName("model", entry.name);
2276
+ refuseModelOwner(entry);
2277
+ const variant = variants.get(entry);
2278
+ if (variant !== void 0 && !variant.singleTable) refuseUnderivedVariantLink(entry, variant);
2279
+ const singleTableVariants = models.filter((other) => other !== entry && variants.get(other)?.singleTable === true && variants.get(other)?.base === entry);
2280
+ const travelledForeignKeys = /* @__PURE__ */ new Set();
2281
+ const fields = [...buildScalarFields({
2282
+ entry,
2283
+ variant,
2284
+ enums,
2285
+ domainEnums: all.contract.domain.namespaces[entry.namespaceId]?.enum ?? {},
2286
+ inferredConstructors: all.inferredConstructors,
2287
+ context: all.context,
2288
+ executionDefaults: all.executionDefaults,
2289
+ defaultDomainEnumNames: new Set(Object.keys(all.defaultDomainEnums))
2290
+ }), ...buildRelationFields({
2291
+ entry,
2292
+ variant,
2293
+ relations: relationsByModel.get(modelCoordinate(entry.namespaceId, entry.name)) ?? [],
2294
+ relationsByModel,
2295
+ modelsByCoordinate: byCoordinate,
2296
+ pinned: all.pinned,
2297
+ travelledForeignKeys
2298
+ })];
2299
+ if (variant?.singleTable !== true) for (const other of singleTableVariants) for (const relation of relationsByModel.get(modelCoordinate(entry.namespaceId, other.name)) ?? []) {
2300
+ const target = byCoordinate.get(relation.targetCoordinate);
2301
+ const fk = target === void 0 ? void 0 : foreignKeyFor(relation, target);
2302
+ if (fk !== void 0) travelledForeignKeys.add(fk);
2303
+ }
2304
+ refuseUntravelledForeignKeys(entry, variant, travelledForeignKeys);
2305
+ const checks = derivedChecks({
2306
+ table: entry.table,
2307
+ tableName: entry.tableName,
2308
+ managed: effectiveControlPolicy(entry.table.control, all.contract.defaultControlPolicy) === "managed",
2309
+ domainEnumValues: all.domainEnumValues
2310
+ });
2311
+ if (variant?.singleTable !== true) refuseUnderivedChecks(entry, checks);
2312
+ return {
2313
+ kind: "model",
2314
+ name: entry.name,
2315
+ fields,
2316
+ attributes: buildModelAttributes({
2317
+ entry,
2318
+ variant,
2319
+ singleTableVariants,
2320
+ derivedChecksByName: checks,
2321
+ rlsEnabled: rlsTables.has(entry.tableName)
2322
+ }),
2323
+ span: SYNTHETIC_SPAN
2324
+ };
2325
+ }
2326
+ /**
2327
+ * The namespace block of one storage namespace: its models, value objects, enum blocks, roles and
2328
+ * policies. `undefined` when the namespace holds none of them.
2329
+ */
2330
+ function buildNamespace(all, namespaceId, namespace) {
2331
+ const { contract, models, variants } = all;
2332
+ refuseUnprintedEntryKinds(namespaceId, namespace.entries);
2333
+ const valueSets = new Map(Object.entries(namespace.entries.valueSet ?? {}).map(([name, valueSet]) => [name, valueSet.values]));
2334
+ const enums = buildNativeEnumBlocksForNamespace({
2335
+ namespaceId,
2336
+ nativeEnums: nativeEnumsOf(namespaceId, namespace.entries),
2337
+ valueSets,
2338
+ columns: models.filter((entry) => entry.namespaceId === namespaceId).flatMap((entry) => Object.values(entry.table.columns))
2339
+ });
2340
+ refuseUnderivedValueSets({
2341
+ namespaceId,
2342
+ actual: valueSets,
2343
+ derived: derivedValueSetsOf(namespaceId, enums, all.defaultDomainEnums)
2344
+ });
2345
+ const rlsTables = rlsEnabledTables(namespaceId, namespace.entries["rls"]);
2346
+ const namespaceModels = models.filter((entry) => entry.namespaceId === namespaceId).map((entry) => buildModel(all, entry, enums, rlsTables));
2347
+ const compositeTypes = buildCompositeTypes({
2348
+ contract,
2349
+ namespaceId,
2350
+ inferredConstructors: all.inferredConstructors,
2351
+ context: all.context,
2352
+ enumBlockNames: enums.blockNamesByTypeName,
2353
+ domainEnums: all.defaultDomainEnums
2354
+ });
2355
+ const modelNameForTable = (tableName) => models.find((entry) => entry.namespaceId === namespaceId && entry.tableName === tableName && variants.get(entry)?.singleTable !== true)?.name;
2356
+ for (const tableName of rlsTables) if (modelNameForTable(tableName) === void 0) refuseRlsWithoutModel(namespaceId, tableName);
2357
+ const blocks = [
2358
+ ...enums.blocks,
2359
+ ...buildRoleBlocks(namespaceId, namespace.entries["role"]),
2360
+ ...buildPolicyBlocks({
2361
+ namespaceId,
2362
+ entries: namespace.entries["policy"],
2363
+ modelNameForTable,
2364
+ rlsTables
2365
+ })
2366
+ ];
2367
+ if (namespaceModels.length === 0 && blocks.length === 0 && compositeTypes.length === 0) return;
2368
+ refuseNamespaceNamedUnbound(namespaceId);
2369
+ const name = pslNamespaceName(namespaceId);
2370
+ refuseUnwritableName("namespace", name);
2371
+ return makePslNamespace({
2372
+ kind: "namespace",
2373
+ name,
2374
+ entries: makePslNamespaceEntries(namespaceModels, compositeTypes, blocks),
2375
+ span: SYNTHETIC_SPAN
2376
+ });
2377
+ }
2378
+ function refuseUnwritableTableNames(contract) {
2379
+ for (const domainNamespace of Object.values(contract.domain.namespaces)) for (const model of Object.values(domainNamespace.models)) refuseUnwritableMappedName("table", blindCast(model.storage).table);
2380
+ }
2381
+ /**
2382
+ * Builds the Prisma 8 PSL document a Postgres contract was, or would have been, authored as: every
2383
+ * model with its columns, keys, indexes and relations, every value object and every native enum, in the namespace block that carries it.
2384
+ *
2385
+ * Read back by the PSL contract source with the same stack, the document yields the contract it was
2386
+ * built from. Anything the language cannot carry is refused by name. `contract` must be one the
2387
+ * Postgres contract serializer accepted: its structure is asserted, not checked again.
2388
+ */
2389
+ function buildPostgresPslContract(contract, context) {
2390
+ refuseUnwritableTableNames(contract);
2391
+ const models = indexContractModels(contract);
2392
+ refuseDuplicateModelNames(models);
2393
+ const byCoordinate = modelsByCoordinate(models);
2394
+ const relations = collectRelations(models);
2395
+ const byModel = relationsByModel(relations);
2396
+ const defaultDomainEnums = contract.domain.namespaces["public"]?.enum ?? {};
2397
+ const all = {
2398
+ contract,
2399
+ context,
2400
+ inferredConstructors: inferredTypeConstructors({
2401
+ authoringTypes: context.authoringContributions.type,
2402
+ codecLookup: context.codecLookup,
2403
+ dataTypeLookup: context.dataTypes.lookup
2404
+ }),
2405
+ models,
2406
+ byCoordinate,
2407
+ variants: new Map(models.map((entry) => [entry, variantInfo(entry, byCoordinate)])),
2408
+ relationsByModel: byModel,
2409
+ pinned: resolvePinnedRelations(relations, byModel),
2410
+ executionDefaults: executionDefaultsByColumn(contract),
2411
+ defaultDomainEnums,
2412
+ domainEnumValues: new Map(Object.entries(defaultDomainEnums).map(([name, domainEnum]) => [name, domainEnum.members.map((member) => member.value)]))
2413
+ };
2414
+ const namespaces = [];
2415
+ refuseEnumsOutsideDefaultNamespace(contract);
2416
+ const topLevelEnums = buildDomainEnumBlocks(defaultDomainEnums, context);
2417
+ if (topLevelEnums.length > 0) namespaces.push(makePslNamespace({
2418
+ kind: "namespace",
2419
+ name: UNSPECIFIED_PSL_NAMESPACE_ID,
2420
+ entries: makePslNamespaceEntries([], [], topLevelEnums),
2421
+ span: SYNTHETIC_SPAN
2422
+ }));
2423
+ const writtenStorageNamespaces = /* @__PURE__ */ new Set();
2424
+ for (const [namespaceId, namespace] of Object.entries(contract.storage.namespaces)) {
2425
+ const built = buildNamespace(all, namespaceId, namespace);
2426
+ if (built === void 0) continue;
2427
+ writtenStorageNamespaces.add(namespaceId);
2428
+ namespaces.push(built);
2429
+ }
2430
+ refuseUnmodelledTablesAndColumns(contract, models, all.variants);
2431
+ refuseUnwrittenNamespaces({
2432
+ contract,
2433
+ models,
2434
+ writtenStorageNamespaces
2435
+ });
2436
+ refuseContractMeta(contract);
2437
+ refuseUnderivedRoots(contract, models, all.variants);
2438
+ refuseRegisteredDatabaseTypes(contract);
2439
+ return {
2440
+ kind: "document",
2441
+ sourceId: "<contract>",
2442
+ namespaces,
2443
+ span: SYNTHETIC_SPAN
2444
+ };
2445
+ }
2446
+ function createPostgresTargetDescriptor() {
2447
+ setFallbackTemporal(Temporal);
2448
+ return {
2449
+ ...postgresTargetDescriptorMeta,
2450
+ contractSerializer: new PostgresContractSerializer(),
2451
+ schemaVerifier: new PostgresSchemaVerifier(),
2452
+ inferPslContract(schema, context, describedContracts) {
2453
+ PostgresDatabaseSchemaNode.assert(schema);
2454
+ return inferPostgresPslContract(schema, context, describedContracts);
2455
+ },
2456
+ buildPslContract(contract, context) {
2457
+ return buildPostgresPslContract(contract, context);
2458
+ },
2459
+ diffSchema(input) {
2460
+ return diffPostgresSchema(input);
2461
+ },
2462
+ classifySubjectGranularity: postgresDiffSubjectGranularity,
2463
+ classifyEntityKind: postgresDiffSubjectEntityKind,
2464
+ migrations: {
2465
+ createPlanner(adapter) {
2466
+ return createPostgresMigrationPlanner(adapter);
2467
+ },
2468
+ createRunner(family) {
2469
+ return blindCast(createPostgresMigrationRunner(family));
2470
+ },
2471
+ contractToSchema(contract, frameworkComponents) {
2472
+ return postgresContractToSchema(contract, frameworkComponents);
2473
+ }
2474
+ },
2475
+ create() {
2476
+ return {
2477
+ familyId: "sql",
2478
+ targetId: "postgres"
2479
+ };
2480
+ },
2481
+ /**
2482
+ * Direct method for SQL-specific usage.
2483
+ * @deprecated Use migrations.createPlanner() for CLI compatibility.
2484
+ */
2485
+ createPlanner(adapter) {
2486
+ return createPostgresMigrationPlanner(adapter);
2487
+ },
2488
+ /**
2489
+ * Direct method for SQL-specific usage.
2490
+ * @deprecated Use migrations.createRunner() for CLI compatibility.
2491
+ */
2492
+ createRunner(family) {
2493
+ return createPostgresMigrationRunner(family);
2494
+ }
2495
+ };
2496
+ }
2497
+ const postgresTargetDescriptor = createPostgresTargetDescriptor();
2498
+ //#endregion
2499
+ export { decodePostgresListText, postgresTargetDescriptor as default, parsePostgresListText, postgresNativeAuthoringTypes, postgresNowGeneratorControlDescriptors, postgresScalarAndNativeTypeConstructors, postgresScalarAuthoringTypes };
2500
+
2501
+ //# sourceMappingURL=target__control.mjs.map