@prisma-next/target-postgres 0.14.0-dev.49 → 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 (97) hide show
  1. package/dist/control-policy-DUFgy9jO.mjs +1103 -0
  2. package/dist/control-policy-DUFgy9jO.mjs.map +1 -0
  3. package/dist/control.d.mts.map +1 -1
  4. package/dist/control.mjs +19 -40
  5. package/dist/control.mjs.map +1 -1
  6. package/dist/default-normalizer.mjs +247 -1
  7. package/dist/default-normalizer.mjs.map +1 -0
  8. package/dist/diff-database-schema-BmSmWcaY.mjs +313 -0
  9. package/dist/diff-database-schema-BmSmWcaY.mjs.map +1 -0
  10. package/dist/diff-database-schema.d.mts +46 -0
  11. package/dist/diff-database-schema.d.mts.map +1 -0
  12. package/dist/diff-database-schema.mjs +2 -0
  13. package/dist/issue-planner.d.mts +34 -10
  14. package/dist/issue-planner.d.mts.map +1 -1
  15. package/dist/issue-planner.mjs +2 -2
  16. package/dist/migration.d.mts +2 -2
  17. package/dist/migration.mjs +2 -2
  18. package/dist/native-type-normalizer.mjs +37 -1
  19. package/dist/native-type-normalizer.mjs.map +1 -0
  20. package/dist/{op-factory-call-BuoGT5UI.mjs → op-factory-call-BKRnMgrB.mjs} +2 -2
  21. package/dist/op-factory-call-BKRnMgrB.mjs.map +1 -0
  22. package/dist/{op-factory-call-Caqus-Qg.d.mts → op-factory-call-Dt-Jx5JS.d.mts} +2 -2
  23. package/dist/{op-factory-call-Caqus-Qg.d.mts.map → op-factory-call-Dt-Jx5JS.d.mts.map} +1 -1
  24. package/dist/op-factory-call.d.mts +2 -2
  25. package/dist/op-factory-call.mjs +2 -2
  26. package/dist/planner-BMBRPzsv.mjs +367 -0
  27. package/dist/planner-BMBRPzsv.mjs.map +1 -0
  28. package/dist/planner-ddl-builders-B8Nn6nHN.mjs.map +1 -1
  29. package/dist/planner-ddl-builders.d.mts +2 -2
  30. package/dist/planner-ddl-builders.d.mts.map +1 -1
  31. package/dist/planner-identity-values-CJPha2Sz.mjs.map +1 -1
  32. package/dist/planner-identity-values.d.mts +7 -1
  33. package/dist/planner-identity-values.d.mts.map +1 -1
  34. package/dist/planner-identity-values.mjs +2 -2
  35. package/dist/{planner-produced-postgres-migration-CtJi4sgS.d.mts → planner-produced-postgres-migration-C0a7I1-e.d.mts} +2 -2
  36. package/dist/{planner-produced-postgres-migration-CtJi4sgS.d.mts.map → planner-produced-postgres-migration-C0a7I1-e.d.mts.map} +1 -1
  37. package/dist/{planner-produced-postgres-migration-C2_H6Vvl.mjs → planner-produced-postgres-migration-Dp6IO_gj.mjs} +2 -2
  38. package/dist/{planner-produced-postgres-migration-C2_H6Vvl.mjs.map → planner-produced-postgres-migration-Dp6IO_gj.mjs.map} +1 -1
  39. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  40. package/dist/planner-produced-postgres-migration.mjs +1 -1
  41. package/dist/planner-sql-checks-Cze3vMfe.mjs.map +1 -1
  42. package/dist/planner-sql-checks.d.mts +1 -1
  43. package/dist/planner-sql-checks.d.mts.map +1 -1
  44. package/dist/planner.d.mts +27 -67
  45. package/dist/planner.d.mts.map +1 -1
  46. package/dist/planner.mjs +3 -2
  47. package/dist/{postgres-database-schema-node-os8ogEap.d.mts → postgres-database-schema-node-C9bTuMrd.d.mts} +14 -7
  48. package/dist/postgres-database-schema-node-C9bTuMrd.d.mts.map +1 -0
  49. package/dist/{postgres-migration-D0QIVE-p.mjs → postgres-migration-D0jwzYDT.mjs} +2 -2
  50. package/dist/{postgres-migration-D0QIVE-p.mjs.map → postgres-migration-D0jwzYDT.mjs.map} +1 -1
  51. package/dist/{postgres-migration-CfyKDT7b.d.mts → postgres-migration-DFaxuRyI.d.mts} +2 -2
  52. package/dist/{postgres-migration-CfyKDT7b.d.mts.map → postgres-migration-DFaxuRyI.d.mts.map} +1 -1
  53. package/dist/{postgres-table-schema-node-Clei_xel.mjs → postgres-table-schema-node-BgaSrxYN.mjs} +30 -29
  54. package/dist/postgres-table-schema-node-BgaSrxYN.mjs.map +1 -0
  55. package/dist/schema-node-kinds-ClScchhi.mjs +76 -0
  56. package/dist/schema-node-kinds-ClScchhi.mjs.map +1 -0
  57. package/dist/types.d.mts +1 -1
  58. package/dist/types.mjs +1 -1
  59. package/package.json +21 -20
  60. package/src/core/migrations/column-ddl-rendering.ts +117 -0
  61. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +25 -1
  62. package/src/core/migrations/control-policy.ts +68 -48
  63. package/src/core/migrations/diff-database-schema.ts +242 -153
  64. package/src/core/migrations/issue-planner.ts +621 -667
  65. package/src/core/migrations/operations/constraints.ts +1 -1
  66. package/src/core/migrations/planner-ddl-builders.ts +5 -2
  67. package/src/core/migrations/planner-identity-values.ts +1 -1
  68. package/src/core/migrations/planner-sql-checks.ts +1 -1
  69. package/src/core/migrations/planner-strategies.ts +248 -208
  70. package/src/core/migrations/planner.ts +180 -74
  71. package/src/core/migrations/runner.ts +1 -4
  72. package/src/core/migrations/verify-postgres-namespaces.ts +26 -15
  73. package/src/core/postgres-schema-verifier.ts +10 -7
  74. package/src/core/psl-infer/infer-psl-contract.ts +5 -10
  75. package/src/core/schema-ir/postgres-database-schema-node.ts +3 -6
  76. package/src/core/schema-ir/postgres-namespace-schema-node.ts +8 -9
  77. package/src/core/schema-ir/postgres-policy-schema-node.ts +3 -6
  78. package/src/core/schema-ir/postgres-role-schema-node.ts +3 -6
  79. package/src/core/schema-ir/postgres-table-schema-node.ts +20 -9
  80. package/src/core/schema-ir/schema-node-kinds.ts +80 -2
  81. package/src/exports/control.ts +10 -43
  82. package/src/exports/diff-database-schema.ts +7 -0
  83. package/src/exports/issue-planner.ts +1 -1
  84. package/src/exports/op-factory-call.ts +1 -0
  85. package/src/exports/planner-identity-values.ts +4 -1
  86. package/src/exports/planner.ts +0 -1
  87. package/dist/default-normalizer-Dug8Fez9.mjs +0 -248
  88. package/dist/default-normalizer-Dug8Fez9.mjs.map +0 -1
  89. package/dist/issue-planner-Cbh-xTEr.mjs +0 -849
  90. package/dist/issue-planner-Cbh-xTEr.mjs.map +0 -1
  91. package/dist/native-type-normalizer-Bc9XJzWC.mjs +0 -38
  92. package/dist/native-type-normalizer-Bc9XJzWC.mjs.map +0 -1
  93. package/dist/op-factory-call-BuoGT5UI.mjs.map +0 -1
  94. package/dist/planner-Bq0Z2sVO.mjs +0 -641
  95. package/dist/planner-Bq0Z2sVO.mjs.map +0 -1
  96. package/dist/postgres-database-schema-node-os8ogEap.d.mts.map +0 -1
  97. package/dist/postgres-table-schema-node-Clei_xel.mjs.map +0 -1
