@prisma-next/target-postgres 0.14.0-dev.8 → 0.14.0-dev.80

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