@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
@@ -1,122 +1,112 @@
1
1
  /**
2
- * Postgres migration planner.
2
+ * Postgres migration issue planner.
3
3
  *
4
- * Takes schema issues (from verifySqlSchema) and emits migration IR
5
- * (`PostgresOpFactoryCall[]`). Strategies consume issues they recognize and
6
- * produce specialized call sequences (e.g. NOT NULL backfill
4
+ * Takes node-typed schema-diff issues (from the one differ see
5
+ * `buildPostgresPlanDiff` in `diff-database-schema.ts`) and emits migration
6
+ * IR (`PostgresOpFactoryCall[]`). Strategies consume issues they recognize
7
+ * and produce specialized call sequences (e.g. NOT NULL backfill →
7
8
  * addColumn(nullable) + dataTransform + setNotNull); remaining issues flow
8
- * through `mapIssueToCall` for the default case.
9
+ * through `mapNodeIssueToCall` for the default case.
10
+ *
11
+ * Structural op-render (column type/default DDL) resolves the column node's
12
+ * `codecRef` against the codec hooks the caller holds (`column-ddl-
13
+ * rendering.ts`) — never re-derived from the contract. The retained
14
+ * subsystems (codec type-operations, the NOT-NULL temp-default deferred DDL,
15
+ * control-policy disposition) still read the contract via the strategy
16
+ * context, per the slice's scope.
9
17
  */
10
18
 
11
- import type { Contract, JsonValue } from '@prisma-next/contract/types';
19
+ import type { Contract } from '@prisma-next/contract/types';
12
20
  import type {
13
21
  CodecControlHooks,
14
22
  MigrationOperationPolicy,
15
23
  SqlPlannerConflict,
16
24
  SqlPlannerConflictLocation,
17
25
  } from '@prisma-next/family-sql/control';
18
- import { arraysEqual } from '@prisma-next/family-sql/schema-verify';
19
26
  import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