@@ -1,37 +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/diff';
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';
34
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';
35
57
  import {
36
58
  AddColumnCall,
37
59
  AddForeignKeyCall,
@@ -49,22 +71,15 @@ import {
49
71
  DropNotNullCall,
50
72
  DropTableCall,
51
73
  type PostgresOpFactoryCall,
52
- postgresDefaultToDdlColumnDefault,
53
74
  SetDefaultCall,
54
75
  SetNotNullCall,
55
76
  } from './op-factory-call';
56
77
  import type { ForeignKeySpec } from './operations/shared';
57
- import { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';
58
- import { buildExpectedFormatType } from './planner-sql-checks';
59
78
  import {
60
79
  type CallMigrationStrategy,
61
80
  postgresPlannerStrategies,
62
- resolveDdlSchemaForNamespace,
63
- resolveNamespaceIdForIssue,
64
81
  type StrategyContext,
65
- tableAt,
66
82
  } from './planner-strategies';
67
- import { resolveColumnTypeMetadata } from './planner-type-resolution';
68
83
 
69
84
  export type { CallMigrationStrategy, StrategyContext };
70
85
 
@@ -88,58 +103,6 @@ function elementNonNullCheckExpression(columnName: string): string {
88
103
  return `array_position(${quoteIdentifier(columnName)}, NULL) IS NULL`;
89
104
  }
90
105
 
91
- // ============================================================================
92
- // Issue kind ordering (dependency order)
93
- // ============================================================================
94
-
95
- const ISSUE_KIND_ORDER: Record<string, number> = {
96
- // Schemas first — the database container must exist before any DDL
97
- // that targets it can run.
98
- missing_schema: 1,
99
-
100
- // Types next
101
- type_missing: 2,
102
- type_values_mismatch: 3,
103
- enum_values_changed: 3,
104
-
105
- // Drops (reconciliation — clear the way for creates)
106
- // FKs dropped first (they depend on other constraints)
107
- extra_foreign_key: 10,
108
- extra_unique_constraint: 11,
109
- extra_primary_key: 12,
110
- extra_index: 13,
111
- extra_default: 14,
112
- extra_column: 15,
113
- extra_table: 16,
114
-
115
- // Tables before columns
116
- missing_table: 20,
117
-
118
- // Columns before constraints
119
- missing_column: 30,
120
-
121
- // Reconciliation alters (on existing objects)
122
- type_mismatch: 40,
123
- nullability_mismatch: 41,
124
- default_missing: 42,
125
- default_mismatch: 43,
126
-
127
- // Constraints after columns exist
128
- primary_key_mismatch: 50,
129
- unique_constraint_mismatch: 51,
130
- index_mismatch: 52,
131
- foreign_key_mismatch: 60,
132
-
133
- // Check constraints
134
- check_missing: 53,
135
- check_mismatch: 54,
136
- check_removed: 55,
137
- };
138
-
139
- function issueOrder(issue: SchemaIssue): number {
140
- return ISSUE_KIND_ORDER[issue.kind] ?? 99;
141
- }
142
-
143
106
  // ============================================================================
144
107
  // Conflict helpers
145
108
  // ============================================================================
@@ -157,570 +120,10 @@ function issueConflict(
157
120
  };
158
121
  }
159
122
 
160
- function isMissing(issue: SchemaIssue): boolean {
161
- if (issue.kind === 'enum_values_changed') return false;
162
- return issue.actual === undefined;
163
- }
164
-
165
- // ============================================================================
166
- // Issue planner
167
- // ============================================================================
168
-
169
- export interface IssuePlannerOptions {
170
- readonly issues: readonly SchemaIssue[];
171
- readonly toContract: Contract<SqlStorage>;
172
- readonly fromContract: Contract<SqlStorage> | null;
173
- readonly schemaName: string;
174
- readonly codecHooks: ReadonlyMap<string, CodecControlHooks>;
175
- readonly storageTypes: Readonly<Record<string, StorageTypeInstance>>;
176
- /**
177
- * Current database schema IR. Strategies read this to detect whether a
178
- * structure already exists (e.g. `buildSchemaLookupMap` for shared-temp-
179
- * default safety, extension dependency checks). Defaults to an empty schema
180
- * when omitted so the planner can still run over "fresh DB" contract
181
- * snapshots.
182
- */
183
- readonly schema?: SqlSchemaIR;
184
- /**
185
- * Operation-class policy. `planIssues` filters calls whose `operationClass`
186
- * is not in `policy.allowedOperationClasses` and surfaces them as conflicts
187
- * instead of emitting disallowed DDL. Defaults to additive-only.
188
- */
189
- readonly policy?: MigrationOperationPolicy;
190
- /**
191
- * Framework components participating in this composition. Available to
192
- * future strategies that may consult component metadata at plan time.
193
- */
194
- readonly frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
195
- readonly strategies?: readonly CallMigrationStrategy[];
196
- }
197
-
198
123
  export interface IssuePlannerValue {
199
124
  readonly calls: readonly PostgresOpFactoryCall[];
200
125
  }
201
126
 
202
- function toDdlColumn(
203
- name: string,
204
- column: StorageColumn,
205
- codecHooks: ReadonlyMap<string, CodecControlHooks>,
206
- storageTypes: Readonly<Record<string, StorageTypeInstance>>,
207
- ): DdlColumn {
208
- const typeSql = buildColumnTypeSql(column, codecHooks, storageTypes);
209
- const ddlDefault = postgresDefaultToDdlColumnDefault(column.default);
210
- const resolved = resolveColumnTypeMetadata(
211
- column,
212
- storageTypes as Record<string, StorageTypeInstance>,
213
- );
214
- const codecRef: CodecRef | undefined = resolved.codecId
215
- ? {
216
- codecId: resolved.codecId,
217
- ...(resolved.typeParams !== undefined
218
- ? {
219
- typeParams: blindCast<
220
- JsonValue,
221
- 'resolved.typeParams is JsonValue-shaped storage metadata; the narrowed (non-undefined) value lands in CodecRef.typeParams which is JsonValue'
222
- >(resolved.typeParams),
223
- }
224
- : {}),
225
- }
226
- : undefined;
227
- return contractFree.col(name, typeSql, {
228
- ...(!column.nullable ? { notNull: true } : {}),
229
- ...ifDefined('default', ddlDefault),
230
- ...ifDefined('codecRef', codecRef),
231
- });
232
- }
233
-
234
- function mapIssueToCall(
235
- issue: SchemaIssue,
236
- ctx: StrategyContext,
237
- ): Result<readonly PostgresOpFactoryCall[], SqlPlannerConflict> {
238
- const { schemaName, codecHooks, storageTypes } = ctx;
239
- // Per-table effective schema. `extra_table` issues intentionally
240
- // omit `namespaceId` — the live DB carries a table that
241
- // is not claimed by any contract namespace, so there is no contract
242
- // coordinate to project from. Those issues fall back to the planner's
243
- // global `ctx.schemaName`; every other issue dispatches through the
244
- // resolved namespace's polymorphic `ddlSchemaName`.
245
- const tableSchema = (issue: SchemaIssue): string => {
246
- if (issue.kind === 'extra_table') return schemaName;
247
- if (!('table' in issue) || !issue.table) return schemaName;
248
- return resolveDdlSchemaForNamespace(ctx, resolveNamespaceIdForIssue(issue));
249
- };
250
-
251
- switch (issue.kind) {
252
- case 'missing_schema': {
253
- const namespaceId = issue.namespaceId;
254
- if (!namespaceId)
255
- return notOk(
256
- issueConflict('unsupportedOperation', 'Missing schema issue has no namespaceId'),
257
- );
258
- const ddlSchemaName = resolveDdlSchemaForNamespace(ctx, namespaceId);
259
- return ok([new CreateSchemaCall(ddlSchemaName)]);
260
- }
261
-
262
- case 'missing_table': {
263
- if (!issue.table)
264
- return notOk(
265
- issueConflict('unsupportedOperation', 'Missing table issue has no table name'),
266
- );
267
- const namespaceId = resolveNamespaceIdForIssue(issue);
268
- const contractTable = tableAt(ctx.toContract.storage, namespaceId, issue.table);
269
- if (!contractTable) {
270
- return notOk(
271
- issueConflict(
272
- 'unsupportedOperation',
273
- `Table "${issue.table}" in namespace "${namespaceId}" reported missing but not found in destination contract`,
274
- ),
275
- );
276
- }
277
- const schemaForTable = tableSchema(issue);
278
- const missingTableName = issue.table;
279
- const ddlColumns: DdlColumn[] = Object.entries(contractTable.columns).map(([name, column]) =>
280
- toDdlColumn(name, column, codecHooks, storageTypes),
281
- );
282
- const primaryKeyConstraints: DdlTableConstraint[] = contractTable.primaryKey
283
- ? [
284
- contractFree.primaryKey(contractTable.primaryKey.columns, {
285
- ...(contractTable.primaryKey.name ? { name: contractTable.primaryKey.name } : {}),
286
- }),
287
- ]
288
- : [];
289
- const elementNonNullChecks: DdlTableConstraint[] = Object.entries(contractTable.columns)
290
- .filter(([, column]) => column.many === true)
291
- .map(([columnName]) =>
292
- contractFree.checkExpression(
293
- elementNonNullCheckName(missingTableName, columnName),
294
- elementNonNullCheckExpression(columnName),
295
- ),
296
- );
297
- const allTableConstraints = [...primaryKeyConstraints, ...elementNonNullChecks];
298
- const ddlConstraints: DdlTableConstraint[] | undefined =
299
- allTableConstraints.length > 0 ? allTableConstraints : undefined;
300
- const calls: PostgresOpFactoryCall[] = [
301
- new CreateTableCall(schemaForTable, issue.table, ddlColumns, ddlConstraints),
302
- ];
303
- for (const index of contractTable.indexes) {
304
- const indexName = index.name ?? `${issue.table}_${index.columns.join('_')}_idx`;
305
- const extras: { type?: string; options?: Record<string, unknown> } = {};
306
- if (index.type !== undefined) extras.type = index.type;
307
- if (index.options !== undefined) extras.options = index.options;
308
- calls.push(
309
- new CreateIndexCall(schemaForTable, issue.table, indexName, [...index.columns], extras),
310
- );
311
- }
312
- const explicitIndexColumnSets = new Set(
313
- contractTable.indexes.map((idx) => idx.columns.join(',')),
314
- );
315
- for (const fk of contractTable.foreignKeys) {
316
- if (fk.constraint) {
317
- const fkName = fk.name ?? `${issue.table}_${fk.source.columns.join('_')}_fkey`;
318
- const fkSpec: ForeignKeySpec = {
319
- name: fkName,
320
- columns: fk.source.columns,
321
- references: {
322
- schema: fk.target.namespaceId,
323
- table: fk.target.tableName,
324
- columns: fk.target.columns,
325
- },
326
- ...(fk.onDelete !== undefined && { onDelete: fk.onDelete }),
327
- ...(fk.onUpdate !== undefined && { onUpdate: fk.onUpdate }),
328
- };
329
- calls.push(new AddForeignKeyCall(schemaForTable, issue.table, fkSpec));
330
- }
331
- if (fk.index && !explicitIndexColumnSets.has(fk.source.columns.join(','))) {
332
- const indexName = `${issue.table}_${fk.source.columns.join('_')}_idx`;
333
- calls.push(
334
- new CreateIndexCall(schemaForTable, issue.table, indexName, [...fk.source.columns]),
335
- );
336
- }
337
- }
338
- for (const unique of contractTable.uniques) {
339
- const constraintName = unique.name ?? `${issue.table}_${unique.columns.join('_')}_key`;
340
- calls.push(
341
- new AddUniqueCall(schemaForTable, issue.table, constraintName, [...unique.columns]),
342
- );
343
- }
344
- return ok(calls);
345
- }
346
-
347
- case 'missing_column':
348
- if (!issue.table || !issue.column)
349
- return notOk(
350
- issueConflict('unsupportedOperation', 'Missing column issue has no table/column name'),
351
- );
352
- {
353
- const namespaceId = resolveNamespaceIdForIssue(issue);
354
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
355
- issue.column
356
- ];
357
- if (!column)
358
- return notOk(
359
- issueConflict(
360
- 'unsupportedOperation',
361
- `Column "${issue.table}"."${issue.column}" not in destination contract`,
362
- ),
363
- );
364
- return ok([
365
- new AddColumnCall(
366
- tableSchema(issue),
367
- issue.table,
368
- toDdlColumn(issue.column, column, codecHooks, storageTypes),
369
- ),
370
- ]);
371
- }
372
-
373
- case 'default_missing':
374
- if (!issue.table || !issue.column)
375
- return notOk(
376
- issueConflict('unsupportedOperation', 'Default missing issue has no table/column name'),
377
- );
378
- {
379
- const namespaceId = resolveNamespaceIdForIssue(issue);
380
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
381
- issue.column
382
- ];
383
- if (!column?.default) {
384
- return notOk(
385
- issueConflict(
386
- 'unsupportedOperation',
387
- `Column "${issue.table}"."${issue.column}" has no default in contract`,
388
- ),
389
- );
390
- }
391
- const defaultSql = buildColumnDefaultSql(column.default, column);
392
- if (!defaultSql) return ok([]);
393
- return ok([new SetDefaultCall(tableSchema(issue), issue.table, issue.column, defaultSql)]);
394
- }
395
-
396
- case 'extra_table':
397
- if (!issue.table)
398
- return notOk(issueConflict('unsupportedOperation', 'Extra table issue has no table name'));
399
- return ok([new DropTableCall(tableSchema(issue), issue.table)]);
400
-
401
- case 'extra_column':
402
- if (!issue.table || !issue.column)
403
- return notOk(
404
- issueConflict('unsupportedOperation', 'Extra column issue has no table/column name'),
405
- );
406
- return ok([new DropColumnCall(tableSchema(issue), issue.table, issue.column)]);
407
-
408
- case 'extra_index':
409
- if (!issue.table || !issue.indexOrConstraint)
410
- return notOk(
411
- issueConflict('unsupportedOperation', 'Extra index issue has no table/index name'),
412
- );
413
- return ok([new DropIndexCall(tableSchema(issue), issue.table, issue.indexOrConstraint)]);
414
-
415
- case 'extra_unique_constraint':
416
- case 'extra_foreign_key':
417
- case 'extra_primary_key': {
418
- if (!issue.table)
419
- return notOk(
420
- issueConflict(
421
- 'unsupportedOperation',
422
- 'Extra constraint issue has no table/constraint name',
423
- ),
424
- );
425
- // `extra_primary_key` issues don't carry a constraint name — the
426
- // verifier only has the table. Fall back to `<table>_pkey`, matching
427
- // Postgres' default PK constraint naming and the old reconciliation
428
- // planner's behavior.
429
- const constraintName =
430
- issue.indexOrConstraint ??
431
- (issue.kind === 'extra_primary_key' ? `${issue.table}_pkey` : undefined);
432
- if (!constraintName)
433
- return notOk(
434
- issueConflict(
435
- 'unsupportedOperation',
436
- 'Extra constraint issue has no table/constraint name',
437
- ),
438
- );
439
- const kindMap = {
440
- extra_unique_constraint: 'unique' as const,
441
- extra_foreign_key: 'foreignKey' as const,
442
- extra_primary_key: 'primaryKey' as const,
443
- };
444
- return ok([
445
- new DropConstraintCall(
446
- tableSchema(issue),
447
- issue.table,
448
- constraintName,
449
- kindMap[issue.kind],
450
- ),
451
- ]);
452
- }
453
-
454
- case 'extra_default':
455
- if (!issue.table || !issue.column)
456
- return notOk(
457
- issueConflict('unsupportedOperation', 'Extra default issue has no table/column name'),
458
- );
459
- return ok([new DropDefaultCall(tableSchema(issue), issue.table, issue.column)]);
460
-
461
- case 'nullability_mismatch': {
462
- if (!issue.table || !issue.column)
463
- return notOk(
464
- issueConflict('nullabilityConflict', 'Nullability mismatch has no table/column name'),
465
- );
466
- const namespaceId = resolveNamespaceIdForIssue(issue);
467
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
468
- issue.column
469
- ];
470
- if (!column)
471
- return notOk(
472
- issueConflict(
473
- 'nullabilityConflict',
474
- `Column "${issue.table}"."${issue.column}" not found in destination contract`,
475
- ),
476
- );
477
- const schemaForTable = tableSchema(issue);
478
- return ok(
479
- column.nullable
480
- ? [new DropNotNullCall(schemaForTable, issue.table, issue.column)]
481
- : [new SetNotNullCall(schemaForTable, issue.table, issue.column)],
482
- );
483
- }
484
-
485
- case 'type_mismatch':
486
- if (!issue.table || !issue.column)
487
- return notOk(issueConflict('typeMismatch', 'Type mismatch has no table/column name'));
488
- {
489
- const namespaceId = resolveNamespaceIdForIssue(issue);
490
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
491
- issue.column
492
- ];
493
- if (!column)
494
- return notOk(
495
- issueConflict(
496
- 'typeMismatch',
497
- `Column "${issue.table}"."${issue.column}" not in destination contract`,
498
- ),
499
- );
500
- const hooksMap = codecHooks as Map<string, CodecControlHooks>;
501
- const typesMap = storageTypes as Record<string, StorageTypeInstance>;
502
- const qualifiedTargetType = buildColumnTypeSql(column, hooksMap, typesMap, false);
503
- const formatTypeExpected = buildExpectedFormatType(column, hooksMap, typesMap);
504
- return ok([
505
- new AlterColumnTypeCall(tableSchema(issue), issue.table, issue.column, {
506
- qualifiedTargetType,
507
- formatTypeExpected,
508
- rawTargetTypeForLabel: qualifiedTargetType,
509
- }),
510
- ]);
511
- }
512
-
513
- case 'default_mismatch':
514
- if (!issue.table || !issue.column)
515
- return notOk(
516
- issueConflict('unsupportedOperation', 'Default mismatch has no table/column name'),
517
- );
518
- {
519
- const namespaceId = resolveNamespaceIdForIssue(issue);
520
- const column = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.columns[
521
- issue.column
522
- ];
523
- if (!column?.default) return ok([]);
524
- const defaultSql = buildColumnDefaultSql(column.default, column);
525
- if (!defaultSql) return ok([]);
526
- return ok([
527
- new SetDefaultCall(tableSchema(issue), issue.table, issue.column, defaultSql, 'widening'),
528
- ]);
529
- }
530
-
531
- case 'primary_key_mismatch':
532
- if (!issue.table)
533
- return notOk(issueConflict('indexIncompatible', 'Primary key issue has no table name'));
534
- if (isMissing(issue)) {
535
- const namespaceId = resolveNamespaceIdForIssue(issue);
536
- const pk = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.primaryKey;
537
- if (!pk)
538
- return notOk(
539
- issueConflict('indexIncompatible', `No primary key in contract for "${issue.table}"`),
540
- );
541
- const constraintName = pk.name ?? `${issue.table}_pkey`;
542
- return ok([
543
- new AddPrimaryKeyCall(tableSchema(issue), issue.table, constraintName, pk.columns),
544
- ]);
545
- }
546
- return notOk(
547
- issueConflict(
548
- 'indexIncompatible',
549
- `Primary key on "${issue.table}" has different columns (expected: ${issue.expected}, actual: ${issue.actual})`,
550
- { table: issue.table },
551
- ),
552
- );
553
-
554
- case 'unique_constraint_mismatch':
555
- if (!issue.table)
556
- return notOk(
557
- issueConflict('indexIncompatible', 'Unique constraint issue has no table name'),
558
- );
559
- if (isMissing(issue) && issue.expected) {
560
- const columns = issue.expected.split(', ');
561
- const constraintName = `${issue.table}_${columns.join('_')}_key`;
562
- return ok([new AddUniqueCall(tableSchema(issue), issue.table, constraintName, columns)]);
563
- }
564
- return notOk(
565
- issueConflict(
566
- 'indexIncompatible',
567
- `Unique constraint on "${issue.table}" differs (expected: ${issue.expected}, actual: ${issue.actual})`,
568
- { table: issue.table },
569
- ),
570
- );
571
-
572
- case 'index_mismatch':
573
- if (!issue.table)
574
- return notOk(issueConflict('indexIncompatible', 'Index issue has no table name'));
575
- if (isMissing(issue) && issue.expected) {
576
- const namespaceId = resolveNamespaceIdForIssue(issue);
577
- const columns = issue.expected.split(', ');
578
- const contractIndex = tableAt(
579
- ctx.toContract.storage,
580
- namespaceId,
581
- issue.table,
582
- )?.indexes.find((idx: StorageTable['indexes'][number]) =>
583
- arraysEqual(idx.columns, columns),
584
- );
585
- const indexName = contractIndex?.name ?? `${issue.table}_${columns.join('_')}_idx`;
586
- const extras: { type?: string; options?: Record<string, unknown> } = {};
587
- if (contractIndex?.type !== undefined) extras.type = contractIndex.type;
588
- if (contractIndex?.options !== undefined) extras.options = contractIndex.options;
589
- return ok([
590
- new CreateIndexCall(tableSchema(issue), issue.table, indexName, columns, extras),
591
- ]);
592
- }
593
- return notOk(
594
- issueConflict(
595
- 'indexIncompatible',
596
- `Index on "${issue.table}" differs (expected: ${issue.expected}, actual: ${issue.actual})`,
597
- { table: issue.table },
598
- ),
599
- );
600
-
601
- case 'check_missing': {
602
- if (!issue.table || !issue.indexOrConstraint)
603
- return notOk(
604
- issueConflict('unsupportedOperation', 'Check missing issue has no table/constraint name'),
605
- );
606
- // check_missing is normally consumed by checkConstraintPlanCallStrategy.
607
- // This case handles any that arrive here (e.g. in tests that invoke
608
- // mapIssueToCall directly or skip the strategy).
609
- return notOk(
610
- issueConflict(
611
- 'unsupportedOperation',
612
- `Check constraint "${issue.indexOrConstraint}" missing on "${issue.table}" — handled by checkConstraintPlanCallStrategy`,
613
- ),
614
- );
615
- }
616
-
617
- case 'check_mismatch': {
618
- if (!issue.table || !issue.indexOrConstraint)
619
- return notOk(
620
- issueConflict(
621
- 'unsupportedOperation',
622
- 'Check mismatch issue has no table/constraint name',
623
- ),
624
- );
625
- return notOk(
626
- issueConflict(
627
- 'unsupportedOperation',
628
- `Check constraint "${issue.indexOrConstraint}" values mismatch on "${issue.table}" — handled by checkConstraintPlanCallStrategy`,
629
- ),
630
- );
631
- }
632
-
633
- case 'check_removed': {
634
- if (!issue.table || !issue.indexOrConstraint)
635
- return notOk(
636
- issueConflict('unsupportedOperation', 'Check removed issue has no table/constraint name'),
637
- );
638
- return ok([
639
- new DropCheckConstraintCall(tableSchema(issue), issue.table, issue.indexOrConstraint),
640
- ]);
641
- }
642
-
643
- case 'foreign_key_mismatch':
644
- if (!issue.table)
645
- return notOk(issueConflict('foreignKeyConflict', 'Foreign key issue has no table name'));
646
- if (isMissing(issue) && issue.expected) {
647
- const arrowIdx = issue.expected.indexOf(' -> ');
648
- if (arrowIdx >= 0) {
649
- const namespaceId = resolveNamespaceIdForIssue(issue);
650
- const columns = issue.expected.slice(0, arrowIdx).split(', ');
651
- const fkName = `${issue.table}_${columns.join('_')}_fkey`;
652
- const fk = tableAt(ctx.toContract.storage, namespaceId, issue.table)?.foreignKeys.find(
653
- (k) => k.source.columns.join(', ') === columns.join(', '),
654
- );
655
- if (fk) {
656
- const fkSpec: ForeignKeySpec = {
657
- name: fkName,
658
- columns: fk.source.columns,
659
- references: {
660
- schema: fk.target.namespaceId,
661
- table: fk.target.tableName,
662
- columns: fk.target.columns,
663
- },
664
- ...(fk.onDelete !== undefined && { onDelete: fk.onDelete }),
665
- ...(fk.onUpdate !== undefined && { onUpdate: fk.onUpdate }),
666
- };
667
- return ok([new AddForeignKeyCall(tableSchema(issue), issue.table, fkSpec)]);
668
- }
669
- return notOk(
670
- issueConflict(
671
- 'foreignKeyConflict',
672
- `Foreign key on "${issue.table}" (${columns.join(', ')}) not found in destination contract`,
673
- { table: issue.table },
674
- ),
675
- );
676
- }
677
- }
678
- return notOk(
679
- issueConflict(
680
- 'foreignKeyConflict',
681
- `Foreign key on "${issue.table}" differs (expected: ${issue.expected}, actual: ${issue.actual})`,
682
- { table: issue.table },
683
- ),
684
- );
685
-
686
- case 'type_missing': {
687
- if (!issue.typeName)
688
- return notOk(issueConflict('unsupportedOperation', 'Type missing issue has no typeName'));
689
- const typeInstance = ctx.toContract.storage.types?.[issue.typeName];
690
- if (!typeInstance) {
691
- return notOk(
692
- issueConflict(
693
- 'unsupportedOperation',
694
- `Type "${issue.typeName}" reported missing but not found in destination contract`,
695
- ),
696
- );
697
- }
698
- return notOk(
699
- issueConflict(
700
- 'unsupportedOperation',
701
- `Type "${issue.typeName}" uses codec "${typeInstance.codecId}" — only value-set types are supported`,
702
- ),
703
- );
704
- }
705
-
706
- case 'type_values_mismatch':
707
- return notOk(
708
- issueConflict(
709
- 'unsupportedOperation',
710
- `Type "${issue.typeName ?? 'unknown'}" values differ — type alteration not yet supported`,
711
- ),
712
- );
713
-
714
- default:
715
- return notOk(
716
- issueConflict(
717
- 'unsupportedOperation',
718
- `Unhandled issue kind: ${(issue as SchemaIssue).kind}`,
719
- ),
720
- );
721
- }
722
- }
723
-
724
127
  /**
725
128
  * Classifies calls into dependency order categories for correct DDL sequencing.
726
129
  */
