@prisma-next/target-postgres 0.14.0 → 0.15.0-dev.10

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