20
- import type { SchemaIssue } from '@prisma-next/framework-components/control';
21
- import type {
22
- SqlStorage,
23
- StorageColumn,
24
- StorageTable,
25
- StorageTypeInstance,
26
- } from '@prisma-next/sql-contract/types';
27
- import type { CodecRef, DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';
27
+ import type { DiffableNode, SchemaDiffIssue } from '@prisma-next/framework-components/control';
28
+ import { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';
29
+ import type { SqlStorage, StorageTypeInstance } from '@prisma-next/sql-contract/types';
30
+ import type { DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';
28
31
  import * as contractFree from '@prisma-next/sql-relational-core/contract-free';
29
- import type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';
32
+ import { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';
33
+ import {
34
+ RelationalSchemaNodeKind,
35
+ type SqlColumnDefaultIR,
36
+ type SqlColumnIR,
37
+ type SqlForeignKeyIR,
38
+ type SqlIndexIR,
39
+ SqlSchemaIR,
40
+ type SqlSchemaIRNode,
41
+ type SqlUniqueIR,
42
+ } from '@prisma-next/sql-schema-ir/types';
30
43
  import { blindCast } from '@prisma-next/utils/casts';
31
44
  import { ifDefined } from '@prisma-next/utils/defined';
32
45
  import type { Result } from '@prisma-next/utils/result';
33
46
  import { notOk, ok } from '@prisma-next/utils/result';
47
+ import type { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';
48
+ import type { PostgresNativeEnumSchemaNode } from '../schema-ir/postgres-native-enum-schema-node';
49
+ import type { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';
50
+ import { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';
51
+ import { quoteIdentifier } from '../sql-utils';
52
+ import {
53
+ renderColumnAlterType,
54
+ renderColumnDdl,
55
+ renderColumnDefaultSql,
56
+ } from './column-ddl-rendering';
57
+ import { resolveNamespaceIdForDdlSchema } from './control-policy';
34
58
  import {
35
59
  AddColumnCall,
36
60
  AddForeignKeyCall,
61
+ AddNativeEnumValueCall,
37
62
  AddPrimaryKeyCall,
38
63
  AddUniqueCall,
39
64
  AlterColumnTypeCall,
40
65
  CreateIndexCall,
66
+ CreateNativeEnumTypeCall,
41
67
  CreateSchemaCall,
42
68
  CreateTableCall,
69
+ DisableRowLevelSecurityCall,
43
70
  DropCheckConstraintCall,
44
71
  DropColumnCall,
45
72
  DropConstraintCall,
46
73
  DropDefaultCall,
47
74
  DropIndexCall,
75
+ DropNativeEnumTypeCall,
48
76
  DropNotNullCall,
49
77
  DropTableCall,
78
+ EnableRowLevelSecurityCall,
50
79
  type PostgresOpFactoryCall,
51
- postgresDefaultToDdlColumnDefault,
52
80
  SetDefaultCall,
53
81
  SetNotNullCall,
54
82
  } from './op-factory-call';
55
83
  import type { ForeignKeySpec } from './operations/shared';
56
- import { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';
57
- import { buildExpectedFormatType } from './planner-sql-checks';
58
84
  import {
59
85
  type CallMigrationStrategy,
60
86
  postgresPlannerStrategies,
61
- resolveDdlSchemaForNamespace,
62
- resolveNamespaceIdForIssue,
63
87
  type StrategyContext,
64
- tableAt,
65
88
  } from './planner-strategies';
66
- import { resolveColumnTypeMetadata } from './planner-type-resolution';
67
89
 
68
90
  export type { CallMigrationStrategy, StrategyContext };
69
91
 
70
- // ============================================================================
71
- // Issue kind ordering (dependency order)
72
- // ============================================================================
73
-
74
- const ISSUE_KIND_ORDER: Record<string, number> = {
75
- // Schemas first — the database container must exist before any DDL
76
- // that targets it can run.
77
- missing_schema: 1,
78
-
79
- // Types next
80
- type_missing: 2,
81
- type_values_mismatch: 3,
82
- enum_values_changed: 3,
83
-
84
- // Drops (reconciliation — clear the way for creates)
85
- // FKs dropped first (they depend on other constraints)
86
- extra_foreign_key: 10,
87
- extra_unique_constraint: 11,
88
- extra_primary_key: 12,
89
- extra_index: 13,
90
- extra_default: 14,
91
- extra_column: 15,
92
- extra_table: 16,
93
-
94
- // Tables before columns
95
- missing_table: 20,
96
-
97
- // Columns before constraints
98
- missing_column: 30,
99
-
100
- // Reconciliation alters (on existing objects)
101
- type_mismatch: 40,
102
- nullability_mismatch: 41,
103
- default_missing: 42,
104
- default_mismatch: 43,
105
-
106
- // Constraints after columns exist
107
- primary_key_mismatch: 50,
108
- unique_constraint_mismatch: 51,
109
- index_mismatch: 52,
110
- foreign_key_mismatch: 60,
111
-
112
- // Check constraints
113
- check_missing: 53,
114
- check_mismatch: 54,
115
- check_removed: 55,
116
- };
92
+ /**
93
+ * Deterministic name for the element-non-null CHECK constraint on a scalar-array
94
+ * column. Distinct `_elem_not_null` suffix avoids collision with the enum
95
+ * value-set `_check` constraints. Re-emitting the same schema produces the same
96
+ * name, so `pg_get_constraintdef`-based verify sees no drift.
97
+ */
98
+ function elementNonNullCheckName(tableName: string, columnName: string): string {
99
+ return `${tableName}_${columnName}_elem_not_null`;
100
+ }
117
101
 
118
- function issueOrder(issue: SchemaIssue): number {
119
- return ISSUE_KIND_ORDER[issue.kind] ?? 99;
102
+ /**
103
+ * Predicate enforcing that a scalar-array column carries no NULL element. The
104
+ * array column itself may be NULL (container nullability is the column's NOT NULL
105
+ * clause); `array_position` over a NULL array yields NULL, which a CHECK treats
106
+ * as satisfied, so a nullable array column is unaffected.
107
+ */
108
+ function elementNonNullCheckExpression(columnName: string): string {
109
+ return `array_position(${quoteIdentifier(columnName)}, NULL) IS NULL`;
120
110
  }
121
111
 
122
112
  // ============================================================================
@@ -136,558 +126,10 @@ function issueConflict(
136
126
  };
137
127
  }
138
128
 
139
- function isMissing(issue: SchemaIssue): boolean {
140
- if (issue.kind === 'enum_values_changed') return false;
141
- return issue.actual === undefined;
142
- }
143
-
144
- // ============================================================================
145
- // Issue planner
146
- // ============================================================================
147
-
148
- export interface IssuePlannerOptions {
149
- readonly issues: readonly SchemaIssue[];
150
- readonly toContract: Contract<SqlStorage>;
151
- readonly fromContract: Contract<SqlStorage> | null;
152
- readonly schemaName: string;
153
- readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;
154
- readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;
155
- /**
156
- * Current database schema IR. Strategies read this to detect whether a
157
- * structure already exists (e.g. `buildSchemaLookupMap` for shared-temp-
158
- * default safety, extension dependency checks). Defaults to an empty schema
159
- * when omitted so the planner can still run over "fresh DB" contract
160
- * snapshots.
161
- */
162
- readonly schema?: SqlSchemaIR;
163
- /**
164
- * Operation-class policy. `planIssues` filters calls whose `operationClass`
165
- * is not in `policy.allowedOperationClasses` and surfaces them as conflicts
166
- * instead of emitting disallowed DDL. Defaults to additive-only.
167
- */
168
- readonly policy?: MigrationOperationPolicy;
169
- /**
170
- * Framework components participating in this composition. Available to
171
- * future strategies that may consult component metadata at plan time.
172
- */
173
- readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
174
- readonly strategies?: readonly CallMigrationStrategy[];
175
- }
176
-
177
129
  export interface IssuePlannerValue {
178
130
  readonly calls: readonly PostgresOpFactoryCall[];
179
131
  }
180
132
 
181
- function toDdlColumn(
182
- name: string,
183
- column: StorageColumn,
184
- codecHooks: ReadonlyMap<string, CodecControlHooks>,
185
- storageTypes: Readonly<Record<string, StorageTypeInstance>>,
186
- ): DdlColumn {
187
- const typeSql = buildColumnTypeSql(column, codecHooks, storageTypes);
188
- const ddlDefault = postgresDefaultToDdlColumnDefault(column.default);
189
- const resolved = resolveColumnTypeMetadata(
190
- column,
191
- storageTypes as Record<string, StorageTypeInstance>,
192
- );
193
- const codecRef: CodecRef | undefined = resolved.codecId
194
- ? {
195
- codecId: resolved.codecId,
196
- ...(resolved.typeParams !== undefined
197
- ? {
198
- typeParams: blindCast<
199
- JsonValue,
200
- 'resolved.typeParams is JsonValue-shaped storage metadata; the narrowed (non-undefined) value lands in CodecRef.typeParams which is JsonValue'
201
- >(resolved.typeParams),
202
- }
203
- : {}),
204
- }
205
- : undefined;
206
- return contractFree.col(name, typeSql, {
207
- ...(!column.nullable ? { notNull: true } : {}),
208
- ...ifDefined('default', ddlDefault),
209
- ...ifDefined('codecRef', codecRef),
210
- });
211
- }
212
-
213
- function mapIssueToCall(
214
- issue: SchemaIssue,
215
- ctx: StrategyContext,
216
- ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
217
- const { schemaName, codecHooks, storageTypes } = ctx;
218
- // Per-table effective schema. `extra_table` issues intentionally
219
- // omit `namespaceId` — the live DB carries a table that
220
- // is not claimed by any contract namespace, so there is no contract
221
- // coordinate to project from. Those issues fall back to the planner's
222
- // global `ctx.schemaName`; every other issue dispatches through the
223
- // resolved namespace's polymorphic `ddlSchemaName`.
224
- const tableSchema = (issue: SchemaIssue): string => {
225
- if (issue.kind === 'extra_table') return schemaName;
226
- if (!('table' in issue) || !issue.table) return schemaName;
227
- return resolveDdlSchemaForNamespace(ctx, resolveNamespaceIdForIssue(issue));
228
- };
229
-
230
- switch (issue.kind) {
231
- case 'missing_schema': {
232
- const namespaceId = issue.namespaceId;
233
- if (!namespaceId)
234
- return notOk(
235
- issueConflict('unsupportedOperation', 'Missing schema issue has no namespaceId'),
236
- );
237
- const ddlSchemaName = resolveDdlSchemaForNamespace(ctx, namespaceId);
238
- return ok([new CreateSchemaCall(ddlSchemaName)]);
239
- }
240
-
241
- case 'missing_table': {
242
- if (!issue.table)
243
- return notOk(
244
- issueConflict('unsupportedOperation', 'Missing table issue has no table name'),
245
- );
246
- const namespaceId = resolveNamespaceIdForIssue(issue);
247
- const contractTable = tableAt(ctx.toContract.storage, namespaceId, issue.table);
248
- if (!contractTable) {
249
- return notOk(
250
- issueConflict(
251
- 'unsupportedOperation',
252
- `Table "${issue.table}" in namespace "${namespaceId}" reported missing but not found in destination contract`,
253
- ),
254
- );
255
- }
256
- const schemaForTable = tableSchema(issue);
257
- const ddlColumns: DdlColumn[] = Object.entries(contractTable.columns).map(([name, column]) =>
258
- toDdlColumn(name, column, codecHooks, storageTypes),
259
- );
260
- const ddlConstraints: DdlTableConstraint[] | undefined = contractTable.primaryKey
261
- ? [
262
- contractFree.primaryKey(contractTable.primaryKey.columns, {
263
- ...(contractTable.primaryKey.name ? { name: contractTable.primaryKey.name } : {}),
264
- }),
265
- ]
266
- : undefined;
267
- const calls: PostgresOpFactoryCall[] = [
268
- new CreateTableCall(schemaForTable, issue.table, ddlColumns, ddlConstraints),
269
- ];
270
- for (const index of contractTable.indexes) {
271
- const indexName = index.name ?? `${issue.table}_${index.columns.join('_')}_idx`;
272
- const extras: { type?: string; options?: Record<string, unknown> } = {};
273
- if (index.type !== undefined) extras.type = index.type;
274
- if (index.options !== undefined) extras.options = index.options;
275
- calls.push(
276
- new CreateIndexCall(schemaForTable, issue.table, indexName, [...index.columns], extras),
277
- );
278
- }
279
- const explicitIndexColumnSets = new Set(
280
- contractTable.indexes.map((idx) => idx.columns.join(',')),
281
- );
282
- for (const fk of contractTable.foreignKeys) {
283
- if (fk.constraint) {
284
- const fkName = fk.name ?? `${issue.table}_${fk.source.columns.join('_')}_fkey`;
285
- const fkSpec: ForeignKeySpec = {
286
- name: fkName,
287
- columns: fk.source.columns,
288
- references: {
289
- schema: fk.target.namespaceId,
290
- table: fk.target.tableName,
291
- columns: fk.target.columns,
292
- },
293
- ...(fk.onDelete !== undefined && { onDelete: fk.onDelete }),
294
- ...(fk.onUpdate !== undefined && { onUpdate: fk.onUpdate }),
295
- };
296
- calls.push(new AddForeignKeyCall(schemaForTable, issue.table, fkSpec));
297
- }
298
- if (fk.index && !explicitIndexColumnSets.has(fk.source.columns.join(','))) {
299
- const indexName = `${issue.table}_${fk.source.columns.join('_')}_idx`;
300
- calls.push(
301
- new CreateIndexCall(schemaForTable, issue.table, indexName, [...fk.source.columns]),
302
- );
303
- }
304
- }
305
- for (const unique of contractTable.uniques) {
306
- const constraintName = unique.name ?? `${issue.table}_${unique.columns.join('_')}_key`;
307
- calls.push(
308
- new AddUniqueCall(schemaForTable, issue.table, constraintName, [...unique.columns]),
309
- );
310
- }
311
- return ok(calls);
312
- }
313
-
314
- case 'missing_column':
315
- if (!issue.table || !issue.column)
316
- return notOk(
317
- issueConflict('unsupportedOperation', 'Missing column issue has no table/column name'),
318
- );
319
- {
320
- const namespaceId = resolveNamespaceIdForIssue(issue);
321
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
322
- issue.column
323
- ];
324
- if (!column)
325
- return notOk(
326
- issueConflict(
327
- 'unsupportedOperation',
328
- `Column "${issue.table}"."${issue.column}" not in destination contract`,
329
- ),
330
- );
331
- return ok([
332
- new AddColumnCall(
333
- tableSchema(issue),
334
- issue.table,
335
- toDdlColumn(issue.column, column, codecHooks, storageTypes),
336
- ),
337
- ]);
338
- }
339
-
340
- case 'default_missing':
341
- if (!issue.table || !issue.column)
342
- return notOk(
343
- issueConflict('unsupportedOperation', 'Default missing issue has no table/column name'),
344
- );
345
- {
346
- const namespaceId = resolveNamespaceIdForIssue(issue);
347
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
348
- issue.column
349
- ];
350
- if (!column?.default) {
351
- return notOk(
352
- issueConflict(
353
- 'unsupportedOperation',
354
- `Column "${issue.table}"."${issue.column}" has no default in contract`,
355
- ),
356
- );
357
- }
358
- const defaultSql = buildColumnDefaultSql(column.default, column);
359
- if (!defaultSql) return ok([]);
360
- return ok([new SetDefaultCall(tableSchema(issue), issue.table, issue.column, defaultSql)]);
361
- }
362
-
363
- case 'extra_table':
364
- if (!issue.table)
365
- return notOk(issueConflict('unsupportedOperation', 'Extra table issue has no table name'));
366
- return ok([new DropTableCall(tableSchema(issue), issue.table)]);
367
-
368
- case 'extra_column':
369
- if (!issue.table || !issue.column)
370
- return notOk(
371
- issueConflict('unsupportedOperation', 'Extra column issue has no table/column name'),
372
- );
373
- return ok([new DropColumnCall(tableSchema(issue), issue.table, issue.column)]);
374
-
375
- case 'extra_index':
376
- if (!issue.table || !issue.indexOrConstraint)
377
- return notOk(
378
- issueConflict('unsupportedOperation', 'Extra index issue has no table/index name'),
379
- );
380
- return ok([new DropIndexCall(tableSchema(issue), issue.table, issue.indexOrConstraint)]);
381
-
382
- case 'extra_unique_constraint':
383
- case 'extra_foreign_key':
384
- case 'extra_primary_key': {
385
- if (!issue.table)
386
- return notOk(
387
- issueConflict(
388
- 'unsupportedOperation',
389
- 'Extra constraint issue has no table/constraint name',
390
- ),
391
- );
392
- // `extra_primary_key` issues don't carry a constraint name — the
393
- // verifier only has the table. Fall back to `<table>_pkey`, matching
394
- // Postgres' default PK constraint naming and the old reconciliation
395
- // planner's behavior.
396
- const constraintName =
397
- issue.indexOrConstraint ??
398
- (issue.kind === 'extra_primary_key' ? `${issue.table}_pkey` : undefined);
399
- if (!constraintName)
400
- return notOk(
401
- issueConflict(
402
- 'unsupportedOperation',
403
- 'Extra constraint issue has no table/constraint name',
404
- ),
405
- );
406
- const kindMap = {
407
- extra_unique_constraint: 'unique' as const,
408
- extra_foreign_key: 'foreignKey' as const,
409
- extra_primary_key: 'primaryKey' as const,
410
- };
411
- return ok([
412
- new DropConstraintCall(
413
- tableSchema(issue),
414
- issue.table,
415
- constraintName,
416
- kindMap[issue.kind],
417
- ),
418
- ]);
419
- }
420
-
421
- case 'extra_default':
422
- if (!issue.table || !issue.column)
423
- return notOk(
424
- issueConflict('unsupportedOperation', 'Extra default issue has no table/column name'),
425
- );
426
- return ok([new DropDefaultCall(tableSchema(issue), issue.table, issue.column)]);
427
-
428
- case 'nullability_mismatch': {
429
- if (!issue.table || !issue.column)
430
- return notOk(
431
- issueConflict('nullabilityConflict', 'Nullability mismatch has no table/column name'),
432
- );
433
- const namespaceId = resolveNamespaceIdForIssue(issue);
434
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
435
- issue.column
436
- ];
437
- if (!column)
438
- return notOk(
439
- issueConflict(
440
- 'nullabilityConflict',
441
- `Column "${issue.table}"."${issue.column}" not found in destination contract`,
442
- ),
443
- );
444
- const schemaForTable = tableSchema(issue);
445
- return ok(
446
- column.nullable
447
- ? [new DropNotNullCall(schemaForTable, issue.table, issue.column)]
448
- : [new SetNotNullCall(schemaForTable, issue.table, issue.column)],
449
- );
450
- }
451
-
452
- case 'type_mismatch':
453
- if (!issue.table || !issue.column)
454
- return notOk(issueConflict('typeMismatch', 'Type mismatch has no table/column name'));
455
- {
456
- const namespaceId = resolveNamespaceIdForIssue(issue);
457
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
458
- issue.column
459
- ];
460
- if (!column)
461
- return notOk(
462
- issueConflict(
463
- 'typeMismatch',
464
- `Column "${issue.table}"."${issue.column}" not in destination contract`,
465
- ),
466
- );
467
- const hooksMap = codecHooks as Map<string, CodecControlHooks>;
468
- const typesMap = storageTypes as Record<string, StorageTypeInstance>;
469
- const qualifiedTargetType = buildColumnTypeSql(column, hooksMap, typesMap, false);
470
- const formatTypeExpected = buildExpectedFormatType(column, hooksMap, typesMap);
471
- return ok([
472
- new AlterColumnTypeCall(tableSchema(issue), issue.table, issue.column, {
473
- qualifiedTargetType,
474
- formatTypeExpected,
475
- rawTargetTypeForLabel: qualifiedTargetType,
476
- }),
477
- ]);
478
- }
479
-
480
- case 'default_mismatch':
481
- if (!issue.table || !issue.column)
482
- return notOk(
483
- issueConflict('unsupportedOperation', 'Default mismatch has no table/column name'),
484
- );
485
- {
486
- const namespaceId = resolveNamespaceIdForIssue(issue);
487
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
488
- issue.column
489
- ];
490
- if (!column?.default) return ok([]);
491
- const defaultSql = buildColumnDefaultSql(column.default, column);
492
- if (!defaultSql) return ok([]);
493
- return ok([
494
- new SetDefaultCall(tableSchema(issue), issue.table, issue.column, defaultSql, 'widening'),
495
- ]);
496
- }
497
-
498
- case 'primary_key_mismatch':
499
- if (!issue.table)
500
- return notOk(issueConflict('indexIncompatible', 'Primary key issue has no table name'));
501
- if (isMissing(issue)) {
502
- const namespaceId = resolveNamespaceIdForIssue(issue);
503
- const pk = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.primaryKey;
504
- if (!pk)
505
- return notOk(
506
- issueConflict('indexIncompatible', `No primary key in contract for "${issue.table}"`),
507
- );
508
- const constraintName = pk.name ?? `${issue.table}_pkey`;
509
- return ok([
510
- new AddPrimaryKeyCall(tableSchema(issue), issue.table, constraintName, pk.columns),
511
- ]);
512
- }
513
- return notOk(
514
- issueConflict(
515
- 'indexIncompatible',
516
- `Primary key on "${issue.table}" has different columns (expected: ${issue.expected}, actual: ${issue.actual})`,
517
- { table: issue.table },
518
- ),
519
- );
520
-
521
- case 'unique_constraint_mismatch':
522
- if (!issue.table)
523
- return notOk(
524
- issueConflict('indexIncompatible', 'Unique constraint issue has no table name'),
525
- );
526
- if (isMissing(issue) && issue.expected) {
527
- const columns = issue.expected.split(', ');
528
- const constraintName = `${issue.table}_${columns.join('_')}_key`;
529
- return ok([new AddUniqueCall(tableSchema(issue), issue.table, constraintName, columns)]);
530
- }
531
- return notOk(
532
- issueConflict(
533
- 'indexIncompatible',
534
- `Unique constraint on "${issue.table}" differs (expected: ${issue.expected}, actual: ${issue.actual})`,
535
- { table: issue.table },
536
- ),
537
- );
538
-
539
- case 'index_mismatch':
540
- if (!issue.table)
541
- return notOk(issueConflict('indexIncompatible', 'Index issue has no table name'));
542
- if (isMissing(issue) && issue.expected) {
543
- const namespaceId = resolveNamespaceIdForIssue(issue);
544
- const columns = issue.expected.split(', ');
545
- const contractIndex = tableAt(
546
- ctx.toContract.storage,
547
- namespaceId,
548
- issue.table,
549
- )?.indexes.find((idx: StorageTable['indexes'][number]) =>
550
- arraysEqual(idx.columns, columns),
551
- );
552
- const indexName = contractIndex?.name ?? `${issue.table}_${columns.join('_')}_idx`;
553
- const extras: { type?: string; options?: Record<string, unknown> } = {};
554
- if (contractIndex?.type !== undefined) extras.type = contractIndex.type;
555
- if (contractIndex?.options !== undefined) extras.options = contractIndex.options;
556
- return ok([
557
- new CreateIndexCall(tableSchema(issue), issue.table, indexName, columns, extras),
558
- ]);
559
- }
560
- return notOk(
561
- issueConflict(
562
- 'indexIncompatible',
563
- `Index on "${issue.table}" differs (expected: ${issue.expected}, actual: ${issue.actual})`,
564
- { table: issue.table },
565
- ),
566
- );
567
-
568
- case 'check_missing': {
569
- if (!issue.table || !issue.indexOrConstraint)
570
- return notOk(
571
- issueConflict('unsupportedOperation', 'Check missing issue has no table/constraint name'),
572
- );
573
- // check_missing is normally consumed by checkConstraintPlanCallStrategy.
574
- // This case handles any that arrive here (e.g. in tests that invoke
575
- // mapIssueToCall directly or skip the strategy).
576
- return notOk(
577
- issueConflict(
578
- 'unsupportedOperation',
579
- `Check constraint "${issue.indexOrConstraint}" missing on "${issue.table}" — handled by checkConstraintPlanCallStrategy`,
580
- ),
581
- );
582
- }
583
-
584
- case 'check_mismatch': {
585
- if (!issue.table || !issue.indexOrConstraint)
586
- return notOk(
587
- issueConflict(
588
- 'unsupportedOperation',
589
- 'Check mismatch issue has no table/constraint name',
590
- ),
591
- );
592
- return notOk(
593
- issueConflict(
594
- 'unsupportedOperation',
595
- `Check constraint "${issue.indexOrConstraint}" values mismatch on "${issue.table}" — handled by checkConstraintPlanCallStrategy`,
596
- ),
597
- );
598
- }
599
-
600
- case 'check_removed': {
601
- if (!issue.table || !issue.indexOrConstraint)
602
- return notOk(
603
- issueConflict('unsupportedOperation', 'Check removed issue has no table/constraint name'),
604
- );
605
- return ok([
606
- new DropCheckConstraintCall(tableSchema(issue), issue.table, issue.indexOrConstraint),
607
- ]);
608
- }
609
-
610
- case 'foreign_key_mismatch':
611
- if (!issue.table)
612
- return notOk(issueConflict('foreignKeyConflict', 'Foreign key issue has no table name'));
613
- if (isMissing(issue) && issue.expected) {
614
- const arrowIdx = issue.expected.indexOf(' -> ');
615
- if (arrowIdx >= 0) {
616
- const namespaceId = resolveNamespaceIdForIssue(issue);
617
- const columns = issue.expected.slice(0, arrowIdx).split(', ');
618
- const fkName = `${issue.table}_${columns.join('_')}_fkey`;
619
- const fk = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.foreignKeys.find(
620
- (k) => k.source.columns.join(', ') === columns.join(', '),
621
- );
622
- if (fk) {
623
- const fkSpec: ForeignKeySpec = {
624
- name: fkName,
625
- columns: fk.source.columns,
626
- references: {
627
- schema: fk.target.namespaceId,
628
- table: fk.target.tableName,
629
- columns: fk.target.columns,
630
- },
631
- ...(fk.onDelete !== undefined && { onDelete: fk.onDelete }),
632
- ...(fk.onUpdate !== undefined && { onUpdate: fk.onUpdate }),
633
- };
634
- return ok([new AddForeignKeyCall(tableSchema(issue), issue.table, fkSpec)]);
635
- }
636
- return notOk(
637
- issueConflict(
638
- 'foreignKeyConflict',
639
- `Foreign key on "${issue.table}" (${columns.join(', ')}) not found in destination contract`,
640
- { table: issue.table },
641
- ),
642
- );
643
- }
644
- }
645
- return notOk(
646
- issueConflict(
647
- 'foreignKeyConflict',
648
- `Foreign key on "${issue.table}" differs (expected: ${issue.expected}, actual: ${issue.actual})`,
649
- { table: issue.table },
650
- ),
651
- );
652
-
653
- case 'type_missing': {
654
- if (!issue.typeName)
655
- return notOk(issueConflict('unsupportedOperation', 'Type missing issue has no typeName'));
656
- const typeInstance = ctx.toContract.storage.types?.[issue.typeName];
657
- if (!typeInstance) {
658
- return notOk(
659
- issueConflict(
660
- 'unsupportedOperation',
661
- `Type "${issue.typeName}" reported missing but not found in destination contract`,
662
- ),
663
- );
664
- }
665
- return notOk(
666
- issueConflict(
667
- 'unsupportedOperation',
668
- `Type "${issue.typeName}" uses codec "${typeInstance.codecId}" — only value-set types are supported`,
669
- ),
670
- );
671
- }
672
-
673
- case 'type_values_mismatch':
674
- return notOk(
675
- issueConflict(
676
- 'unsupportedOperation',
677
- `Type "${issue.typeName ?? 'unknown'}" values differ — type alteration not yet supported`,
678
- ),
679
- );
680
-
681
- default:
682
- return notOk(
683
- issueConflict(
684
- 'unsupportedOperation',
685
- `Unhandled issue kind: ${(issue as SchemaIssue).kind}`,
686
- ),
687
- );
688
- }
689
- }
690
-
691
133
  /**
692
134
  * Classifies calls into dependency order categories for correct DDL sequencing.
693
135
  */
@@ -695,6 +137,8 @@ type CallCategory =
695
137
  | 'dep'
696
138
  | 'drop'
697
139
  | 'table'
140
+ | 'rlsEnable'
141
+ | 'rlsPolicy'
698
142
  | 'column'
699
143
  | 'alter'
700
144
  | 'primaryKey'
@@ -712,8 +156,11 @@ function classifyCall(call: PostgresOpFactoryCall): CallCategory {
712
156
  switch (call.factoryName) {
713
157
  case 'createExtension':
714
158
  case 'createSchema':
159
+ case 'createNativeEnumType':
160
+ case 'addNativeEnumValue':
715
161
  return 'dep';
716
162
  case 'dropTable':
163
+ case 'dropNativeEnumType':
717
164
  case 'dropColumn':
718
165
  case 'dropConstraint':
719
166
  case 'dropCheckConstraint':
@@ -724,6 +171,13 @@ function classifyCall(call: PostgresOpFactoryCall): CallCategory {
724
171
  return 'unique'; // after uniques, before indexes
725
172
  case 'createTable':
726
173
  return 'table';
174
+ case 'enableRowLevelSecurity':
175
+ case 'disableRowLevelSecurity':
176
+ return 'rlsEnable';
177
+ case 'createRlsPolicy':
178
+ return 'rlsPolicy';
179
+ case 'dropRlsPolicy':
180
+ return 'drop';
727
181
  case 'addColumn':
728
182
  return 'column';
729
183
  case 'alterColumnType':
@@ -760,17 +214,6 @@ function classifyCall(call: PostgresOpFactoryCall): CallCategory {
760
214
  }
761
215
  }
762
216
 
763
- /** Stable lexical key used to order issues within the same kind bucket. */
764
- function issueKey(issue: SchemaIssue): string {
765
- const table = 'table' in issue && typeof issue.table === 'string' ? issue.table : '';
766
- const column = 'column' in issue && typeof issue.column === 'string' ? issue.column : '';
767
- const name =
768
- 'indexOrConstraint' in issue && typeof issue.indexOrConstraint === 'string'
769
- ? issue.indexOrConstraint
770
- : '';
771
- return `${table}\u0000${column}\u0000${name}`;
772
- }
773
-
774
217
  // When no policy is explicitly supplied (test-only path; production callers
775
218
  // always pass one), allow every class so strategies that gate on
776
219
  // `'data'` (data-safe placeholders) still fire — the test is treated as
@@ -781,7 +224,7 @@ const DEFAULT_POLICY: MigrationOperationPolicy = {
781
224
  };
782
225
 
783
226
  function emptySchemaIR(): SqlSchemaIR {
784
- return { tables: {} };
227
+ return new SqlSchemaIR({ tables: {} });
785
228
  }
786
229
 
787
230
  function conflictKindForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['kind'] {
@@ -814,17 +257,22 @@ function locationForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['locat
814
257
  typeName?: string;
815
258
  };
816
259
  const location: {
817
- table?: string;
260
+ entityKind?: string;
261
+ entityName?: string;
818
262
  column?: string;
819
263
  index?: string;
820
264
  constraint?: string;
821
- type?: string;
822
265
  } = {};
823
- if (anyCall.tableName) location.table = anyCall.tableName;
266
+ if (anyCall.tableName) {
267
+ location.entityKind = 'table';
268
+ location.entityName = anyCall.tableName;
269
+ } else if (anyCall.typeName) {
270
+ location.entityKind = 'native_enum';
271
+ location.entityName = anyCall.typeName;
272
+ }
824
273
  if (anyCall.columnName) location.column = anyCall.columnName;
825
274
  if (anyCall.indexName) location.index = anyCall.indexName;
826
275
  if (anyCall.constraintName) location.constraint = anyCall.constraintName;
827
- if (anyCall.typeName) location.type = anyCall.typeName;
828
276
  return Object.keys(location).length > 0 ? (location as SqlPlannerConflictLocation) : undefined;
829
277
  }
830
278
 
@@ -842,13 +290,734 @@ function conflictForDisallowedCall(
842
290
  };
843
291
  }
844
292
 
293
+ // ============================================================================
294
+ // Node-based issue planner
295
+ // ============================================================================
296
+ //
297
+ // Consumes node-typed `SchemaDiffIssue`s (from the one differ —
298
+ // `buildPostgresPlanDiff`) and reads the diff node each issue carries
299
+ // (`issue.expected` / `issue.actual`). Column DDL (type/default SQL) resolves
300
+ // from the column node's `codecRef` against the codec hooks the caller holds
301
+ // (`column-ddl-rendering.ts`), never the contract. The retained subsystems —
302
+ // codec type-operations, field-lifecycle hooks, the NOT-NULL temp-default
303
+ // deferred DDL, control-policy disposition — keep the contract via the
304
+ // strategy context, per the slice's scope.
305
+
306
+ /** The diff node an issue concerns — expected when present, else the actual (extra) node. */
307
+ export function issueNode(issue: SchemaDiffIssue): SqlSchemaIRNode | undefined {
308
+ const node = issue.expected ?? issue.actual;
309
+ if (node === undefined) return undefined;
310
+ return blindCast<
311
+ SqlSchemaIRNode,
312
+ 'every node in a Postgres schema diff tree is a SqlSchemaIRNode; nodeKind is its required discriminant'
313
+ >(node);
314
+ }
315
+
316
+ /** DDL schema segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */
317
+ export function issueSchemaName(issue: SchemaDiffIssue): string | undefined {
318
+ return issue.path[1];
319
+ }
320
+
321
+ /** Table segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */
322
+ export function issueTableName(issue: SchemaDiffIssue): string | undefined {
323
+ return issue.path[2];
324
+ }
325
+
326
+ /** Column name embedded in a column/default issue path segment (`column:<name>`). */
327
+ export function issueColumnName(issue: SchemaDiffIssue): string | undefined {
328
+ const segment = issue.path[3];
329
+ if (segment === undefined || !segment.startsWith('column:')) return undefined;
330
+ return segment.slice('column:'.length);
331
+ }
332
+
333
+ /**
334
+ * The DDL schema name to use when EMITTING an op against `ddlSchemaName` (the
335
+ * diff tree's resolved physical schema, `issueSchemaName(issue)`). The
336
+ * unbound namespace's diff-tree identity resolves to `public` (a concrete
337
+ * physical default the differ needs in order to compare its tree against
338
+ * introspection — `resolveDdlSchemaForNamespaceStorage`), but DDL EMISSION
339
+ * must stay unqualified so the live connection's `search_path` resolves it
340
+ * at runtime (`boundSchema`). Recovers the logical namespace id via the
341
+ * contract and substitutes the unbound sentinel back in when it resolves
342
+ * there; every other namespace's `ddlSchemaName` already agrees between the
343
+ * two resolution paths, so it passes through unchanged.
344
+ */
345
+ export function emissionSchemaName(ctx: StrategyContext, ddlSchemaName: string): string {
346
+ const namespaceId = resolveNamespaceIdForDdlSchema(ctx.toContract, ddlSchemaName);
347
+ return namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchemaName;
348
+ }
349
+
350
+ /**
351
+ * Whether a column node is a scalar-array (`many: true`) column. The family
352
+ * converter (`contractToSchemaIR`'s `convertColumn`) never stamps `many` on
353
+ * the derived node — array-ness is folded into the `[]` suffix on
354
+ * `nativeType` instead — so the node-derived check reads the suffix; `.many`
355
+ * is still checked first for nodes a caller stamps directly (e.g. hand-built
356
+ * test fixtures, or an adapter that populates it at introspection).
357
+ */
358
+ function isManyColumn(column: SqlColumnIR): boolean {
359
+ return column.many === true || column.nativeType.endsWith('[]');
360
+ }
361
+
362
+ /** Whether the expected/actual native type (resolved, or raw+many fallback) differs — mirrors `SqlColumnIR.isEqualTo`'s type comparison. */
363
+ export function columnTypeChanged(expected: SqlColumnIR, actual: SqlColumnIR): boolean {
364
+ if (expected.resolvedNativeType !== undefined && actual.resolvedNativeType !== undefined) {
365
+ return expected.resolvedNativeType !== actual.resolvedNativeType;
366
+ }
367
+ return (
368
+ expected.nativeType !== actual.nativeType || Boolean(expected.many) !== Boolean(actual.many)
369
+ );
370
+ }
371
+
372
+ // ----------------------------------------------------------------------------
373
+ // Node-keyed issue ordering (re-keys ISSUE_KIND_ORDER on nodeKind + reason)
374
+ // ----------------------------------------------------------------------------
375
+
376
+ /**
377
+ * Re-keys the legacy `ISSUE_KIND_ORDER` on `(nodeKind, reason)`, numbers
378
+ * preserved so the dependency intent stays legible. Final emission order is
379
+ * fixed downstream by `classifyCall` bucketing (dep → drop → table → column →
380
+ * recipe → alter → primaryKey → unique → index → foreignKey), so this only
381
+ * breaks ties within a bucket.
382
+ */
383
+ export function nodeIssueOrder(issue: SchemaDiffIssue): number {
384
+ const node = issueNode(issue);
385
+ if (node === undefined) return 99;
386
+ switch (node.nodeKind) {
387
+ case PostgresSchemaNodeKind.namespace:
388
+ return 1;
389
+ case PostgresSchemaNodeKind.nativeEnum:
390
+ // Creates order right after namespace creates within the 'dep' bucket
391
+ // (CREATE SCHEMA before CREATE TYPE); drops order after table drops
392
+ // within the 'drop' bucket (DROP TYPE only after its dependents left).
393
+ return issue.reason === 'not-expected' ? 17 : 2;
394
+ case RelationalSchemaNodeKind.foreignKey:
395
+ return issue.reason === 'not-expected' ? 10 : 60;
396
+ case RelationalSchemaNodeKind.unique:
397
+ return issue.reason === 'not-expected' ? 11 : 51;
398
+ case RelationalSchemaNodeKind.primaryKey:
399
+ return issue.reason === 'not-expected' ? 12 : 50;
400
+ case RelationalSchemaNodeKind.index:
401
+ return issue.reason === 'not-expected' ? 13 : 52;
402
+ case RelationalSchemaNodeKind.columnDefault:
403
+ if (issue.reason === 'not-expected') return 14;
404
+ return issue.reason === 'not-found' ? 42 : 43;
405
+ case RelationalSchemaNodeKind.column:
406
+ if (issue.reason === 'not-expected') return 15;
407
+ return issue.reason === 'not-found' ? 30 : 40;
408
+ case PostgresSchemaNodeKind.table:
409
+ return issue.reason === 'not-expected' ? 16 : 20;
410
+ case RelationalSchemaNodeKind.check:
411
+ if (issue.reason === 'not-found') return 53;
412
+ return issue.reason === 'not-expected' ? 55 : 54;
413
+ default:
414
+ return 99;
415
+ }
416
+ }
417
+
418
+ /** Deterministic tiebreak within an order bucket: the diff path already encodes schema → table → child. */
419
+ export function nodeIssueKey(issue: SchemaDiffIssue): string {
420
+ return issue.path.join(' ');
421
+ }
422
+
423
+ // ----------------------------------------------------------------------------
424
+ // Subtree coalescing (the planner's responsibility per the differ's contract)
425
+ // ----------------------------------------------------------------------------
426
+
427
+ /**
428
+ * The generic differ is total: a missing/extra table (or column) emits an
429
+ * issue for itself AND for every node in its subtree. `CreateTable`/`DropTable`
430
+ * and `AddColumn`/`DropColumn` already account for the whole subtree, so the
431
+ * nested issues are redundant — coalescing drops any issue whose path is a
432
+ * strict descendant of a `not-found`/`not-expected` issue's path. Run over the
433
+ * relational subset ONLY (policy issues and synthesized namespace issues are
434
+ * handled on their own paths, never coalesced against tables).
435
+ */
436
+ export function coalesceSubtreeIssues<TNode extends DiffableNode = DiffableNode>(
437
+ issues: readonly SchemaDiffIssue<TNode>[],
438
+ ): readonly SchemaDiffIssue<TNode>[] {
439
+ const collapsingPaths = issues
440
+ .filter((issue) => issue.reason === 'not-found' || issue.reason === 'not-expected')
441
+ .map((issue) => issue.path);
442
+ if (collapsingPaths.length === 0) return issues;
443
+ return issues.filter(
444
+ (issue) => !collapsingPaths.some((ancestor) => isStrictDescendantPath(issue.path, ancestor)),
445
+ );
446
+ }
447
+
448
+ function isStrictDescendantPath(path: readonly string[], ancestor: readonly string[]): boolean {
449
+ if (path.length <= ancestor.length) return false;
450
+ for (let i = 0; i < ancestor.length; i += 1) {
451
+ if (path[i] !== ancestor[i]) return false;
452
+ }
453
+ return true;
454
+ }
455
+
456
+ // ----------------------------------------------------------------------------
457
+ // Node → call construction
458
+ // ----------------------------------------------------------------------------
459
+
460
+ function fkSpecFromNode(fk: SqlForeignKeyIR, tableName: string): ForeignKeySpec {
461
+ const name = fk.name ?? `${tableName}_${fk.columns.join('_')}_fkey`;
462
+ return {
463
+ name,
464
+ columns: [...fk.columns],
465
+ references: {
466
+ // The raw target namespace coordinate, matching the retired coordinate
467
+ // path's `references.schema: fk.target.namespaceId` (the FK node stamps
468
+ // it verbatim). The op renderer qualifies the REFERENCES clause from it.
469
+ schema: fk.referencedSchema ?? '',
470
+ table: fk.referencedTable,
471
+ columns: [...fk.referencedColumns],
472
+ },
473
+ ...ifDefined('onDelete', fk.onDelete),
474
+ ...ifDefined('onUpdate', fk.onUpdate),
475
+ };
476
+ }
477
+
478
+ /**
479
+ * Builds the `CreateTable` + child `CreateIndex` / `AddForeignKey` / `AddUnique`
480
+ * calls for a newly-expected table, reading only the table node's children. The
481
+ * PK and element-non-null CHECKs go inline as table constraints; indexes
482
+ * (declared + FK-backing, already merged and ordered at derivation) and the
483
+ * FK / unique constraints are separate calls (re-bucketed downstream). Every
484
+ * column's DDL is resolved from its `codecRef` via `renderColumnDdl`.
485
+ */
486
+ function buildCreateTableCallsFromNode(
487
+ schemaName: string,
488
+ ddlSchemaName: string,
489
+ table: PostgresTableSchemaNode,
490
+ codecHooks: ReadonlyMap<string, CodecControlHooks>,
491
+ ): PostgresOpFactoryCall[] {
492
+ const ddlColumns = Object.values(table.columns).map((c) =>
493
+ renderColumnDdl(c.name, c, codecHooks),
494
+ );
495
+ const primaryKeyConstraints: DdlTableConstraint[] = table.primaryKey
496
+ ? [
497
+ contractFree.primaryKey([...table.primaryKey.columns], {
498
+ ...ifDefined('name', table.primaryKey.name),
499
+ }),
500
+ ]
501
+ : [];
502
+ const elementNonNullChecks: DdlTableConstraint[] = Object.values(table.columns)
503
+ .filter((c) => isManyColumn(c))
504
+ .map((c) =>
505
+ contractFree.checkExpression(
506
+ elementNonNullCheckName(table.name, c.name),
507
+ elementNonNullCheckExpression(c.name),
508
+ ),
509
+ );
510
+ const allTableConstraints = [...primaryKeyConstraints, ...elementNonNullChecks];
511
+ const calls: PostgresOpFactoryCall[] = [
512
+ new CreateTableCall(
513
+ schemaName,
514
+ table.name,
515
+ ddlColumns,
516
+ allTableConstraints.length > 0 ? allTableConstraints : undefined,
517
+ ),
518
+ ];
519
+ for (const index of table.indexes) {
520
+ const indexName = index.name ?? defaultIndexName(table.name, index.columns);
521
+ const extras: { type?: string; options?: Record<string, unknown> } = {};
522
+ if (index.type !== undefined) extras.type = index.type;
523
+ if (index.options !== undefined) extras.options = index.options;
524
+ calls.push(new CreateIndexCall(schemaName, table.name, indexName, [...index.columns], extras));
525
+ }
526
+ for (const fk of table.foreignKeys) {
527
+ calls.push(new AddForeignKeyCall(schemaName, table.name, fkSpecFromNode(fk, table.name)));
528
+ }
529
+ for (const unique of table.uniques) {
530
+ const constraintName = unique.name ?? `${table.name}_${unique.columns.join('_')}_key`;
531
+ calls.push(new AddUniqueCall(schemaName, table.name, constraintName, [...unique.columns]));
532
+ }
533
+ // Marker-driven: a newly-created table that is RLS-controlled enables RLS
534
+ // as part of its creation bundle. The policy set never decides this. The
535
+ // resolved schema (not the emission sentinel) binds into the op's
536
+ // relrowsecurity checks.
537
+ if (table.rlsEnabled) {
538
+ calls.push(new EnableRowLevelSecurityCall(ddlSchemaName, table.name));
539
+ }
540
+ return calls;
541
+ }
542
+
543
+ function nodeConflict(kind: SqlPlannerConflict['kind'], message: string): SqlPlannerConflict {
544
+ return issueConflict(kind, message);
545
+ }
546
+
547
+ /**
548
+ * True when `actualMembers` (the live database's ordered members) is a
549
+ * strict, order-preserving prefix of `expectedMembers` (the contract's) —
550
+ * the database already carries every contract member, in declaration
551
+ * order, and the contract declares at least one member the database still
552
+ * lacks. Any other relationship — a renamed value, a removed value, a
553
+ * reordering, or the database holding members the contract lacks — is not
554
+ * a suffix append.
555
+ */
556
+ function isNativeEnumSuffixAppend(
557
+ actualMembers: readonly string[],
558
+ expectedMembers: readonly string[],
559
+ ): boolean {
560
+ if (actualMembers.length >= expectedMembers.length) return false;
561
+ return actualMembers.every((member, index) => member === expectedMembers[index]);
562
+ }
563
+
564
+ /** Operator-worded refusal for a native-enum member change beyond a suffix append (design ruling — tests match this verbatim). */
565
+ function nativeEnumMemberChangeRefusal(options: {
566
+ readonly ddlSchemaName: string;
567
+ readonly typeName: string;
568
+ readonly expectedMembers: readonly string[];
569
+ readonly actualMembers: readonly string[];
570
+ }): string {
571
+ return (
572
+ `Native enum type "${options.ddlSchemaName}"."${options.typeName}" changed beyond appending new values ` +
573
+ `(contract declares [${options.expectedMembers.join(', ')}], database has [${options.actualMembers.join(', ')}]). ` +
574
+ "Prisma Next does not modify a native enum's existing values (rename, removal, reorder) — " +
575
+ 'see https://pris.ly/d/postgres-native-enums. Author the change manually with `migration new`.'
576
+ );
577
+ }
578
+
579
+ /**
580
+ * Managed native-enum issue -> op lowering. A missing declared type creates
581
+ * it; an unclaimed live type drops it (ownership-scoped upstream by
582
+ * `retainUnownedExtras`, destructiveness gated by the operation-class
583
+ * policy); a paired member-value mismatch lowers to one `ALTER TYPE ... ADD
584
+ * VALUE` per appended member when the database's members are a strict,
585
+ * order-preserving prefix of the contract's — any other change (rename,
586
+ * removal, reorder, or the database holding members the contract lacks) is
587
+ * refused with a NAMED diagnostic, never a silent no-op and never a
588
+ * drop-and-recreate.
589
+ */
590
+ function mapNativeEnumNodeIssue(
591
+ issue: SchemaDiffIssue,
592
+ ctx: StrategyContext,
593
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
594
+ const ddlSchemaName = issueSchemaName(issue);
595
+ if (ddlSchemaName === undefined) {
596
+ return notOk(
597
+ nodeConflict(
598
+ 'unsupportedOperation',
599
+ `Enum issue has no schema in its path: ${issue.path.join('/')}`,
600
+ ),
601
+ );
602
+ }
603
+ const schemaName = emissionSchemaName(ctx, ddlSchemaName);
604
+ if (issue.reason === 'not-found') {
605
+ const expected = blindCast<
606
+ PostgresNativeEnumSchemaNode,
607
+ 'a not-found native-enum issue always carries the expected PostgresNativeEnumSchemaNode'
608
+ >(issue.expected);
609
+ return ok([new CreateNativeEnumTypeCall(schemaName, expected.typeName, expected.members)]);
610
+ }
611
+ if (issue.reason === 'not-expected') {
612
+ const actual = blindCast<
613
+ PostgresNativeEnumSchemaNode,
614
+ 'a not-expected native-enum issue always carries the actual PostgresNativeEnumSchemaNode'
615
+ >(issue.actual);
616
+ return ok([new DropNativeEnumTypeCall(schemaName, actual.typeName)]);
617
+ }
618
+ const expected = blindCast<
619
+ PostgresNativeEnumSchemaNode,
620
+ 'a not-equal native-enum issue carries both sides; the expected node names the type'
621
+ >(issue.expected);
622
+ const actual = blindCast<
623
+ PostgresNativeEnumSchemaNode,
624
+ 'a not-equal native-enum issue carries both sides'
625
+ >(issue.actual);
626
+ if (isNativeEnumSuffixAppend(actual.members, expected.members)) {
627
+ const appendedValues = expected.members.slice(actual.members.length);
628
+ return ok(
629
+ appendedValues.map(
630
+ (value) => new AddNativeEnumValueCall(schemaName, expected.typeName, value),
631
+ ),
632
+ );
633
+ }
634
+ return notOk(
635
+ nodeConflict(
636
+ 'unsupportedOperation',
637
+ nativeEnumMemberChangeRefusal({
638
+ ddlSchemaName,
639
+ typeName: expected.typeName,
640
+ expectedMembers: expected.members,
641
+ actualMembers: actual.members,
642
+ }),
643
+ ),
644
+ );
645
+ }
646
+
647
+ function mapTableNodeIssue(
648
+ issue: SchemaDiffIssue,
649
+ schemaName: string,
650
+ // The diff tree's RESOLVED physical schema. Enablement ops bind it into
651
+ // their `pg_class`/`pg_namespace` checks (the emission sentinel would
652
+ // never match a live nspname), mirroring the schema the retired
653
+ // policy-half enable resolved via `resolveDdlSchemaForNamespaceStorage`.
654
+ ddlSchemaName: string,
655
+ codecHooks: ReadonlyMap<string, CodecControlHooks>,
656
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
657
+ if (issue.reason === 'not-found') {
658
+ const table = blindCast<
659
+ PostgresTableSchemaNode,
660
+ 'a not-found table issue always carries the expected PostgresTableSchemaNode'
661
+ >(issue.expected);
662
+ return ok(buildCreateTableCallsFromNode(schemaName, ddlSchemaName, table, codecHooks));
663
+ }
664
+ if (issue.reason === 'not-expected') {
665
+ const table = blindCast<
666
+ PostgresTableSchemaNode,
667
+ 'a not-expected table issue always carries the actual PostgresTableSchemaNode'
668
+ >(issue.actual);
669
+ return ok([new DropTableCall(schemaName, table.name)]);
670
+ }
671
+ // A paired table `not-equal` means enablement drift TODAY, because
672
+ // `isEqualTo` compares only name + `rlsEnabled`. Key on the actual
673
+ // expected-vs-actual `rlsEnabled` delta rather than assuming it: emit ENABLE
674
+ // when it flipped on, DISABLE when it flipped off, and fail loud when
675
+ // `rlsEnabled` matches on both sides — that means a second table attribute
676
+ // drifted into `isEqualTo` and this mapper does not yet handle it. The
677
+ // expected side is authoritative (marker-driven, never the policy set).
678
+ const expected = blindCast<
679
+ PostgresTableSchemaNode,
680
+ 'a not-equal table issue always carries the expected PostgresTableSchemaNode'
681
+ >(issue.expected);
682
+ const actual = blindCast<
683
+ PostgresTableSchemaNode,
684
+ 'a not-equal table issue always carries the actual PostgresTableSchemaNode'
685
+ >(issue.actual);
686
+ if (expected.rlsEnabled && !actual.rlsEnabled) {
687
+ return ok([new EnableRowLevelSecurityCall(ddlSchemaName, expected.name)]);
688
+ }
689
+ if (!expected.rlsEnabled && actual.rlsEnabled) {
690
+ return ok([new DisableRowLevelSecurityCall(ddlSchemaName, expected.name)]);
691
+ }
692
+ return notOk(
693
+ nodeConflict(
694
+ 'unsupportedOperation',
695
+ `unhandled table-attribute drift on "${expected.name}": table not-equal with no rlsEnabled delta (a second table attribute drifted)`,
696
+ ),
697
+ );
698
+ }
699
+
700
+ function mapColumnNodeIssue(
701
+ issue: SchemaDiffIssue,
702
+ schemaName: string,
703
+ tableName: string,
704
+ codecHooks: ReadonlyMap<string, CodecControlHooks>,
705
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
706
+ if (issue.reason === 'not-found') {
707
+ const column = blindCast<
708
+ SqlColumnIR,
709
+ 'a not-found column issue always carries the expected column node'
710
+ >(issue.expected);
711
+ return ok([
712
+ new AddColumnCall(schemaName, tableName, renderColumnDdl(column.name, column, codecHooks)),
713
+ ]);
714
+ }
715
+ if (issue.reason === 'not-expected') {
716
+ const column = blindCast<
717
+ SqlColumnIR,
718
+ 'a not-expected column issue always carries the actual column node'
719
+ >(issue.actual);
720
+ return ok([new DropColumnCall(schemaName, tableName, column.name)]);
721
+ }
722
+ // not-equal: Postgres alters in place — type drift and/or nullability drift.
723
+ const expected = blindCast<
724
+ SqlColumnIR,
725
+ 'a not-equal column issue always carries the expected column node'
726
+ >(issue.expected);
727
+ const actual = blindCast<
728
+ SqlColumnIR,
729
+ 'a not-equal column issue always carries the actual column node'
730
+ >(issue.actual);
731
+ const calls: PostgresOpFactoryCall[] = [];
732
+ if (columnTypeChanged(expected, actual)) {
733
+ const { qualifiedTargetType, formatTypeExpected } = renderColumnAlterType(expected, codecHooks);
734
+ calls.push(
735
+ new AlterColumnTypeCall(schemaName, tableName, expected.name, {
736
+ qualifiedTargetType,
737
+ formatTypeExpected,
738
+ rawTargetTypeForLabel: qualifiedTargetType,
739
+ }),
740
+ );
741
+ }
742
+ if (expected.nullable !== actual.nullable) {
743
+ calls.push(
744
+ expected.nullable
745
+ ? new DropNotNullCall(schemaName, tableName, expected.name)
746
+ : new SetNotNullCall(schemaName, tableName, expected.name),
747
+ );
748
+ }
749
+ return ok(calls);
750
+ }
751
+
752
+ function mapColumnDefaultNodeIssue(
753
+ issue: SchemaDiffIssue,
754
+ schemaName: string,
755
+ tableName: string,
756
+ columnName: string,
757
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
758
+ if (issue.reason === 'not-expected') {
759
+ return ok([new DropDefaultCall(schemaName, tableName, columnName)]);
760
+ }
761
+ // not-found (SET DEFAULT, additive) or not-equal (SET DEFAULT, widening).
762
+ if (issue.expected === undefined) return ok([]);
763
+ const defaultNode = blindCast<
764
+ SqlColumnDefaultIR,
765
+ 'a not-found/not-equal column-default issue always carries the expected default node'
766
+ >(issue.expected);
767
+ const defaultSql = renderColumnDefaultSql(defaultNode);
768
+ if (!defaultSql) return ok([]);
769
+ return ok([
770
+ new SetDefaultCall(
771
+ schemaName,
772
+ tableName,
773
+ columnName,
774
+ defaultSql,
775
+ issue.reason === 'not-equal' ? 'widening' : 'additive',
776
+ ),
777
+ ]);
778
+ }
779
+
780
+ function mapPrimaryKeyNodeIssue(
781
+ issue: SchemaDiffIssue,
782
+ schemaName: string,
783
+ tableName: string,
784
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
785
+ if (issue.reason === 'not-found') {
786
+ const pk = blindCast<
787
+ { readonly columns: readonly string[]; readonly name?: string },
788
+ 'a not-found primary-key issue always carries the expected PrimaryKey node'
789
+ >(issue.expected);
790
+ const constraintName = pk.name ?? `${tableName}_pkey`;
791
+ return ok([new AddPrimaryKeyCall(schemaName, tableName, constraintName, [...pk.columns])]);
792
+ }
793
+ if (issue.reason === 'not-expected') {
794
+ const pk = blindCast<
795
+ { readonly name?: string },
796
+ 'a not-expected primary-key issue always carries the actual PrimaryKey node'
797
+ >(issue.actual);
798
+ return ok([
799
+ new DropConstraintCall(schemaName, tableName, pk.name ?? `${tableName}_pkey`, 'primaryKey'),
800
+ ]);
801
+ }
802
+ return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));
803
+ }
804
+
805
+ function mapForeignKeyNodeIssue(
806
+ issue: SchemaDiffIssue,
807
+ schemaName: string,
808
+ tableName: string,
809
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
810
+ if (issue.reason === 'not-found') {
811
+ const fk = blindCast<
812
+ SqlForeignKeyIR,
813
+ 'a not-found foreign-key issue always carries the expected foreign-key node'
814
+ >(issue.expected);
815
+ return ok([new AddForeignKeyCall(schemaName, tableName, fkSpecFromNode(fk, tableName))]);
816
+ }
817
+ if (issue.reason === 'not-expected') {
818
+ const fk = blindCast<
819
+ SqlForeignKeyIR,
820
+ 'a not-expected foreign-key issue always carries the actual foreign-key node'
821
+ >(issue.actual);
822
+ const name = fk.name ?? `${tableName}_${fk.columns.join('_')}_fkey`;
823
+ return ok([new DropConstraintCall(schemaName, tableName, name, 'foreignKey')]);
824
+ }
825
+ return notOk(nodeConflict('foreignKeyConflict', issue.path.join('/')));
826
+ }
827
+
828
+ function mapUniqueNodeIssue(
829
+ issue: SchemaDiffIssue,
830
+ schemaName: string,
831
+ tableName: string,
832
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
833
+ if (issue.reason === 'not-found') {
834
+ const unique = blindCast<
835
+ SqlUniqueIR,
836
+ 'a not-found unique issue always carries the expected unique node'
837
+ >(issue.expected);
838
+ const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;
839
+ return ok([new AddUniqueCall(schemaName, tableName, name, [...unique.columns])]);
840
+ }
841
+ if (issue.reason === 'not-expected') {
842
+ const unique = blindCast<
843
+ SqlUniqueIR,
844
+ 'a not-expected unique issue always carries the actual unique node'
845
+ >(issue.actual);
846
+ const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;
847
+ return ok([new DropConstraintCall(schemaName, tableName, name, 'unique')]);
848
+ }
849
+ return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));
850
+ }
851
+
852
+ function mapIndexNodeIssue(
853
+ issue: SchemaDiffIssue,
854
+ schemaName: string,
855
+ tableName: string,
856
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
857
+ if (issue.reason === 'not-found') {
858
+ const index = blindCast<
859
+ SqlIndexIR,
860
+ 'a not-found index issue always carries the expected index node'
861
+ >(issue.expected);
862
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns);
863
+ const extras: { type?: string; options?: Record<string, unknown> } = {};
864
+ if (index.type !== undefined) extras.type = index.type;
865
+ if (index.options !== undefined) extras.options = index.options;
866
+ return ok([new CreateIndexCall(schemaName, tableName, indexName, [...index.columns], extras)]);
867
+ }
868
+ if (issue.reason === 'not-expected') {
869
+ const index = blindCast<
870
+ SqlIndexIR,
871
+ 'a not-expected index issue always carries the actual index node'
872
+ >(issue.actual);
873
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns);
874
+ return ok([new DropIndexCall(schemaName, tableName, indexName)]);
875
+ }
876
+ return notOk(nodeConflict('indexIncompatible', issue.path.join('/')));
877
+ }
878
+
879
+ function mapCheckNodeIssue(
880
+ issue: SchemaDiffIssue,
881
+ schemaName: string,
882
+ tableName: string,
883
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
884
+ // check_removed (extra live check not in contract) is the only check drift
885
+ // the default mapper handles directly; check_missing / check_mismatch are
886
+ // consumed by `checkConstraintPlanCallStrategy` (drop+recreate), so reaching
887
+ // here for them means the strategy did not run — a conflict.
888
+ if (issue.reason === 'not-expected') {
889
+ const check = blindCast<
890
+ { readonly name: string },
891
+ 'a not-expected check issue always carries the actual check node'
892
+ >(issue.actual);
893
+ return ok([new DropCheckConstraintCall(schemaName, tableName, check.name)]);
894
+ }
895
+ return notOk(
896
+ nodeConflict(
897
+ 'unsupportedOperation',
898
+ `Check constraint drift on "${tableName}" — handled by checkConstraintPlanCallStrategy: ${issue.path.join('/')}`,
899
+ ),
900
+ );
901
+ }
902
+
903
+ /**
904
+ * Maps one node-typed diff issue to its migration call(s), dispatching on the
905
+ * node's `nodeKind` + `issue.reason`, reading nodes and resolving column DDL
906
+ * from `codecRef` via `column-ddl-rendering.ts`.
907
+ */
908
+ export function mapNodeIssueToCall(
909
+ issue: SchemaDiffIssue,
910
+ ctx: StrategyContext,
911
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
912
+ const node = issueNode(issue);
913
+ if (node === undefined) {
914
+ return notOk(
915
+ nodeConflict(
916
+ 'unsupportedOperation',
917
+ `Issue carries neither an expected nor an actual node: ${issue.path.join('/')}`,
918
+ ),
919
+ );
920
+ }
921
+ if (node.nodeKind === PostgresSchemaNodeKind.namespace) {
922
+ if (issue.reason !== 'not-found') {
923
+ return notOk(
924
+ nodeConflict('unsupportedOperation', `Unexpected namespace drift: ${issue.path.join('/')}`),
925
+ );
926
+ }
927
+ const namespace = blindCast<
928
+ PostgresNamespaceSchemaNode,
929
+ 'a namespace-presence issue always carries a PostgresNamespaceSchemaNode'
930
+ >(issue.expected);
931
+ return ok([new CreateSchemaCall(namespace.schemaName)]);
932
+ }
933
+
934
+ if (node.nodeKind === PostgresSchemaNodeKind.nativeEnum) {
935
+ return mapNativeEnumNodeIssue(issue, ctx);
936
+ }
937
+
938
+ const ddlSchemaName = issueSchemaName(issue);
939
+ const tableName = issueTableName(issue);
940
+ if (ddlSchemaName === undefined || tableName === undefined) {
941
+ return notOk(
942
+ nodeConflict(
943
+ 'unsupportedOperation',
944
+ `Issue has no schema/table in its path: ${issue.path.join('/')}`,
945
+ ),
946
+ );
947
+ }
948
+ const schemaName = emissionSchemaName(ctx, ddlSchemaName);
949
+
950
+ switch (node.nodeKind) {
951
+ case PostgresSchemaNodeKind.table:
952
+ return mapTableNodeIssue(issue, schemaName, ddlSchemaName, ctx.codecHooks);
953
+ case RelationalSchemaNodeKind.column:
954
+ return mapColumnNodeIssue(issue, schemaName, tableName, ctx.codecHooks);
955
+ case RelationalSchemaNodeKind.columnDefault: {
956
+ const columnName = issueColumnName(issue);
957
+ if (columnName === undefined) {
958
+ return notOk(
959
+ nodeConflict(
960
+ 'unsupportedOperation',
961
+ `Default issue has no column in its path: ${issue.path.join('/')}`,
962
+ ),
963
+ );
964
+ }
965
+ return mapColumnDefaultNodeIssue(issue, schemaName, tableName, columnName);
966
+ }
967
+ case RelationalSchemaNodeKind.primaryKey:
968
+ return mapPrimaryKeyNodeIssue(issue, schemaName, tableName);
969
+ case RelationalSchemaNodeKind.foreignKey:
970
+ return mapForeignKeyNodeIssue(issue, schemaName, tableName);
971
+ case RelationalSchemaNodeKind.unique:
972
+ return mapUniqueNodeIssue(issue, schemaName, tableName);
973
+ case RelationalSchemaNodeKind.index:
974
+ return mapIndexNodeIssue(issue, schemaName, tableName);
975
+ case RelationalSchemaNodeKind.check:
976
+ return mapCheckNodeIssue(issue, schemaName, tableName);
977
+ default:
978
+ return notOk(nodeConflict('unsupportedOperation', `Unhandled node kind: ${node.nodeKind}`));
979
+ }
980
+ }
981
+
982
+ export interface IssuePlannerOptions {
983
+ readonly issues: readonly SchemaDiffIssue[];
984
+ readonly toContract: Contract<SqlStorage>;
985
+ readonly fromContract: Contract<SqlStorage> | null;
986
+ readonly schemaName: string;
987
+ readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;
988
+ readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;
989
+ /**
990
+ * Current database schema IR. Strategies read this to detect whether a
991
+ * structure already exists (e.g. `buildSchemaLookupMap` for shared-temp-
992
+ * default safety, extension dependency checks). Defaults to an empty schema
993
+ * when omitted so the planner can still run over "fresh DB" contract
994
+ * snapshots.
995
+ */
996
+ readonly schema?: SqlSchemaIR;
997
+ /**
998
+ * Operation-class policy. `planIssues` filters calls whose `operationClass`
999
+ * is not in `policy.allowedOperationClasses` and surfaces them as conflicts
1000
+ * instead of emitting disallowed DDL. Defaults to additive-only.
1001
+ */
1002
+ readonly policy?: MigrationOperationPolicy;
1003
+ /**
1004
+ * Framework components participating in this composition. Available to
1005
+ * future strategies that may consult component metadata at plan time.
1006
+ */
1007
+ readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
1008
+ readonly strategies?: readonly CallMigrationStrategy[];
1009
+ }
1010
+
1011
+ /**
1012
+ * Runs the ordered strategy list over the node-typed diff issues, maps
1013
+ * leftover issues via {@link mapNodeIssueToCall}, applies operation-class
1014
+ * policy gating, and buckets calls into the fixed DDL emission order (dep →
1015
+ * drop → table → column → recipe → alter → primaryKey → unique → index →
1016
+ * foreignKey).
1017
+ */
845
1018
  export function planIssues(
846
1019
  options: IssuePlannerOptions,
847
1020
  ): Result<IssuePlannerValue, readonly SqlPlannerConflict[]> {
848
- // When no policy is supplied, `planIssues` treats the call as trusted (the
849
- // caller — typically a test — has already vetted the issues). Only explicit
850
- // policies gate operation classes into conflicts.
851
- // `PostgresMigrationPlanner` always passes an explicit policy.
852
1021
  const policyProvided = options.policy !== undefined;
853
1022
  const policy = options.policy ?? DEFAULT_POLICY;
854
1023
  const schema = options.schema ?? emptySchemaIR();
@@ -884,10 +1053,10 @@ export function planIssues(
884
1053
  }
885
1054
 
886
1055
  const sorted = [...remaining].sort((a, b) => {
887
- const kindDelta = issueOrder(a) - issueOrder(b);
1056
+ const kindDelta = nodeIssueOrder(a) - nodeIssueOrder(b);
888
1057
  if (kindDelta !== 0) return kindDelta;
889
- const keyA = issueKey(a);
890
- const keyB = issueKey(b);
1058
+ const keyA = nodeIssueKey(a);
1059
+ const keyB = nodeIssueKey(b);
891
1060
  return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
892
1061
  });
893
1062
 
@@ -895,7 +1064,7 @@ export function planIssues(
895
1064
  const conflicts: SqlPlannerConflict[] = [];
896
1065
 
897
1066
  for (const issue of sorted) {
898
- const result = mapIssueToCall(issue, context);
1067
+ const result = mapNodeIssueToCall(issue, context);
899
1068
  if (result.ok) {
900
1069
  defaultCalls.push(...result.value);
901
1070
  } else {
@@ -903,11 +1072,6 @@ export function planIssues(
903
1072
  }
904
1073
  }
905
1074
 
906
- // Policy gating: drop calls whose operation class is not allowed and
907
- // surface a conflict describing the disallowed op. Applies to both strategy
908
- // output and default-mapped output. Only active when the caller explicitly
909
- // supplied a policy — direct unit-test invocations (which pass no policy)
910
- // stay as pass-through and keep destructive recipe steps intact.
911
1075
  const allowed = policy.allowedOperationClasses;
912
1076
  let gatedDefault = defaultCalls;
913
1077
  let gatedRecipe = recipeCalls;
@@ -935,13 +1099,6 @@ export function planIssues(
935
1099
  return notOk(conflicts);
936
1100
  }
937
1101
 
938
- // Recipe strategies (`notNullBackfillCallStrategy`,
939
- // `nullableTighteningCallStrategy`, etc.) emit a cohesive sequence that must
940
- // stay contiguous. They are inserted at a single pattern slot. Non-recipe
941
- // pattern strategies (`checkConstraintPlanCallStrategy`,
942
- // `storageTypePlanCallStrategy`, `notNullAddColumnCallStrategy`) produce
943
- // individually classifiable calls that slot into DDL buckets alongside
944
- // default-mapped calls.
945
1102
  const combinedBucketable = [...gatedDefault, ...gatedBucketable];
946
1103
  const byCategory = (cat: CallCategory) =>
947
1104
  combinedBucketable.filter((c) => classifyCall(c) === cat);
@@ -957,6 +1114,10 @@ export function planIssues(
957
1114
  ...byCategory('unique'),
958
1115
  ...byCategory('index'),
959
1116
  ...byCategory('foreignKey'),
1117
+ // Enablement changes run after all relational DDL (the table must exist)
1118
+ // and before the policy calls the planner appends after `planIssues` —
1119
+ // the same position the retired imperative enable-on-first-policy used.
1120
+ ...byCategory('rlsEnable'),
960
1121
  ];
961
1122
 
962
1123
  return ok({ calls });