@@ -801,17 +204,6 @@ function classifyCall(call: PostgresOpFactoryCall): CallCategory {
801
204
  }
802
205
  }
803
206
 
804
- /** Stable lexical key used to order issues within the same kind bucket. */
805
- function issueKey(issue: SchemaIssue): string {
806
- const table = 'table' in issue && typeof issue.table === 'string' ? issue.table : '';
807
- const column = 'column' in issue && typeof issue.column === 'string' ? issue.column : '';
808
- const name =
809
- 'indexOrConstraint' in issue && typeof issue.indexOrConstraint === 'string'
810
- ? issue.indexOrConstraint
811
- : '';
812
- return `${table}\u0000${column}\u0000${name}`;
813
- }
814
-
815
207
  // When no policy is explicitly supplied (test-only path; production callers
816
208
  // always pass one), allow every class so strategies that gate on
817
209
  // `'data'` (data-safe placeholders) still fire — the test is treated as
@@ -822,7 +214,7 @@ const DEFAULT_POLICY: MigrationOperationPolicy = {
822
214
  };
823
215
 
824
216
  function emptySchemaIR(): SqlSchemaIR {
825
- return { tables: {} };
217
+ return new SqlSchemaIR({ tables: {} });
826
218
  }
827
219
 
828
220
  function conflictKindForCall(call: PostgresOpFactoryCall): SqlPlannerConflict['kind'] {
@@ -883,13 +275,587 @@ function conflictForDisallowedCall(
883
275
  };
884
276
  }
