@prisma-next/target-postgres 0.14.0-dev.6 → 0.14.0-dev.60

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