@prisma-next/target-postgres 0.14.0-dev.5 → 0.14.0-dev.50

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 (238) hide show
  1. package/dist/authoring-DzHOdWTl.mjs +364 -0
  2. package/dist/authoring-DzHOdWTl.mjs.map +1 -0
  3. package/dist/canonicalize-Bn3BM1Cn.mjs +46 -0
  4. package/dist/canonicalize-Bn3BM1Cn.mjs.map +1 -0
  5. package/dist/canonicalize-CAbXtVtB.d.mts +37 -0
  6. package/dist/canonicalize-CAbXtVtB.d.mts.map +1 -0
  7. package/dist/{codec-ids-CnXu9Qy3.d.mts → codec-ids-BzrFF-I4.d.mts} +3 -2
  8. package/dist/codec-ids-BzrFF-I4.d.mts.map +1 -0
  9. package/dist/{codec-ids-BvytN2P8.mjs → codec-ids-C_-Hj6bL.mjs} +3 -2
  10. package/dist/codec-ids-C_-Hj6bL.mjs.map +1 -0
  11. package/dist/codec-ids.d.mts +2 -2
  12. package/dist/codec-ids.mjs +2 -2
  13. package/dist/{codec-types-DHCkwPKE.d.mts → codec-types-BDVmvKAW.d.mts} +3 -2
  14. package/dist/codec-types-BDVmvKAW.d.mts.map +1 -0
  15. package/dist/codec-types.d.mts +1 -1
  16. package/dist/{codecs--0A5_4Bq.d.mts → codecs-Dk2sxGLv.d.mts} +77 -4
  17. package/dist/codecs-Dk2sxGLv.d.mts.map +1 -0
  18. package/dist/codecs.d.mts +1 -1
  19. package/dist/codecs.mjs +117 -2
  20. package/dist/codecs.mjs.map +1 -1
  21. package/dist/contract-free.d.mts +8 -3
  22. package/dist/contract-free.d.mts.map +1 -1
  23. package/dist/contract-free.mjs +4 -4
  24. package/dist/control-policy-DUFgy9jO.mjs +1103 -0
  25. package/dist/control-policy-DUFgy9jO.mjs.map +1 -0
  26. package/dist/control.d.mts +2 -2
  27. package/dist/control.d.mts.map +1 -1
  28. package/dist/control.mjs +757 -35
  29. package/dist/control.mjs.map +1 -1
  30. package/dist/data-transform-BOWpliq8.mjs.map +1 -1
  31. package/dist/{data-transform-DDgWdB5o.d.mts → data-transform-DPzwBMhW.d.mts} +3 -3
  32. package/dist/{data-transform-DDgWdB5o.d.mts.map → data-transform-DPzwBMhW.d.mts.map} +1 -1
  33. package/dist/data-transform.d.mts +1 -1
  34. package/dist/{ddl-QDyOSeLc.mjs → ddl-ujxH2A7r.mjs} +63 -6
  35. package/dist/ddl-ujxH2A7r.mjs.map +1 -0
  36. package/dist/ddl.d.mts +3 -2
  37. package/dist/ddl.mjs +2 -2
  38. package/dist/default-normalizer.d.mts +1 -1
  39. package/dist/default-normalizer.d.mts.map +1 -1
  40. package/dist/default-normalizer.mjs +247 -1
  41. package/dist/default-normalizer.mjs.map +1 -0
  42. package/dist/descriptor-meta-CuGDsrG4.mjs +19 -0
  43. package/dist/descriptor-meta-CuGDsrG4.mjs.map +1 -0
  44. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs +12 -0
  45. package/dist/descriptor-meta-runtime-UwYdV8fD.mjs.map +1 -0
  46. package/dist/diff-database-schema-BmSmWcaY.mjs +313 -0
  47. package/dist/diff-database-schema-BmSmWcaY.mjs.map +1 -0
  48. package/dist/diff-database-schema.d.mts +46 -0
  49. package/dist/diff-database-schema.d.mts.map +1 -0
  50. package/dist/diff-database-schema.mjs +2 -0
  51. package/dist/issue-planner.d.mts +35 -11
  52. package/dist/issue-planner.d.mts.map +1 -1
  53. package/dist/issue-planner.mjs +2 -2
  54. package/dist/migration.d.mts +5 -5
  55. package/dist/migration.d.mts.map +1 -1
  56. package/dist/migration.mjs +4 -4
  57. package/dist/namespace-ids-xtp_ZY86.mjs +7 -0
  58. package/dist/namespace-ids-xtp_ZY86.mjs.map +1 -0
  59. package/dist/native-type-normalizer.mjs +37 -1
  60. package/dist/native-type-normalizer.mjs.map +1 -0
  61. package/dist/nodes-CSkPX3rI.d.mts +120 -0
  62. package/dist/nodes-CSkPX3rI.d.mts.map +1 -0
  63. package/dist/{nodes-Bbhs2rwj.mjs → nodes-Dh__NS58.mjs} +56 -2
  64. package/dist/nodes-Dh__NS58.mjs.map +1 -0
  65. package/dist/{op-factory-call-D_p5vxwt.mjs → op-factory-call-BKRnMgrB.mjs} +205 -31
  66. package/dist/op-factory-call-BKRnMgrB.mjs.map +1 -0
  67. package/dist/{op-factory-call-DmQEc3XV.d.mts → op-factory-call-Dt-Jx5JS.d.mts} +46 -15
  68. package/dist/op-factory-call-Dt-Jx5JS.d.mts.map +1 -0
  69. package/dist/op-factory-call.d.mts +2 -2
  70. package/dist/op-factory-call.mjs +2 -2
  71. package/dist/pack.d.mts +115 -3
  72. package/dist/pack.d.mts.map +1 -1
  73. package/dist/pack.mjs +1 -1
  74. package/dist/planner-BMBRPzsv.mjs +367 -0
  75. package/dist/planner-BMBRPzsv.mjs.map +1 -0
  76. package/dist/{planner-ddl-builders-B2wOwLqI.mjs → planner-ddl-builders-B8Nn6nHN.mjs} +12 -27
  77. package/dist/planner-ddl-builders-B8Nn6nHN.mjs.map +1 -0
  78. package/dist/planner-ddl-builders.d.mts +4 -6
  79. package/dist/planner-ddl-builders.d.mts.map +1 -1
  80. package/dist/planner-ddl-builders.mjs +2 -2
  81. package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -1
  82. package/dist/planner-identity-values.d.mts +8 -2
  83. package/dist/planner-identity-values.d.mts.map +1 -1
  84. package/dist/planner-identity-values.mjs +2 -2
  85. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts → planner-produced-postgres-migration-C0a7I1-e.d.mts} +4 -4
  86. package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts.map → planner-produced-postgres-migration-C0a7I1-e.d.mts.map} +1 -1
  87. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs → planner-produced-postgres-migration-Dp6IO_gj.mjs} +3 -3
  88. package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-Dp6IO_gj.mjs.map} +1 -1
  89. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  90. package/dist/planner-produced-postgres-migration.mjs +1 -1
  91. package/dist/{planner-sql-checks-jqUUGyQR.mjs → planner-sql-checks-Cze3vMfe.mjs} +2 -2
  92. package/dist/{planner-sql-checks-jqUUGyQR.mjs.map → planner-sql-checks-Cze3vMfe.mjs.map} +1 -1
  93. package/dist/planner-sql-checks.d.mts +2 -2
  94. package/dist/planner-sql-checks.d.mts.map +1 -1
  95. package/dist/planner-sql-checks.mjs +1 -1
  96. package/dist/{planner-target-details-CIY6tLeo.d.mts → planner-target-details-HkP4RrRO.d.mts} +2 -2
  97. package/dist/planner-target-details-HkP4RrRO.d.mts.map +1 -0
  98. package/dist/planner-target-details.d.mts +1 -1
  99. package/dist/planner.d.mts +55 -17
  100. package/dist/planner.d.mts.map +1 -1
  101. package/dist/planner.mjs +3 -2
  102. package/dist/{postgres-contract-serializer-k3TAcPMY.mjs → postgres-contract-view-3xfUgjnC.mjs} +44 -41
  103. package/dist/postgres-contract-view-3xfUgjnC.mjs.map +1 -0
  104. package/dist/postgres-contract-view-C9j5cqP0.d.mts +34 -0
  105. package/dist/postgres-contract-view-C9j5cqP0.d.mts.map +1 -0
  106. package/dist/postgres-database-schema-node-C9bTuMrd.d.mts +190 -0
  107. package/dist/postgres-database-schema-node-C9bTuMrd.d.mts.map +1 -0
  108. package/dist/{postgres-migration-B5jKrXv3.mjs → postgres-migration-D0jwzYDT.mjs} +21 -2
  109. package/dist/postgres-migration-D0jwzYDT.mjs.map +1 -0
  110. package/dist/{postgres-migration-Y4YBJqkS.d.mts → postgres-migration-DFaxuRyI.d.mts} +20 -7
  111. package/dist/postgres-migration-DFaxuRyI.d.mts.map +1 -0
  112. package/dist/postgres-native-enum-xdiqmBf_.mjs +41 -0
  113. package/dist/postgres-native-enum-xdiqmBf_.mjs.map +1 -0
  114. package/dist/postgres-rls-policy--CSddvMR.d.mts +52 -0
  115. package/dist/postgres-rls-policy--CSddvMR.d.mts.map +1 -0
  116. package/dist/{postgres-schema-COGZ1ark.mjs → postgres-schema-CajYAwny.mjs} +135 -7
  117. package/dist/postgres-schema-CajYAwny.mjs.map +1 -0
  118. package/dist/postgres-schema-DqnhQRvR.d.mts +226 -0
  119. package/dist/postgres-schema-DqnhQRvR.d.mts.map +1 -0
  120. package/dist/postgres-table-schema-node-BgaSrxYN.mjs +249 -0
  121. package/dist/postgres-table-schema-node-BgaSrxYN.mjs.map +1 -0
  122. package/dist/render-ops.d.mts +1 -1
  123. package/dist/{render-typescript-KMgosran.mjs → render-typescript-7yqILcwr.mjs} +45 -16
  124. package/dist/render-typescript-7yqILcwr.mjs.map +1 -0
  125. package/dist/render-typescript.mjs +1 -1
  126. package/dist/resolve-ddl-schema-Bv1ZvjX8.mjs +22 -0
  127. package/dist/resolve-ddl-schema-Bv1ZvjX8.mjs.map +1 -0
  128. package/dist/rls-canonicalize.d.mts +2 -0
  129. package/dist/rls-canonicalize.mjs +2 -0
  130. package/dist/runtime.d.mts +6 -8
  131. package/dist/runtime.d.mts.map +1 -1
  132. package/dist/runtime.mjs +3 -3
  133. package/dist/runtime.mjs.map +1 -1
  134. package/dist/schema-ir-annotations.d.mts +15 -0
  135. package/dist/schema-ir-annotations.d.mts.map +1 -0
  136. package/dist/schema-ir-annotations.mjs +2 -0
  137. package/dist/schema-node-kinds-ClScchhi.mjs +76 -0
  138. package/dist/schema-node-kinds-ClScchhi.mjs.map +1 -0
  139. package/dist/types.d.mts +4 -140
  140. package/dist/types.mjs +3 -2
  141. package/package.json +23 -17
  142. package/src/contract-free/checks.ts +73 -0
  143. package/src/contract-free/ddl.ts +45 -1
  144. package/src/core/authoring.ts +287 -2
  145. package/src/core/codec-ids.ts +1 -0
  146. package/src/core/codec-type-map.ts +2 -0
  147. package/src/core/codecs.ts +141 -1
  148. package/src/core/ddl/nodes.ts +94 -2
  149. package/src/core/default-normalizer.ts +122 -2
  150. package/src/core/descriptor-meta.ts +6 -1
  151. package/src/core/entity-kinds.ts +30 -0
  152. package/src/core/migrations/bound-schema.ts +10 -0
  153. package/src/core/migrations/column-ddl-rendering.ts +117 -0
  154. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +149 -0
  155. package/src/core/migrations/control-policy.ts +70 -47
  156. package/src/core/migrations/diff-database-schema.ts +280 -0
  157. package/src/core/migrations/issue-planner.ts +647 -652
  158. package/src/core/migrations/op-factory-call.ts +109 -21
  159. package/src/core/migrations/operations/columns.ts +24 -12
  160. package/src/core/migrations/operations/constraints.ts +1 -1
  161. package/src/core/migrations/operations/data-transform.ts +6 -0
  162. package/src/core/migrations/operations/dependencies.ts +2 -1
  163. package/src/core/migrations/operations/rls.ts +106 -0
  164. package/src/core/migrations/operations/shared.ts +0 -30
  165. package/src/core/migrations/planner-ddl-builders.ts +20 -58
  166. package/src/core/migrations/planner-identity-values.ts +1 -1
  167. package/src/core/migrations/planner-recipes.ts +31 -13
  168. package/src/core/migrations/planner-sql-checks.ts +1 -1
  169. package/src/core/migrations/planner-strategies.ts +248 -216
  170. package/src/core/migrations/planner-target-details.ts +3 -1
  171. package/src/core/migrations/planner.ts +297 -59
  172. package/src/core/migrations/postgres-migration.ts +34 -4
  173. package/src/core/migrations/render-typescript.ts +42 -15
  174. package/src/core/migrations/resolve-ddl-schema.ts +26 -0
  175. package/src/core/migrations/runner.ts +10 -16
  176. package/src/core/migrations/verify-postgres-namespaces.ts +47 -30
  177. package/src/core/namespace-ids.ts +3 -0
  178. package/src/core/postgres-contract-serializer.ts +41 -71
  179. package/src/core/postgres-contract-view.ts +48 -0
  180. package/src/core/postgres-native-enum.ts +51 -0
  181. package/src/core/postgres-rls-policy.ts +64 -0
  182. package/src/core/postgres-role.ts +37 -0
  183. package/src/core/postgres-schema-verifier.ts +10 -7
  184. package/src/core/postgres-schema.ts +62 -14
  185. package/src/core/postgres-validators.ts +27 -0
  186. package/src/core/psl-infer/infer-psl-contract.ts +1068 -0
  187. package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
  188. package/src/core/psl-infer/postgres-type-map.ts +157 -0
  189. package/src/core/rls/canonicalize.ts +48 -0
  190. package/src/core/schema-ir/postgres-database-schema-node.ts +60 -0
  191. package/src/core/schema-ir/postgres-namespace-schema-node.ts +60 -0
  192. package/src/core/schema-ir/postgres-policy-schema-node.ts +90 -0
  193. package/src/core/schema-ir/postgres-role-schema-node.ts +63 -0
  194. package/src/core/schema-ir/postgres-table-schema-node.ts +118 -0
  195. package/src/core/schema-ir/schema-node-kinds.ts +106 -0
  196. package/src/exports/contract-free.ts +7 -1
  197. package/src/exports/control.ts +27 -33
  198. package/src/exports/ddl.ts +4 -0
  199. package/src/exports/diff-database-schema.ts +7 -0
  200. package/src/exports/issue-planner.ts +1 -1
  201. package/src/exports/migration.ts +1 -0
  202. package/src/exports/op-factory-call.ts +1 -0
  203. package/src/exports/planner-ddl-builders.ts +0 -2
  204. package/src/exports/planner-identity-values.ts +4 -1
  205. package/src/exports/planner.ts +1 -0
  206. package/src/exports/rls-canonicalize.ts +6 -0
  207. package/src/exports/runtime.ts +1 -0
  208. package/src/exports/schema-ir-annotations.ts +1 -0
  209. package/src/exports/types.ts +28 -0
  210. package/dist/codec-ids-BvytN2P8.mjs.map +0 -1
  211. package/dist/codec-ids-CnXu9Qy3.d.mts.map +0 -1
  212. package/dist/codec-types-DHCkwPKE.d.mts.map +0 -1
  213. package/dist/codecs--0A5_4Bq.d.mts.map +0 -1
  214. package/dist/ddl-QDyOSeLc.mjs.map +0 -1
  215. package/dist/default-normalizer-DyyCHQWs.mjs +0 -131
  216. package/dist/default-normalizer-DyyCHQWs.mjs.map +0 -1
  217. package/dist/descriptor-meta-CpGygXpI.mjs +0 -140
  218. package/dist/descriptor-meta-CpGygXpI.mjs.map +0 -1
  219. package/dist/issue-planner-DL6g3CmE.mjs +0 -824
  220. package/dist/issue-planner-DL6g3CmE.mjs.map +0 -1
  221. package/dist/native-type-normalizer-Bc9XJzWC.mjs +0 -38
  222. package/dist/native-type-normalizer-Bc9XJzWC.mjs.map +0 -1
  223. package/dist/nodes-Bbhs2rwj.mjs.map +0 -1
  224. package/dist/nodes-pLeLgdis.d.mts +0 -67
  225. package/dist/nodes-pLeLgdis.d.mts.map +0 -1
  226. package/dist/op-factory-call-D_p5vxwt.mjs.map +0 -1
  227. package/dist/op-factory-call-DmQEc3XV.d.mts.map +0 -1
  228. package/dist/planner-Bs_baQax.mjs +0 -324
  229. package/dist/planner-Bs_baQax.mjs.map +0 -1
  230. package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +0 -1
  231. package/dist/planner-target-details-CIY6tLeo.d.mts.map +0 -1
  232. package/dist/postgres-contract-serializer-k3TAcPMY.mjs.map +0 -1
  233. package/dist/postgres-migration-B5jKrXv3.mjs.map +0 -1
  234. package/dist/postgres-migration-Y4YBJqkS.d.mts.map +0 -1
  235. package/dist/postgres-schema-COGZ1ark.mjs.map +0 -1
  236. package/dist/render-typescript-KMgosran.mjs.map +0 -1
  237. package/dist/types.d.mts.map +0 -1
  238. package/src/core/postgres-enum-type-schema.ts +0 -17