885
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
+ */
886
856
  export function planIssues(
887
857
  options: IssuePlannerOptions,
888
858
  ): Result<IssuePlannerValue, readonly SqlPlannerConflict[]> {
889
- // When no policy is supplied, `planIssues` treats the call as trusted (the
890
- // caller — typically a test — has already vetted the issues). Only explicit
891
- // policies gate operation classes into conflicts.
892
- // `PostgresMigrationPlanner` always passes an explicit policy.
893
859
  const policyProvided = options.policy !== undefined;
894
860
  const policy = options.policy ?? DEFAULT_POLICY;
895
861
  const schema = options.schema ?? emptySchemaIR();
@@ -925,10 +891,10 @@ export function planIssues(
925
891
  }
926
892
 
927
893
  const sorted = [...remaining].sort((a, b) => {
928
- const kindDelta = issueOrder(a) - issueOrder(b);
894
+ const kindDelta = nodeIssueOrder(a) - nodeIssueOrder(b);
929
895
  if (kindDelta !== 0) return kindDelta;
930
- const keyA = issueKey(a);
931
- const keyB = issueKey(b);
896
+ const keyA = nodeIssueKey(a);
897
+ const keyB = nodeIssueKey(b);
932
898
  return keyA < keyB ? -1 : keyA > keyB ? 1 : 0;
933
899
  });
934
900
 
@@ -936,7 +902,7 @@ export function planIssues(
936
902
  const conflicts: SqlPlannerConflict[] = [];
937
903
 
938
904
  for (const issue of sorted) {
939
- const result = mapIssueToCall(issue, context);
905
+ const result = mapNodeIssueToCall(issue, context);
940
906
  if (result.ok) {
941
907
  defaultCalls.push(...result.value);
942
908
  } else {
@@ -944,11 +910,6 @@ export function planIssues(
944
910
  }
945
911
  }
946
912
 
947
- // Policy gating: drop calls whose operation class is not allowed and
948
- // surface a conflict describing the disallowed op. Applies to both strategy
949
- // output and default-mapped output. Only active when the caller explicitly
950
- // supplied a policy — direct unit-test invocations (which pass no policy)
951
- // stay as pass-through and keep destructive recipe steps intact.
952
913
  const allowed = policy.allowedOperationClasses;
953
914
  let gatedDefault = defaultCalls;
954
915
  let gatedRecipe = recipeCalls;
@@ -976,13 +937,6 @@ export function planIssues(
976
937
  return notOk(conflicts);
977
938
  }
978
939
 
979
- // Recipe strategies (`notNullBackfillCallStrategy`,
980
- // `nullableTighteningCallStrategy`, etc.) emit a cohesive sequence that must
981
- // stay contiguous. They are inserted at a single pattern slot. Non-recipe
982
- // pattern strategies (`checkConstraintPlanCallStrategy`,
983
- // `storageTypePlanCallStrategy`, `notNullAddColumnCallStrategy`) produce
984
- // individually classifiable calls that slot into DDL buckets alongside
985
- // default-mapped calls.
986
940
  const combinedBucketable = [...gatedDefault, ...gatedBucketable];
987
941
  const byCategory = (cat: CallCategory) =>
988
942
  combinedBucketable.filter((c) => classifyCall(c) === cat);