@@ -1,36 +1,59 @@
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 { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';
49
+ import { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';
50
+ import { quoteIdentifier } from '../sql-utils';
51
+ import {
52
+ renderColumnAlterType,
53
+ renderColumnDdl,
54
+ renderColumnDefaultSql,
55
+ } from './column-ddl-rendering';
56
+ import { resolveNamespaceIdForDdlSchema } from './control-policy';
34
57
  import {
35
58
  AddColumnCall,
36
59
  AddForeignKeyCall,
@@ -48,75 +71,36 @@ import {
48
71
  DropNotNullCall,
49
72
  DropTableCall,
50
73
  type PostgresOpFactoryCall,
51
- postgresDefaultToDdlColumnDefault,
52
74
  SetDefaultCall,
53
75
  SetNotNullCall,
54
76
  } from './op-factory-call';
55
77
  import type { ForeignKeySpec } from './operations/shared';
56
- import { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';
57
- import { buildExpectedFormatType } from './planner-sql-checks';
58
78
  import {
59
79
  type CallMigrationStrategy,
60
80
  postgresPlannerStrategies,
61
- resolveDdlSchemaForNamespace,
62
- resolveNamespaceIdForIssue,
63
81
  type StrategyContext,
64
- tableAt,
65
82
  } from './planner-strategies';
66
- import { resolveColumnTypeMetadata } from './planner-type-resolution';
67
83
 
68
84
  export type { CallMigrationStrategy, StrategyContext };
69
85
 
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
- };
86
+ /**
87
+ * Deterministic name for the element-non-null CHECK constraint on a scalar-array
88
+ * column. Distinct `_elem_not_null` suffix avoids collision with the enum
89
+ * value-set `_check` constraints. Re-emitting the same schema produces the same
90
+ * name, so `pg_get_constraintdef`-based verify sees no drift.
91
+ */
92
+ function elementNonNullCheckName(tableName: string, columnName: string): string {
93
+ return `${tableName}_${columnName}_elem_not_null`;
94
+ }
117
95
 
118
- function issueOrder(issue: SchemaIssue): number {
119
- return ISSUE_KIND_ORDER[issue.kind] ?? 99;
96
+ /**
97
+ * Predicate enforcing that a scalar-array column carries no NULL element. The
98
+ * array column itself may be NULL (container nullability is the column's NOT NULL
99
+ * clause); `array_position` over a NULL array yields NULL, which a CHECK treats
100
+ * as satisfied, so a nullable array column is unaffected.
101
+ */
102
+ function elementNonNullCheckExpression(columnName: string): string {
103
+ return `array_position(${quoteIdentifier(columnName)}, NULL) IS NULL`;
120
104
  }
121
105
 
122
106
  // ============================================================================
@@ -136,558 +120,10 @@ function issueConflict(
136
120
  };
137
121
  }
138
122
 
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
123
  export interface IssuePlannerValue {
178
124
  readonly calls: readonly PostgresOpFactoryCall[];
179
125
  }
180
126
 
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
127
  /**
692
128
  * Classifies calls into dependency order categories for correct DDL sequencing.
693
129
  */
@@ -695,6 +131,8 @@ type CallCategory =
695
131
  | 'dep'
696
132
  | 'drop'
697
133
  | 'table'
134
+ | 'rlsEnable'
135
+ | 'rlsPolicy'
698
136
  | 'column'
699
137
  | 'alter'
700
138
  | 'primaryKey'
@@ -724,6 +162,12 @@ function classifyCall(call: PostgresOpFactoryCall): CallCategory {
724
162
  return 'unique'; // after uniques, before indexes
725
163
  case 'createTable':
726
164
  return 'table';
165
+ case 'enableRowLevelSecurity':
166
+ return 'rlsEnable';
167
+ case 'createRlsPolicy':
168
+ return 'rlsPolicy';
169
+ case 'dropRlsPolicy':
170
+ return 'drop';
727
171
  case 'addColumn':
728
172
  return 'column';
729
173
  case 'alterColumnType':
@@ -760,17 +204,6 @@ function classifyCall(call: PostgresOpFactoryCall): CallCategory {
760
204
  }
761
205
  }
762
206
 
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
207
  // When no policy is explicitly supplied (test-only path; production callers
775
208
  // always pass one), allow every class so strategies that gate on
776
209
  // `'data'` (data-safe placeholders) still fire — the test is treated as
@@ -781,7 +214,7 @@ const DEFAULT_POLICY: MigrationOperationPolicy = {
781
214
  };
782
215
 
783
216
  function emptySchemaIR(): SqlSchemaIR {
784
- return { tables: {} };
217
+ return new SqlSchemaIR({ tables: {} });
785
218
  }
786
219
 
787
220
  function conflictKindForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['kind'] {
@@ -842,13 +275,587 @@ function conflictForDisallowedCall(
842
275
  };
843
276
  }
844
277
 
278
+ // ============================================================================
279
+ // Node-based issue planner
280
+ // ============================================================================
281
+ //
282
+ // Consumes node-typed `SchemaDiffIssue`s (from the one differ —
283
+ // `buildPostgresPlanDiff`) and reads the diff node each issue carries
284
+ // (`issue.expected` / `issue.actual`). Column DDL (type/default SQL) resolves
285
+ // from the column node's `codecRef` against the codec hooks the caller holds
286
+ // (`column-ddl-rendering.ts`), never the contract. The retained subsystems —
287
+ // codec type-operations, field-lifecycle hooks, the NOT-NULL temp-default
288
+ // deferred DDL, control-policy disposition — keep the contract via the
289
+ // strategy context, per the slice's scope.
290
+
291
+ /** The diff node an issue concerns — expected when present, else the actual (extra) node. */
292
+ export function issueNode(issue: SchemaDiffIssue): SqlSchemaIRNode | undefined {
293
+ const node = issue.expected ?? issue.actual;
294
+ if (node === undefined) return undefined;
295
+ return blindCast<
296
+ SqlSchemaIRNode,
297
+ 'every node in a Postgres schema diff tree is a SqlSchemaIRNode; nodeKind is its required discriminant'
298
+ >(node);
299
+ }
300
+
301
+ /** DDL schema segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */
302
+ export function issueSchemaName(issue: SchemaDiffIssue): string | undefined {
303
+ return issue.path[1];
304
+ }
305
+
306
+ /** Table segment of a table-or-descendant issue path: `[database, ddlSchema, table, …]`. */
307
+ export function issueTableName(issue: SchemaDiffIssue): string | undefined {
308
+ return issue.path[2];
309
+ }
310
+
311
+ /** Column name embedded in a column/default issue path segment (`column:<name>`). */
312
+ export function issueColumnName(issue: SchemaDiffIssue): string | undefined {
313
+ const segment = issue.path[3];
314
+ if (segment === undefined || !segment.startsWith('column:')) return undefined;
315
+ return segment.slice('column:'.length);
316
+ }
317
+
318
+ /**
319
+ * The DDL schema name to use when EMITTING an op against `ddlSchemaName` (the
320
+ * diff tree's resolved physical schema, `issueSchemaName(issue)`). The
321
+ * unbound namespace's diff-tree identity resolves to `public` (a concrete
322
+ * physical default the differ needs in order to compare its tree against
323
+ * introspection — `resolveDdlSchemaForNamespaceStorage`), but DDL EMISSION
324
+ * must stay unqualified so the live connection's `search_path` resolves it
325
+ * at runtime (`boundSchema`). Recovers the logical namespace id via the
326
+ * contract and substitutes the unbound sentinel back in when it resolves
327
+ * there; every other namespace's `ddlSchemaName` already agrees between the
328
+ * two resolution paths, so it passes through unchanged.
329
+ */
330
+ export function emissionSchemaName(ctx: StrategyContext, ddlSchemaName: string): string {
331
+ const namespaceId = resolveNamespaceIdForDdlSchema(ctx.toContract, ddlSchemaName);
332
+ return namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_NAMESPACE_ID : ddlSchemaName;
333
+ }
334
+
335
+ /**
336
+ * Whether a column node is a scalar-array (`many: true`) column. The family
337
+ * converter (`contractToSchemaIR`'s `convertColumn`) never stamps `many` on
338
+ * the derived node — array-ness is folded into the `[]` suffix on
339
+ * `nativeType` instead — so the node-derived check reads the suffix; `.many`
340
+ * is still checked first for nodes a caller stamps directly (e.g. hand-built
341
+ * test fixtures, or an adapter that populates it at introspection).
342
+ */
343
+ function isManyColumn(column: SqlColumnIR): boolean {
344
+ return column.many === true || column.nativeType.endsWith('[]');
345
+ }
346
+
347
+ /** Whether the expected/actual native type (resolved, or raw+many fallback) differs — mirrors `SqlColumnIR.isEqualTo`'s type comparison. */
348
+ export function columnTypeChanged(expected: SqlColumnIR, actual: SqlColumnIR): boolean {
349
+ if (expected.resolvedNativeType !== undefined && actual.resolvedNativeType !== undefined) {
350
+ return expected.resolvedNativeType !== actual.resolvedNativeType;
351
+ }
352
+ return (
353
+ expected.nativeType !== actual.nativeType || Boolean(expected.many) !== Boolean(actual.many)
354
+ );
355
+ }
356
+
357
+ // ----------------------------------------------------------------------------
358
+ // Node-keyed issue ordering (re-keys ISSUE_KIND_ORDER on nodeKind + reason)
359
+ // ----------------------------------------------------------------------------
360
+
361
+ /**
362
+ * Re-keys the legacy `ISSUE_KIND_ORDER` on `(nodeKind, reason)`, numbers
363
+ * preserved so the dependency intent stays legible. Final emission order is
364
+ * fixed downstream by `classifyCall` bucketing (dep → drop → table → column →
365
+ * recipe → alter → primaryKey → unique → index → foreignKey), so this only
366
+ * breaks ties within a bucket.
367
+ */
368
+ export function nodeIssueOrder(issue: SchemaDiffIssue): number {
369
+ const node = issueNode(issue);
370
+ if (node === undefined) return 99;
371
+ switch (node.nodeKind) {
372
+ case PostgresSchemaNodeKind.namespace:
373
+ return 1;
374
+ case RelationalSchemaNodeKind.foreignKey:
375
+ return issue.reason === 'not-expected' ? 10 : 60;
376
+ case RelationalSchemaNodeKind.unique:
377
+ return issue.reason === 'not-expected' ? 11 : 51;
378
+ case RelationalSchemaNodeKind.primaryKey:
379
+ return issue.reason === 'not-expected' ? 12 : 50;
380
+ case RelationalSchemaNodeKind.index:
381
+ return issue.reason === 'not-expected' ? 13 : 52;
382
+ case RelationalSchemaNodeKind.columnDefault:
383
+ if (issue.reason === 'not-expected') return 14;
384
+ return issue.reason === 'not-found' ? 42 : 43;
385
+ case RelationalSchemaNodeKind.column:
386
+ if (issue.reason === 'not-expected') return 15;
387
+ return issue.reason === 'not-found' ? 30 : 40;
388
+ case PostgresSchemaNodeKind.table:
389
+ return issue.reason === 'not-expected' ? 16 : 20;
390
+ case RelationalSchemaNodeKind.check:
391
+ if (issue.reason === 'not-found') return 53;
392
+ return issue.reason === 'not-expected' ? 55 : 54;
393
+ default:
394
+ return 99;
395
+ }
396
+ }
397
+
398
+ /** Deterministic tiebreak within an order bucket: the diff path already encodes schema → table → child. */
399
+ export function nodeIssueKey(issue: SchemaDiffIssue): string {
400
+ return issue.path.join(' ');
401
+ }
402
+
403
+ // ----------------------------------------------------------------------------
404
+ // Subtree coalescing (the planner's responsibility per the differ's contract)
405
+ // ----------------------------------------------------------------------------
406
+
407
+ /**
408
+ * The generic differ is total: a missing/extra table (or column) emits an
409
+ * issue for itself AND for every node in its subtree. `CreateTable`/`DropTable`
410
+ * and `AddColumn`/`DropColumn` already account for the whole subtree, so the
411
+ * nested issues are redundant — coalescing drops any issue whose path is a
412
+ * strict descendant of a `not-found`/`not-expected` issue's path. Run over the
413
+ * relational subset ONLY (policy issues and synthesized namespace issues are
414
+ * handled on their own paths, never coalesced against tables).
415
+ */
416
+ export function coalesceSubtreeIssues<TNode extends DiffableNode = DiffableNode>(
417
+ issues: readonly SchemaDiffIssue<TNode>[],
418
+ ): readonly SchemaDiffIssue<TNode>[] {
419
+ const collapsingPaths = issues
420
+ .filter((issue) => issue.reason === 'not-found' || issue.reason === 'not-expected')
421
+ .map((issue) => issue.path);
422
+ if (collapsingPaths.length === 0) return issues;
423
+ return issues.filter(
424
+ (issue) => !collapsingPaths.some((ancestor) => isStrictDescendantPath(issue.path, ancestor)),
425
+ );
426
+ }
427
+
428
+ function isStrictDescendantPath(path: readonly string[], ancestor: readonly string[]): boolean {
429
+ if (path.length <= ancestor.length) return false;
430
+ for (let i = 0; i < ancestor.length; i += 1) {
431
+ if (path[i] !== ancestor[i]) return false;
432
+ }
433
+ return true;
434
+ }
435
+
436
+ // ----------------------------------------------------------------------------
437
+ // Node → call construction
438
+ // ----------------------------------------------------------------------------
439
+
440
+ function fkSpecFromNode(fk: SqlForeignKeyIR, tableName: string): ForeignKeySpec {
441
+ const name = fk.name ?? `${tableName}_${fk.columns.join('_')}_fkey`;
442
+ return {
443
+ name,
444
+ columns: [...fk.columns],
445
+ references: {
446
+ // The raw target namespace coordinate, matching the retired coordinate
447
+ // path's `references.schema: fk.target.namespaceId` (the FK node stamps
448
+ // it verbatim). The op renderer qualifies the REFERENCES clause from it.
449
+ schema: fk.referencedSchema ?? '',
450
+ table: fk.referencedTable,
451
+ columns: [...fk.referencedColumns],
452
+ },
453
+ ...ifDefined('onDelete', fk.onDelete),
454
+ ...ifDefined('onUpdate', fk.onUpdate),
455
+ };
456
+ }
457
+
458
+ /**
459
+ * Builds the `CreateTable` + child `CreateIndex` / `AddForeignKey` / `AddUnique`
460
+ * calls for a newly-expected table, reading only the table node's children. The
461
+ * PK and element-non-null CHECKs go inline as table constraints; indexes
462
+ * (declared + FK-backing, already merged and ordered at derivation) and the
463
+ * FK / unique constraints are separate calls (re-bucketed downstream). Every
464
+ * column's DDL is resolved from its `codecRef` via `renderColumnDdl`.
465
+ */
466
+ function buildCreateTableCallsFromNode(
467
+ schemaName: string,
468
+ table: PostgresTableSchemaNode,
469
+ codecHooks: ReadonlyMap<string, CodecControlHooks>,
470
+ ): PostgresOpFactoryCall[] {
471
+ const ddlColumns = Object.values(table.columns).map((c) =>
472
+ renderColumnDdl(c.name, c, codecHooks),
473
+ );
474
+ const primaryKeyConstraints: DdlTableConstraint[] = table.primaryKey
475
+ ? [
476
+ contractFree.primaryKey([...table.primaryKey.columns], {
477
+ ...ifDefined('name', table.primaryKey.name),
478
+ }),
479
+ ]
480
+ : [];
481
+ const elementNonNullChecks: DdlTableConstraint[] = Object.values(table.columns)
482
+ .filter((c) => isManyColumn(c))
483
+ .map((c) =>
484
+ contractFree.checkExpression(
485
+ elementNonNullCheckName(table.name, c.name),
486
+ elementNonNullCheckExpression(c.name),
487
+ ),
488
+ );
489
+ const allTableConstraints = [...primaryKeyConstraints, ...elementNonNullChecks];
490
+ const calls: PostgresOpFactoryCall[] = [
491
+ new CreateTableCall(
492
+ schemaName,
493
+ table.name,
494
+ ddlColumns,
495
+ allTableConstraints.length > 0 ? allTableConstraints : undefined,
496
+ ),
497
+ ];
498
+ for (const index of table.indexes) {
499
+ const indexName = index.name ?? defaultIndexName(table.name, index.columns);
500
+ const extras: { type?: string; options?: Record<string, unknown> } = {};
501
+ if (index.type !== undefined) extras.type = index.type;
502
+ if (index.options !== undefined) extras.options = index.options;
503
+ calls.push(new CreateIndexCall(schemaName, table.name, indexName, [...index.columns], extras));
504
+ }
505
+ for (const fk of table.foreignKeys) {
506
+ calls.push(new AddForeignKeyCall(schemaName, table.name, fkSpecFromNode(fk, table.name)));
507
+ }
508
+ for (const unique of table.uniques) {
509
+ const constraintName = unique.name ?? `${table.name}_${unique.columns.join('_')}_key`;
510
+ calls.push(new AddUniqueCall(schemaName, table.name, constraintName, [...unique.columns]));
511
+ }
512
+ return calls;
513
+ }
514
+
515
+ function nodeConflict(kind: SqlPlannerConflict['kind'], message: string): SqlPlannerConflict {
516
+ return issueConflict(kind, message);
517
+ }
518
+
519
+ function mapTableNodeIssue(
520
+ issue: SchemaDiffIssue,
521
+ schemaName: string,
522
+ codecHooks: ReadonlyMap<string, CodecControlHooks>,
523
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
524
+ if (issue.reason === 'not-found') {
525
+ const table = blindCast<
526
+ PostgresTableSchemaNode,
527
+ 'a not-found table issue always carries the expected PostgresTableSchemaNode'
528
+ >(issue.expected);
529
+ return ok(buildCreateTableCallsFromNode(schemaName, table, codecHooks));
530
+ }
531
+ if (issue.reason === 'not-expected') {
532
+ const table = blindCast<
533
+ PostgresTableSchemaNode,
534
+ 'a not-expected table issue always carries the actual PostgresTableSchemaNode'
535
+ >(issue.actual);
536
+ return ok([new DropTableCall(schemaName, table.name)]);
537
+ }
538
+ // Unreachable: PostgresTableSchemaNode.isEqualTo is identity.
539
+ return notOk(nodeConflict('unsupportedOperation', `Unexpected table drift: ${issue.message}`));
540
+ }
541
+
542
+ function mapColumnNodeIssue(
543
+ issue: SchemaDiffIssue,
544
+ schemaName: string,
545
+ tableName: string,
546
+ codecHooks: ReadonlyMap<string, CodecControlHooks>,
547
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
548
+ if (issue.reason === 'not-found') {
549
+ const column = blindCast<
550
+ SqlColumnIR,
551
+ 'a not-found column issue always carries the expected column node'
552
+ >(issue.expected);
553
+ return ok([
554
+ new AddColumnCall(schemaName, tableName, renderColumnDdl(column.name, column, codecHooks)),
555
+ ]);
556
+ }
557
+ if (issue.reason === 'not-expected') {
558
+ const column = blindCast<
559
+ SqlColumnIR,
560
+ 'a not-expected column issue always carries the actual column node'
561
+ >(issue.actual);
562
+ return ok([new DropColumnCall(schemaName, tableName, column.name)]);
563
+ }
564
+ // not-equal: Postgres alters in place — type drift and/or nullability drift.
565
+ const expected = blindCast<
566
+ SqlColumnIR,
567
+ 'a not-equal column issue always carries the expected column node'
568
+ >(issue.expected);
569
+ const actual = blindCast<
570
+ SqlColumnIR,
571
+ 'a not-equal column issue always carries the actual column node'
572
+ >(issue.actual);
573
+ const calls: PostgresOpFactoryCall[] = [];
574
+ if (columnTypeChanged(expected, actual)) {
575
+ const { qualifiedTargetType, formatTypeExpected } = renderColumnAlterType(expected, codecHooks);
576
+ calls.push(
577
+ new AlterColumnTypeCall(schemaName, tableName, expected.name, {
578
+ qualifiedTargetType,
579
+ formatTypeExpected,
580
+ rawTargetTypeForLabel: qualifiedTargetType,
581
+ }),
582
+ );
583
+ }
584
+ if (expected.nullable !== actual.nullable) {
585
+ calls.push(
586
+ expected.nullable
587
+ ? new DropNotNullCall(schemaName, tableName, expected.name)
588
+ : new SetNotNullCall(schemaName, tableName, expected.name),
589
+ );
590
+ }
591
+ return ok(calls);
592
+ }
593
+
594
+ function mapColumnDefaultNodeIssue(
595
+ issue: SchemaDiffIssue,
596
+ schemaName: string,
597
+ tableName: string,
598
+ columnName: string,
599
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
600
+ if (issue.reason === 'not-expected') {
601
+ return ok([new DropDefaultCall(schemaName, tableName, columnName)]);
602
+ }
603
+ // not-found (SET DEFAULT, additive) or not-equal (SET DEFAULT, widening).
604
+ if (issue.expected === undefined) return ok([]);
605
+ const defaultNode = blindCast<
606
+ SqlColumnDefaultIR,
607
+ 'a not-found/not-equal column-default issue always carries the expected default node'
608
+ >(issue.expected);
609
+ const defaultSql = renderColumnDefaultSql(defaultNode);
610
+ if (!defaultSql) return ok([]);
611
+ return ok([
612
+ new SetDefaultCall(
613
+ schemaName,
614
+ tableName,
615
+ columnName,
616
+ defaultSql,
617
+ issue.reason === 'not-equal' ? 'widening' : 'additive',
618
+ ),
619
+ ]);
620
+ }
621
+
622
+ function mapPrimaryKeyNodeIssue(
623
+ issue: SchemaDiffIssue,
624
+ schemaName: string,
625
+ tableName: string,
626
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
627
+ if (issue.reason === 'not-found') {
628
+ const pk = blindCast<
629
+ { readonly columns: readonly string[]; readonly name?: string },
630
+ 'a not-found primary-key issue always carries the expected PrimaryKey node'
631
+ >(issue.expected);
632
+ const constraintName = pk.name ?? `${tableName}_pkey`;
633
+ return ok([new AddPrimaryKeyCall(schemaName, tableName, constraintName, [...pk.columns])]);
634
+ }
635
+ if (issue.reason === 'not-expected') {
636
+ const pk = blindCast<
637
+ { readonly name?: string },
638
+ 'a not-expected primary-key issue always carries the actual PrimaryKey node'
639
+ >(issue.actual);
640
+ return ok([
641
+ new DropConstraintCall(schemaName, tableName, pk.name ?? `${tableName}_pkey`, 'primaryKey'),
642
+ ]);
643
+ }
644
+ return notOk(nodeConflict('indexIncompatible', issue.message));
645
+ }
646
+
647
+ function mapForeignKeyNodeIssue(
648
+ issue: SchemaDiffIssue,
649
+ schemaName: string,
650
+ tableName: string,
651
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
652
+ if (issue.reason === 'not-found') {
653
+ const fk = blindCast<
654
+ SqlForeignKeyIR,
655
+ 'a not-found foreign-key issue always carries the expected foreign-key node'
656
+ >(issue.expected);
657
+ return ok([new AddForeignKeyCall(schemaName, tableName, fkSpecFromNode(fk, tableName))]);
658
+ }
659
+ if (issue.reason === 'not-expected') {
660
+ const fk = blindCast<
661
+ SqlForeignKeyIR,
662
+ 'a not-expected foreign-key issue always carries the actual foreign-key node'
663
+ >(issue.actual);
664
+ const name = fk.name ?? `${tableName}_${fk.columns.join('_')}_fkey`;
665
+ return ok([new DropConstraintCall(schemaName, tableName, name, 'foreignKey')]);
666
+ }
667
+ return notOk(nodeConflict('foreignKeyConflict', issue.message));
668
+ }
669
+
670
+ function mapUniqueNodeIssue(
671
+ issue: SchemaDiffIssue,
672
+ schemaName: string,
673
+ tableName: string,
674
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
675
+ if (issue.reason === 'not-found') {
676
+ const unique = blindCast<
677
+ SqlUniqueIR,
678
+ 'a not-found unique issue always carries the expected unique node'
679
+ >(issue.expected);
680
+ const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;
681
+ return ok([new AddUniqueCall(schemaName, tableName, name, [...unique.columns])]);
682
+ }
683
+ if (issue.reason === 'not-expected') {
684
+ const unique = blindCast<
685
+ SqlUniqueIR,
686
+ 'a not-expected unique issue always carries the actual unique node'
687
+ >(issue.actual);
688
+ const name = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;
689
+ return ok([new DropConstraintCall(schemaName, tableName, name, 'unique')]);
690
+ }
691
+ return notOk(nodeConflict('indexIncompatible', issue.message));
692
+ }
693
+
694
+ function mapIndexNodeIssue(
695
+ issue: SchemaDiffIssue,
696
+ schemaName: string,
697
+ tableName: string,
698
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
699
+ if (issue.reason === 'not-found') {
700
+ const index = blindCast<
701
+ SqlIndexIR,
702
+ 'a not-found index issue always carries the expected index node'
703
+ >(issue.expected);
704
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns);
705
+ const extras: { type?: string; options?: Record<string, unknown> } = {};
706
+ if (index.type !== undefined) extras.type = index.type;
707
+ if (index.options !== undefined) extras.options = index.options;
708
+ return ok([new CreateIndexCall(schemaName, tableName, indexName, [...index.columns], extras)]);
709
+ }
710
+ if (issue.reason === 'not-expected') {
711
+ const index = blindCast<
712
+ SqlIndexIR,
713
+ 'a not-expected index issue always carries the actual index node'
714
+ >(issue.actual);
715
+ const indexName = index.name ?? defaultIndexName(tableName, index.columns);
716
+ return ok([new DropIndexCall(schemaName, tableName, indexName)]);
717
+ }
718
+ return notOk(nodeConflict('indexIncompatible', issue.message));
719
+ }
720
+
721
+ function mapCheckNodeIssue(
722
+ issue: SchemaDiffIssue,
723
+ schemaName: string,
724
+ tableName: string,
725
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
726
+ // check_removed (extra live check not in contract) is the only check drift
727
+ // the default mapper handles directly; check_missing / check_mismatch are
728
+ // consumed by `checkConstraintPlanCallStrategy` (drop+recreate), so reaching
729
+ // here for them means the strategy did not run — a conflict.
730
+ if (issue.reason === 'not-expected') {
731
+ const check = blindCast<
732
+ { readonly name: string },
733
+ 'a not-expected check issue always carries the actual check node'
734
+ >(issue.actual);
735
+ return ok([new DropCheckConstraintCall(schemaName, tableName, check.name)]);
736
+ }
737
+ return notOk(
738
+ nodeConflict(
739
+ 'unsupportedOperation',
740
+ `Check constraint drift on "${tableName}" — handled by checkConstraintPlanCallStrategy: ${issue.message}`,
741
+ ),
742
+ );
743
+ }
744
+
745
+ /**
746
+ * Maps one node-typed diff issue to its migration call(s), dispatching on the
747
+ * node's `nodeKind` + `issue.reason`, reading nodes and resolving column DDL
748
+ * from `codecRef` via `column-ddl-rendering.ts`.
749
+ */
750
+ export function mapNodeIssueToCall(
751
+ issue: SchemaDiffIssue,
752
+ ctx: StrategyContext,
753
+ ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
754
+ const node = issueNode(issue);
755
+ if (node === undefined) {
756
+ return notOk(
757
+ nodeConflict(
758
+ 'unsupportedOperation',
759
+ `Issue carries neither an expected nor an actual node: ${issue.message}`,
760
+ ),
761
+ );
762
+ }
763
+ if (node.nodeKind === PostgresSchemaNodeKind.namespace) {
764
+ if (issue.reason !== 'not-found') {
765
+ return notOk(
766
+ nodeConflict('unsupportedOperation', `Unexpected namespace drift: ${issue.message}`),
767
+ );
768
+ }
769
+ const namespace = blindCast<
770
+ PostgresNamespaceSchemaNode,
771
+ 'a namespace-presence issue always carries a PostgresNamespaceSchemaNode'
772
+ >(issue.expected);
773
+ return ok([new CreateSchemaCall(namespace.schemaName)]);
774
+ }
775
+
776
+ const ddlSchemaName = issueSchemaName(issue);
777
+ const tableName = issueTableName(issue);
778
+ if (ddlSchemaName === undefined || tableName === undefined) {
779
+ return notOk(
780
+ nodeConflict(
781
+ 'unsupportedOperation',
782
+ `Issue has no schema/table in its path: ${issue.message}`,
783
+ ),
784
+ );
785
+ }
786
+ const schemaName = emissionSchemaName(ctx, ddlSchemaName);
787
+
788
+ switch (node.nodeKind) {
789
+ case PostgresSchemaNodeKind.table:
790
+ return mapTableNodeIssue(issue, schemaName, ctx.codecHooks);
791
+ case RelationalSchemaNodeKind.column:
792
+ return mapColumnNodeIssue(issue, schemaName, tableName, ctx.codecHooks);
793
+ case RelationalSchemaNodeKind.columnDefault: {
794
+ const columnName = issueColumnName(issue);
795
+ if (columnName === undefined) {
796
+ return notOk(
797
+ nodeConflict(
798
+ 'unsupportedOperation',
799
+ `Default issue has no column in its path: ${issue.message}`,
800
+ ),
801
+ );
802
+ }
803
+ return mapColumnDefaultNodeIssue(issue, schemaName, tableName, columnName);
804
+ }
805
+ case RelationalSchemaNodeKind.primaryKey:
806
+ return mapPrimaryKeyNodeIssue(issue, schemaName, tableName);
807
+ case RelationalSchemaNodeKind.foreignKey:
808
+ return mapForeignKeyNodeIssue(issue, schemaName, tableName);
809
+ case RelationalSchemaNodeKind.unique:
810
+ return mapUniqueNodeIssue(issue, schemaName, tableName);
811
+ case RelationalSchemaNodeKind.index:
812
+ return mapIndexNodeIssue(issue, schemaName, tableName);
813
+ case RelationalSchemaNodeKind.check:
814
+ return mapCheckNodeIssue(issue, schemaName, tableName);
815
+ default:
816
+ return notOk(nodeConflict('unsupportedOperation', `Unhandled node kind: ${node.nodeKind}`));
817
+ }
818
+ }
819
+
820
+ export interface IssuePlannerOptions {
821
+ readonly issues: readonly SchemaDiffIssue[];
822
+ readonly toContract: Contract<SqlStorage>;
823
+ readonly fromContract: Contract<SqlStorage> | null;
824
+ readonly schemaName: string;
825
+ readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;
826
+ readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;
827
+ /**
828
+ * Current database schema IR. Strategies read this to detect whether a
829
+ * structure already exists (e.g. `buildSchemaLookupMap` for shared-temp-
830
+ * default safety, extension dependency checks). Defaults to an empty schema
831
+ * when omitted so the planner can still run over "fresh DB" contract
832
+ * snapshots.
833
+ */
834
+ readonly schema?: SqlSchemaIR;
835
+ /**
836
+ * Operation-class policy. `planIssues` filters calls whose `operationClass`
837
+ * is not in `policy.allowedOperationClasses` and surfaces them as conflicts
838
+ * instead of emitting disallowed DDL. Defaults to additive-only.
839
+ */
840
+ readonly policy?: MigrationOperationPolicy;
841
+ /**
842
+ * Framework components participating in this composition. Available to
843
+ * future strategies that may consult component metadata at plan time.
844
+ */
845
+ readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
846
+ readonly strategies?: readonly CallMigrationStrategy[];
847
+ }
848
+
849
+ /**
850
+ * Runs the ordered strategy list over the node-typed diff issues, maps
851
+ * leftover issues via {@link mapNodeIssueToCall}, applies operation-class
852
+ * policy gating, and buckets calls into the fixed DDL emission order (dep →
853
+ * drop → table → column → recipe → alter → primaryKey → unique → index →
854
+ * foreignKey).
855
+ */
845
856
  export function planIssues(
846
857
  options: IssuePlannerOptions,
847
858
  ): 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
859
  const policyProvided = options.policy !== undefined;
853
860
  const policy = options.policy ?? DEFAULT_POLICY;
854
861
  const schema = options.schema ?? emptySchemaIR();
@@ -884,10 +891,10 @@ export function planIssues(
884
891
  }
885
892
 
886
893
  const sorted = [...remaining].sort((a, b) => {
887
- const kindDelta = issueOrder(a) - issueOrder(b);
894
+ const kindDelta = nodeIssueOrder(a) - nodeIssueOrder(b);
888
895
  if (kindDelta !== 0) return kindDelta;
889
- const keyA = issueKey(a);
890
- const keyB = issueKey(b);
896
+ const keyA = nodeIssueKey(a);
897
+ const keyB = nodeIssueKey(b);
891
898
  return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
892
899
  });
893
900
 
@@ -895,7 +902,7 @@ export function planIssues(
895
902
  const conflicts: SqlPlannerConflict[] = [];
896
903
 
897
904
  for (const issue of sorted) {
898
- const result = mapIssueToCall(issue, context);
905
+ const result = mapNodeIssueToCall(issue, context);
899
906
  if (result.ok) {
900
907
  defaultCalls.push(...result.value);
901
908
  } else {
@@ -903,11 +910,6 @@ export function planIssues(
903
910
  }
904
911
  }
905
912
 
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
913
  const allowed = policy.allowedOperationClasses;
912
914
  let gatedDefault = defaultCalls;
913
915
  let gatedRecipe = recipeCalls;
@@ -935,13 +937,6 @@ export function planIssues(
935
937
  return notOk(conflicts);
936
938
  }
937
939
 
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
940
  const combinedBucketable = [...gatedDefault, ...gatedBucketable];
946
941
  const byCategory = (cat: CallCategory) =>
947
942
  combinedBucketable.filter((c) => classifyCall(c) === cat);