@prisma-next/target-postgres 0.3.0-dev.6 → 0.3.0-dev.63

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 (46) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +8 -1
  3. package/dist/control.d.mts +16 -0
  4. package/dist/control.d.mts.map +1 -0
  5. package/dist/control.mjs +2947 -0
  6. package/dist/control.mjs.map +1 -0
  7. package/dist/descriptor-meta-DxB8oZzB.mjs +13 -0
  8. package/dist/descriptor-meta-DxB8oZzB.mjs.map +1 -0
  9. package/dist/pack.d.mts +7 -0
  10. package/dist/pack.d.mts.map +1 -0
  11. package/dist/pack.mjs +9 -0
  12. package/dist/pack.mjs.map +1 -0
  13. package/dist/runtime.d.mts +9 -0
  14. package/dist/runtime.d.mts.map +1 -0
  15. package/dist/runtime.mjs +21 -0
  16. package/dist/runtime.mjs.map +1 -0
  17. package/package.json +33 -33
  18. package/src/core/migrations/planner-reconciliation.ts +602 -0
  19. package/src/core/migrations/planner.ts +476 -215
  20. package/src/core/migrations/runner.ts +29 -34
  21. package/src/core/migrations/statement-builders.ts +9 -7
  22. package/src/core/types.ts +5 -0
  23. package/src/exports/control.ts +9 -8
  24. package/src/exports/runtime.ts +7 -12
  25. package/dist/chunk-RKEXRSSI.js +0 -14
  26. package/dist/chunk-RKEXRSSI.js.map +0 -1
  27. package/dist/core/descriptor-meta.d.ts +0 -9
  28. package/dist/core/descriptor-meta.d.ts.map +0 -1
  29. package/dist/core/migrations/planner.d.ts +0 -14
  30. package/dist/core/migrations/planner.d.ts.map +0 -1
  31. package/dist/core/migrations/runner.d.ts +0 -8
  32. package/dist/core/migrations/runner.d.ts.map +0 -1
  33. package/dist/core/migrations/statement-builders.d.ts +0 -30
  34. package/dist/core/migrations/statement-builders.d.ts.map +0 -1
  35. package/dist/exports/control.d.ts +0 -8
  36. package/dist/exports/control.d.ts.map +0 -1
  37. package/dist/exports/control.js +0 -1255
  38. package/dist/exports/control.js.map +0 -1
  39. package/dist/exports/pack.d.ts +0 -4
  40. package/dist/exports/pack.d.ts.map +0 -1
  41. package/dist/exports/pack.js +0 -11
  42. package/dist/exports/pack.js.map +0 -1
  43. package/dist/exports/runtime.d.ts +0 -12
  44. package/dist/exports/runtime.d.ts.map +0 -1
  45. package/dist/exports/runtime.js +0 -19
  46. package/dist/exports/runtime.js.map +0 -1
@@ -0,0 +1,2947 @@
1
+ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-DxB8oZzB.mjs";
2
+ import { SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_VARCHAR_CODEC_ID } from "@prisma-next/sql-relational-core/ast";
3
+ import { arraysEqual, verifySqlSchema } from "@prisma-next/family-sql/schema-verify";
4
+ import { ifDefined } from "@prisma-next/utils/defined";
5
+ import { contractToSchemaIR, createMigrationPlan, extractCodecControlHooks, plannerFailure, plannerSuccess, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
6
+ import { bigintJsonReplacer, isTaggedBigInt } from "@prisma-next/contract/types";
7
+ import { readMarker } from "@prisma-next/family-sql/verify";
8
+ import { SqlQueryError } from "@prisma-next/sql-errors";
9
+ import { ok, okVoid } from "@prisma-next/utils/result";
10
+
11
+ //#region ../../6-adapters/postgres/dist/codec-ids-Bsm9c7ns.mjs
12
+ const PG_TEXT_CODEC_ID = "pg/text@1";
13
+ const PG_ENUM_CODEC_ID = "pg/enum@1";
14
+ const PG_CHAR_CODEC_ID = "pg/char@1";
15
+ const PG_VARCHAR_CODEC_ID = "pg/varchar@1";
16
+ const PG_INT_CODEC_ID = "pg/int@1";
17
+ const PG_INT2_CODEC_ID = "pg/int2@1";
18
+ const PG_INT4_CODEC_ID = "pg/int4@1";
19
+ const PG_INT8_CODEC_ID = "pg/int8@1";
20
+ const PG_FLOAT_CODEC_ID = "pg/float@1";
21
+ const PG_FLOAT4_CODEC_ID = "pg/float4@1";
22
+ const PG_FLOAT8_CODEC_ID = "pg/float8@1";
23
+ const PG_NUMERIC_CODEC_ID = "pg/numeric@1";
24
+ const PG_BOOL_CODEC_ID = "pg/bool@1";
25
+ const PG_BIT_CODEC_ID = "pg/bit@1";
26
+ const PG_VARBIT_CODEC_ID = "pg/varbit@1";
27
+ const PG_TIMESTAMP_CODEC_ID = "pg/timestamp@1";
28
+ const PG_TIMESTAMPTZ_CODEC_ID = "pg/timestamptz@1";
29
+ const PG_TIME_CODEC_ID = "pg/time@1";
30
+ const PG_TIMETZ_CODEC_ID = "pg/timetz@1";
31
+ const PG_INTERVAL_CODEC_ID = "pg/interval@1";
32
+ const PG_JSON_CODEC_ID = "pg/json@1";
33
+ const PG_JSONB_CODEC_ID = "pg/jsonb@1";
34
+
35
+ //#endregion
36
+ //#region ../../6-adapters/postgres/dist/sql-utils-CSfAGEwF.mjs
37
+ /**
38
+ * Shared SQL utility functions for the Postgres adapter.
39
+ *
40
+ * These functions handle safe SQL identifier and literal escaping
41
+ * with security validations to prevent injection and encoding issues.
42
+ */
43
+ /**
44
+ * Error thrown when an invalid SQL identifier or literal is detected.
45
+ * Boundary layers map this to structured envelopes.
46
+ */
47
+ var SqlEscapeError = class extends Error {
48
+ constructor(message, value, kind) {
49
+ super(message);
50
+ this.value = value;
51
+ this.kind = kind;
52
+ this.name = "SqlEscapeError";
53
+ }
54
+ };
55
+ /**
56
+ * Maximum length for PostgreSQL identifiers (NAMEDATALEN - 1).
57
+ */
58
+ const MAX_IDENTIFIER_LENGTH$1 = 63;
59
+ /**
60
+ * Validates and quotes a PostgreSQL identifier (table, column, type, schema names).
61
+ *
62
+ * Security validations:
63
+ * - Rejects null bytes which could cause truncation or unexpected behavior
64
+ * - Rejects empty identifiers
65
+ * - Warns on identifiers exceeding PostgreSQL's 63-character limit
66
+ *
67
+ * @throws {SqlEscapeError} If the identifier contains null bytes or is empty
68
+ */
69
+ function quoteIdentifier(identifier) {
70
+ if (identifier.length === 0) throw new SqlEscapeError("Identifier cannot be empty", identifier, "identifier");
71
+ if (identifier.includes("\0")) throw new SqlEscapeError("Identifier cannot contain null bytes", identifier.replace(/\0/g, "\\0"), "identifier");
72
+ if (identifier.length > MAX_IDENTIFIER_LENGTH$1) console.warn(`Identifier "${identifier.slice(0, 20)}..." exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH$1}-character limit and will be truncated`);
73
+ return `"${identifier.replace(/"/g, "\"\"")}"`;
74
+ }
75
+ /**
76
+ * Escapes a string literal for safe use in SQL statements.
77
+ *
78
+ * Security validations:
79
+ * - Rejects null bytes which could cause truncation or unexpected behavior
80
+ *
81
+ * Note: This assumes PostgreSQL's `standard_conforming_strings` is ON (default since PG 9.1).
82
+ * Backslashes are treated as literal characters, not escape sequences.
83
+ *
84
+ * @throws {SqlEscapeError} If the value contains null bytes
85
+ */
86
+ function escapeLiteral(value) {
87
+ if (value.includes("\0")) throw new SqlEscapeError("Literal value cannot contain null bytes", value.replace(/\0/g, "\\0"), "literal");
88
+ return value.replace(/'/g, "''");
89
+ }
90
+ /**
91
+ * Builds a qualified name (schema.object) with proper quoting.
92
+ */
93
+ function qualifyName(schemaName, objectName) {
94
+ return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;
95
+ }
96
+ /**
97
+ * Validates that an enum value doesn't exceed PostgreSQL's label length limit.
98
+ *
99
+ * PostgreSQL enum labels have a maximum length of NAMEDATALEN-1 (63 bytes by default).
100
+ * Unlike identifiers, enum labels that exceed this limit cause an error rather than
101
+ * silent truncation.
102
+ *
103
+ * @param value - The enum value to validate
104
+ * @param enumTypeName - Name of the enum type (for error messages)
105
+ * @throws {SqlEscapeError} If the value exceeds the maximum length
106
+ */
107
+ function validateEnumValueLength(value, enumTypeName) {
108
+ if (value.length > MAX_IDENTIFIER_LENGTH$1) throw new SqlEscapeError(`Enum value "${value.slice(0, 20)}..." for type "${enumTypeName}" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH$1}-character label limit`, value, "literal");
109
+ }
110
+
111
+ //#endregion
112
+ //#region ../../6-adapters/postgres/dist/descriptor-meta-ilnFI7bx.mjs
113
+ const ENUM_INTROSPECT_QUERY = `
114
+ SELECT
115
+ n.nspname AS schema_name,
116
+ t.typname AS type_name,
117
+ array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values
118
+ FROM pg_type t
119
+ JOIN pg_namespace n ON t.typnamespace = n.oid
120
+ JOIN pg_enum e ON t.oid = e.enumtypid
121
+ WHERE n.nspname = $1
122
+ GROUP BY n.nspname, t.typname
123
+ ORDER BY n.nspname, t.typname
124
+ `;
125
+ /**
126
+ * Type guard for string arrays. Used for runtime validation of introspected data.
127
+ */
128
+ function isStringArray(value) {
129
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
130
+ }
131
+ /**
132
+ * Parses a PostgreSQL array value into a JavaScript string array.
133
+ *
134
+ * PostgreSQL's `pg` library may return `array_agg` results either as:
135
+ * - A JavaScript array (when type parsers are configured)
136
+ * - A string in PostgreSQL array literal format: `{value1,value2,...}`
137
+ *
138
+ * Handles PostgreSQL's quoting rules for array elements:
139
+ * - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted
140
+ * - Inside quoted elements, `\"` represents `"` and `\\` represents `\`
141
+ *
142
+ * @param value - The value to parse (array or PostgreSQL array string)
143
+ * @returns A string array, or null if the value cannot be parsed
144
+ */
145
+ function parsePostgresArray(value) {
146
+ if (isStringArray(value)) return value;
147
+ if (typeof value === "string" && value.startsWith("{") && value.endsWith("}")) {
148
+ const inner = value.slice(1, -1);
149
+ if (inner === "") return [];
150
+ return parseArrayElements(inner);
151
+ }
152
+ return null;
153
+ }
154
+ function parseArrayElements(input) {
155
+ const result = [];
156
+ let i = 0;
157
+ while (i < input.length) {
158
+ if (input[i] === ",") {
159
+ i++;
160
+ continue;
161
+ }
162
+ if (input[i] === "\"") {
163
+ i++;
164
+ let element = "";
165
+ while (i < input.length && input[i] !== "\"") {
166
+ if (input[i] === "\\" && i + 1 < input.length) {
167
+ i++;
168
+ element += input[i];
169
+ } else element += input[i];
170
+ i++;
171
+ }
172
+ i++;
173
+ result.push(element);
174
+ } else {
175
+ const nextComma = input.indexOf(",", i);
176
+ if (nextComma === -1) {
177
+ result.push(input.slice(i).trim());
178
+ i = input.length;
179
+ } else {
180
+ result.push(input.slice(i, nextComma).trim());
181
+ i = nextComma;
182
+ }
183
+ }
184
+ }
185
+ return result;
186
+ }
187
+ /**
188
+ * Extracts enum values from a StorageTypeInstance.
189
+ * Returns null if values are missing or invalid.
190
+ */
191
+ function getEnumValues(typeInstance) {
192
+ const values = typeInstance.typeParams?.["values"];
193
+ return isStringArray(values) ? values : null;
194
+ }
195
+ /**
196
+ * Reads existing enum values from the schema IR for a given native type.
197
+ * Uses optional chaining to simplify navigation through the annotations structure.
198
+ */
199
+ function readExistingEnumValues(schema, nativeType) {
200
+ const existing = ((schema.annotations?.["pg"])?.["storageTypes"])?.[nativeType];
201
+ if (!existing || existing.codecId !== PG_ENUM_CODEC_ID) return null;
202
+ return getEnumValues(existing);
203
+ }
204
+ /**
205
+ * Determines what changes are needed to transform existing enum values to desired values.
206
+ *
207
+ * Returns one of:
208
+ * - `unchanged`: No changes needed, values match exactly
209
+ * - `add_values`: New values can be safely appended (PostgreSQL supports this)
210
+ * - `rebuild`: Full enum rebuild required (value removal, reordering, or both)
211
+ *
212
+ * Note: PostgreSQL enums can only have values added (not removed or reordered) without
213
+ * a full type rebuild involving temp type creation and column migration.
214
+ *
215
+ * @param existing - Current enum values in the database
216
+ * @param desired - Target enum values from the contract
217
+ * @returns The type of change required
218
+ */
219
+ function determineEnumDiff(existing, desired) {
220
+ if (arraysEqual(existing, desired)) return { kind: "unchanged" };
221
+ const existingSet = new Set(existing);
222
+ const desiredSet = new Set(desired);
223
+ const missingValues = desired.filter((value) => !existingSet.has(value));
224
+ const removedValues = existing.filter((value) => !desiredSet.has(value));
225
+ const orderMismatch = missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);
226
+ if (removedValues.length > 0 || orderMismatch) return {
227
+ kind: "rebuild",
228
+ removedValues
229
+ };
230
+ return {
231
+ kind: "add_values",
232
+ values: missingValues
233
+ };
234
+ }
235
+ function enumTypeExistsCheck(schemaName, typeName, exists = true) {
236
+ return `SELECT ${exists ? "EXISTS" : "NOT EXISTS"} (
237
+ SELECT 1
238
+ FROM pg_type t
239
+ JOIN pg_namespace n ON t.typnamespace = n.oid
240
+ WHERE n.nspname = '${escapeLiteral(schemaName)}'
241
+ AND t.typname = '${escapeLiteral(typeName)}'
242
+ )`;
243
+ }
244
+ function buildCreateEnumOperation(typeName, nativeType, schemaName, values) {
245
+ for (const value of values) validateEnumValueLength(value, typeName);
246
+ const literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(", ");
247
+ const qualifiedType = qualifyName(schemaName, nativeType);
248
+ return {
249
+ id: `type.${typeName}`,
250
+ label: `Create type ${typeName}`,
251
+ summary: `Creates enum type ${typeName}`,
252
+ operationClass: "additive",
253
+ target: { id: "postgres" },
254
+ precheck: [{
255
+ description: `ensure type "${nativeType}" does not exist`,
256
+ sql: enumTypeExistsCheck(schemaName, nativeType, false)
257
+ }],
258
+ execute: [{
259
+ description: `create type "${nativeType}"`,
260
+ sql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`
261
+ }],
262
+ postcheck: [{
263
+ description: `verify type "${nativeType}" exists`,
264
+ sql: enumTypeExistsCheck(schemaName, nativeType)
265
+ }]
266
+ };
267
+ }
268
+ /**
269
+ * Computes the optimal position for inserting a new enum value to maintain
270
+ * the desired order relative to existing values.
271
+ *
272
+ * PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.
273
+ * This function finds the best reference value by:
274
+ * 1. Looking for the nearest preceding value that already exists
275
+ * 2. Falling back to the nearest following value if no preceding exists
276
+ * 3. Defaulting to end-of-list if no reference is found
277
+ *
278
+ * @param options.desired - The target ordered list of all enum values
279
+ * @param options.desiredIndex - Index of the value being inserted in the desired list
280
+ * @param options.current - Current list of enum values (being built up incrementally)
281
+ * @returns SQL clause (e.g., " AFTER 'x'") and insert position for tracking
282
+ */
283
+ function computeInsertPosition(options) {
284
+ const { desired, desiredIndex, current } = options;
285
+ const currentSet = new Set(current);
286
+ const previous = desired.slice(0, desiredIndex).reverse().find((candidate) => currentSet.has(candidate));
287
+ const next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));
288
+ return {
289
+ clause: previous ? ` AFTER '${escapeLiteral(previous)}'` : next ? ` BEFORE '${escapeLiteral(next)}'` : "",
290
+ insertAt: previous ? current.indexOf(previous) + 1 : next ? current.indexOf(next) : current.length
291
+ };
292
+ }
293
+ /**
294
+ * Builds operations to add new enum values to an existing PostgreSQL enum type.
295
+ *
296
+ * Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.
297
+ * Values are inserted in the correct order using BEFORE/AFTER positioning to match
298
+ * the desired final order.
299
+ *
300
+ * This is a safe, non-destructive operation - existing data is not affected.
301
+ *
302
+ * @param options.typeName - Contract-level type name (e.g., 'Role')
303
+ * @param options.nativeType - PostgreSQL type name (e.g., 'role')
304
+ * @param options.schemaName - PostgreSQL schema (e.g., 'public')
305
+ * @param options.desired - Target ordered list of all enum values
306
+ * @param options.existing - Current enum values in the database
307
+ * @returns Array of migration operations to add each missing value
308
+ */
309
+ function buildAddValueOperations(options) {
310
+ const { typeName, nativeType, schemaName } = options;
311
+ const current = [...options.existing];
312
+ const currentSet = new Set(current);
313
+ const operations = [];
314
+ for (let index = 0; index < options.desired.length; index += 1) {
315
+ const value = options.desired[index];
316
+ if (value === void 0) continue;
317
+ if (currentSet.has(value)) continue;
318
+ validateEnumValueLength(value, typeName);
319
+ const { clause, insertAt } = computeInsertPosition({
320
+ desired: options.desired,
321
+ desiredIndex: index,
322
+ current
323
+ });
324
+ operations.push({
325
+ id: `type.${typeName}.value.${value}`,
326
+ label: `Add value ${value} to ${typeName}`,
327
+ summary: `Adds enum value ${value} to ${typeName}`,
328
+ operationClass: "widening",
329
+ target: { id: "postgres" },
330
+ precheck: [],
331
+ execute: [{
332
+ description: `add value "${value}" if not exists`,
333
+ sql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(value)}'${clause}`
334
+ }],
335
+ postcheck: []
336
+ });
337
+ current.splice(insertAt, 0, value);
338
+ currentSet.add(value);
339
+ }
340
+ return operations;
341
+ }
342
+ /**
343
+ * Collects columns using the enum type from the contract (desired state).
344
+ * Used for type-safe reference tracking.
345
+ */
346
+ function collectEnumColumnsFromContract(contract, typeName, nativeType) {
347
+ const columns = [];
348
+ for (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeRef === typeName || column.nativeType === nativeType && column.codecId === PG_ENUM_CODEC_ID) columns.push({
349
+ table: tableName,
350
+ column: columnName
351
+ });
352
+ return columns;
353
+ }
354
+ /**
355
+ * Collects columns using the enum type from the schema IR (live database state).
356
+ * This ensures we find ALL dependent columns, including those added outside the contract
357
+ * (e.g., manual DDL), which is critical for safe enum rebuild operations.
358
+ */
359
+ function collectEnumColumnsFromSchema(schema, nativeType) {
360
+ const columns = [];
361
+ for (const [tableName, table] of Object.entries(schema.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.nativeType === nativeType) columns.push({
362
+ table: tableName,
363
+ column: columnName
364
+ });
365
+ return columns;
366
+ }
367
+ /**
368
+ * Collects all columns using the enum type from both contract AND live database.
369
+ * Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.
370
+ *
371
+ * This is critical for data integrity: if a column exists in the database using
372
+ * this enum but is not in the contract (e.g., added via manual DDL), we must
373
+ * still migrate it to avoid DROP TYPE failures.
374
+ */
375
+ function collectAllEnumColumns(contract, schema, typeName, nativeType) {
376
+ const contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);
377
+ const schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);
378
+ const seen = /* @__PURE__ */ new Set();
379
+ const result = [];
380
+ for (const col of [...contractColumns, ...schemaColumns]) {
381
+ const key = `${col.table}.${col.column}`;
382
+ if (!seen.has(key)) {
383
+ seen.add(key);
384
+ result.push(col);
385
+ }
386
+ }
387
+ return result.sort((a, b) => {
388
+ const tableCompare = a.table.localeCompare(b.table);
389
+ return tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);
390
+ });
391
+ }
392
+ /**
393
+ * Builds a SQL check to verify a column's type matches an expected type.
394
+ */
395
+ function columnTypeCheck(options) {
396
+ return `SELECT EXISTS (
397
+ SELECT 1
398
+ FROM information_schema.columns
399
+ WHERE table_schema = '${escapeLiteral(options.schemaName)}'
400
+ AND table_name = '${escapeLiteral(options.tableName)}'
401
+ AND column_name = '${escapeLiteral(options.columnName)}'
402
+ AND udt_name = '${escapeLiteral(options.expectedType)}'
403
+ )`;
404
+ }
405
+ /** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */
406
+ const MAX_IDENTIFIER_LENGTH = 63;
407
+ /** Suffix added to enum type names during rebuild operations */
408
+ const REBUILD_SUFFIX = "__pn_rebuild";
409
+ /**
410
+ * Builds an SQL check to verify no rows contain any of the removed enum values.
411
+ * This prevents data loss during enum rebuild operations.
412
+ *
413
+ * @param schemaName - PostgreSQL schema name
414
+ * @param tableName - Table containing the enum column
415
+ * @param columnName - Column using the enum type
416
+ * @param removedValues - Array of enum values being removed
417
+ * @returns SQL query that returns true if no rows contain removed values
418
+ */
419
+ function noRemovedValuesExistCheck(schemaName, tableName, columnName, removedValues) {
420
+ if (removedValues.length === 0) return "SELECT true";
421
+ const valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(", ");
422
+ return `SELECT NOT EXISTS (
423
+ SELECT 1 FROM ${qualifyName(schemaName, tableName)}
424
+ WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})
425
+ LIMIT 1
426
+ )`;
427
+ }
428
+ /**
429
+ * Builds a migration operation to recreate a PostgreSQL enum type with updated values.
430
+ *
431
+ * This is required when:
432
+ * - Enum values are removed (PostgreSQL doesn't support direct removal)
433
+ * - Enum values are reordered (PostgreSQL doesn't support reordering)
434
+ *
435
+ * The operation:
436
+ * 1. Creates a new enum type with the desired values (temp name)
437
+ * 2. Migrates all columns to use the new type via text cast
438
+ * 3. Drops the original type
439
+ * 4. Renames the temp type to the original name
440
+ *
441
+ * IMPORTANT: If values are being removed and data exists using those values,
442
+ * the operation will fail at the precheck stage with a clear error message.
443
+ * This prevents silent data loss.
444
+ *
445
+ * @param options.typeName - Contract-level type name
446
+ * @param options.nativeType - PostgreSQL type name
447
+ * @param options.schemaName - PostgreSQL schema
448
+ * @param options.values - Desired final enum values
449
+ * @param options.removedValues - Values being removed (for data loss checks)
450
+ * @param options.contract - Full contract for column discovery
451
+ * @param options.schema - Current schema IR for column discovery
452
+ * @returns Migration operation for full enum rebuild
453
+ */
454
+ function buildRecreateEnumOperation(options) {
455
+ const tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;
456
+ if (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {
457
+ const maxBaseLength = MAX_IDENTIFIER_LENGTH - 12;
458
+ throw new Error(`Enum type name "${options.nativeType}" is too long for rebuild operation. Maximum length is ${maxBaseLength} characters (type name + "${REBUILD_SUFFIX}" suffix must fit within PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character identifier limit).`);
459
+ }
460
+ const qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);
461
+ const qualifiedTemp = qualifyName(options.schemaName, tempTypeName);
462
+ const literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(", ");
463
+ const columnRefs = collectAllEnumColumns(options.contract, options.schema, options.typeName, options.nativeType);
464
+ const alterColumns = columnRefs.map((ref) => ({
465
+ description: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,
466
+ sql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}
467
+ ALTER COLUMN ${quoteIdentifier(ref.column)}
468
+ TYPE ${qualifiedTemp}
469
+ USING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`
470
+ }));
471
+ const postchecks = [
472
+ {
473
+ description: `verify type "${options.nativeType}" exists`,
474
+ sql: enumTypeExistsCheck(options.schemaName, options.nativeType)
475
+ },
476
+ {
477
+ description: `verify temp type "${tempTypeName}" was removed`,
478
+ sql: enumTypeExistsCheck(options.schemaName, tempTypeName, false)
479
+ },
480
+ ...columnRefs.map((ref) => ({
481
+ description: `verify ${ref.table}.${ref.column} uses type "${options.nativeType}"`,
482
+ sql: columnTypeCheck({
483
+ schemaName: options.schemaName,
484
+ tableName: ref.table,
485
+ columnName: ref.column,
486
+ expectedType: options.nativeType
487
+ })
488
+ }))
489
+ ];
490
+ return {
491
+ id: `type.${options.typeName}.rebuild`,
492
+ label: `Rebuild type ${options.typeName}`,
493
+ summary: `Recreates enum type ${options.typeName} with updated values`,
494
+ operationClass: "destructive",
495
+ target: { id: "postgres" },
496
+ precheck: [{
497
+ description: `ensure type "${options.nativeType}" exists`,
498
+ sql: enumTypeExistsCheck(options.schemaName, options.nativeType)
499
+ }, ...options.removedValues.length > 0 ? columnRefs.map((ref) => ({
500
+ description: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(", ")})`,
501
+ sql: noRemovedValuesExistCheck(options.schemaName, ref.table, ref.column, options.removedValues)
502
+ })) : []],
503
+ execute: [
504
+ {
505
+ description: `drop orphaned temp type "${tempTypeName}" if exists`,
506
+ sql: `DROP TYPE IF EXISTS ${qualifiedTemp}`
507
+ },
508
+ {
509
+ description: `create temp type "${tempTypeName}"`,
510
+ sql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`
511
+ },
512
+ ...alterColumns,
513
+ {
514
+ description: `drop type "${options.nativeType}"`,
515
+ sql: `DROP TYPE ${qualifiedOriginal}`
516
+ },
517
+ {
518
+ description: `rename type "${tempTypeName}" to "${options.nativeType}"`,
519
+ sql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`
520
+ }
521
+ ],
522
+ postcheck: postchecks
523
+ };
524
+ }
525
+ /**
526
+ * Postgres enum hooks for planning, verifying, and introspecting `storage.types`.
527
+ */
528
+ const pgEnumControlHooks = {
529
+ planTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {
530
+ const desired = getEnumValues(typeInstance);
531
+ if (!desired || desired.length === 0) return { operations: [] };
532
+ const schemaNamespace = schemaName ?? "public";
533
+ const existing = readExistingEnumValues(schema, typeInstance.nativeType);
534
+ if (!existing) return { operations: [buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired)] };
535
+ const diff = determineEnumDiff(existing, desired);
536
+ if (diff.kind === "unchanged") return { operations: [] };
537
+ if (diff.kind === "rebuild") return { operations: [buildRecreateEnumOperation({
538
+ typeName,
539
+ nativeType: typeInstance.nativeType,
540
+ schemaName: schemaNamespace,
541
+ values: desired,
542
+ removedValues: diff.removedValues,
543
+ contract,
544
+ schema
545
+ })] };
546
+ return { operations: buildAddValueOperations({
547
+ typeName,
548
+ nativeType: typeInstance.nativeType,
549
+ schemaName: schemaNamespace,
550
+ desired,
551
+ existing
552
+ }) };
553
+ },
554
+ verifyType: ({ typeName, typeInstance, schema }) => {
555
+ const desired = getEnumValues(typeInstance);
556
+ if (!desired) return [];
557
+ const existing = readExistingEnumValues(schema, typeInstance.nativeType);
558
+ if (!existing) return [{
559
+ kind: "type_missing",
560
+ table: "",
561
+ typeName,
562
+ message: `Type "${typeName}" is missing from database`
563
+ }];
564
+ if (!arraysEqual(existing, desired)) return [{
565
+ kind: "type_values_mismatch",
566
+ table: "",
567
+ typeName,
568
+ expected: desired.join(", "),
569
+ actual: existing.join(", "),
570
+ message: `Type "${typeName}" values do not match contract`
571
+ }];
572
+ return [];
573
+ },
574
+ introspectTypes: async ({ driver, schemaName }) => {
575
+ const namespace = schemaName ?? "public";
576
+ const result = await driver.query(ENUM_INTROSPECT_QUERY, [namespace]);
577
+ const types = {};
578
+ for (const row of result.rows) {
579
+ const values = parsePostgresArray(row.values);
580
+ if (!values) throw new Error(`Failed to parse enum values for type "${row.type_name}": unexpected format: ${JSON.stringify(row.values)}`);
581
+ types[row.type_name] = {
582
+ codecId: PG_ENUM_CODEC_ID,
583
+ nativeType: row.type_name,
584
+ typeParams: { values }
585
+ };
586
+ }
587
+ return types;
588
+ }
589
+ };
590
+ const MAX_DEPTH = 32;
591
+ function isRecord(value) {
592
+ return typeof value === "object" && value !== null;
593
+ }
594
+ function escapeStringLiteral(str) {
595
+ return str.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
596
+ }
597
+ function quotePropertyKey(key) {
598
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;
599
+ }
600
+ function renderLiteral(value) {
601
+ if (typeof value === "string") return `'${escapeStringLiteral(value)}'`;
602
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
603
+ if (value === null) return "null";
604
+ return "unknown";
605
+ }
606
+ function renderUnion(items, depth) {
607
+ return items.map((item) => render(item, depth)).join(" | ");
608
+ }
609
+ function renderObjectType(schema, depth) {
610
+ const properties = isRecord(schema["properties"]) ? schema["properties"] : {};
611
+ const required = Array.isArray(schema["required"]) ? new Set(schema["required"].filter((key) => typeof key === "string")) : /* @__PURE__ */ new Set();
612
+ const keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));
613
+ if (keys.length === 0) {
614
+ const additionalProperties = schema["additionalProperties"];
615
+ if (additionalProperties === true || additionalProperties === void 0) return "Record<string, unknown>";
616
+ return `Record<string, ${render(additionalProperties, depth)}>`;
617
+ }
618
+ return `{ ${keys.map((key) => {
619
+ const valueSchema = properties[key];
620
+ const optionalMarker = required.has(key) ? "" : "?";
621
+ return `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;
622
+ }).join("; ")} }`;
623
+ }
624
+ function renderArrayType(schema, depth) {
625
+ if (Array.isArray(schema["items"])) return `readonly [${schema["items"].map((item) => render(item, depth)).join(", ")}]`;
626
+ if (schema["items"] !== void 0) {
627
+ const itemType = render(schema["items"], depth);
628
+ return itemType.includes(" | ") || itemType.includes(" & ") ? `(${itemType})[]` : `${itemType}[]`;
629
+ }
630
+ return "unknown[]";
631
+ }
632
+ function render(schema, depth) {
633
+ if (depth > MAX_DEPTH || !isRecord(schema)) return "JsonValue";
634
+ const nextDepth = depth + 1;
635
+ if ("const" in schema) return renderLiteral(schema["const"]);
636
+ if (Array.isArray(schema["enum"])) return schema["enum"].map((value) => renderLiteral(value)).join(" | ");
637
+ if (Array.isArray(schema["oneOf"])) return renderUnion(schema["oneOf"], nextDepth);
638
+ if (Array.isArray(schema["anyOf"])) return renderUnion(schema["anyOf"], nextDepth);
639
+ if (Array.isArray(schema["allOf"])) return schema["allOf"].map((item) => render(item, nextDepth)).join(" & ");
640
+ if (Array.isArray(schema["type"])) return schema["type"].map((item) => render({
641
+ ...schema,
642
+ type: item
643
+ }, nextDepth)).join(" | ");
644
+ switch (schema["type"]) {
645
+ case "string": return "string";
646
+ case "number":
647
+ case "integer": return "number";
648
+ case "boolean": return "boolean";
649
+ case "null": return "null";
650
+ case "array": return renderArrayType(schema, nextDepth);
651
+ case "object": return renderObjectType(schema, nextDepth);
652
+ default: break;
653
+ }
654
+ return "JsonValue";
655
+ }
656
+ function renderTypeScriptTypeFromJsonSchema(schema) {
657
+ return render(schema, 0);
658
+ }
659
+ /**
660
+ * Shared utility for expanding parameterized Postgres types to their full SQL representation.
661
+ *
662
+ * This module provides a single source of truth for type expansion logic, used by:
663
+ * - Schema verification (verify-sql-schema.ts) via the expandNativeType codec control hook
664
+ * - Migration planner (planner.ts) via direct import
665
+ *
666
+ * @module
667
+ */
668
+ /** Set of codec IDs that use the 'length' parameter */
669
+ const LENGTH_CODEC_IDS = new Set([
670
+ SQL_CHAR_CODEC_ID,
671
+ SQL_VARCHAR_CODEC_ID,
672
+ PG_CHAR_CODEC_ID,
673
+ PG_VARCHAR_CODEC_ID,
674
+ PG_BIT_CODEC_ID,
675
+ PG_VARBIT_CODEC_ID
676
+ ]);
677
+ /** Set of codec IDs that use the 'precision' parameter for temporal types */
678
+ const TEMPORAL_PRECISION_CODEC_IDS = new Set([
679
+ PG_TIMESTAMP_CODEC_ID,
680
+ PG_TIMESTAMPTZ_CODEC_ID,
681
+ PG_TIME_CODEC_ID,
682
+ PG_TIMETZ_CODEC_ID,
683
+ PG_INTERVAL_CODEC_ID
684
+ ]);
685
+ /**
686
+ * Validates that a value is a valid type parameter number.
687
+ * Type parameters must be finite, non-negative integers.
688
+ */
689
+ function isValidTypeParamNumber(value) {
690
+ return typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;
691
+ }
692
+ /**
693
+ * Expands a parameterized native type to its full SQL representation.
694
+ *
695
+ * For example:
696
+ * - { nativeType: 'character varying', typeParams: { length: 255 } } -> 'character varying(255)'
697
+ * - { nativeType: 'numeric', typeParams: { precision: 10, scale: 2 } } -> 'numeric(10,2)'
698
+ * - { nativeType: 'timestamp without time zone', typeParams: { precision: 3 } } -> 'timestamp without time zone(3)'
699
+ *
700
+ * Returns the original nativeType if:
701
+ * - No typeParams are provided
702
+ * - No codecId is provided
703
+ * - The codecId is not a known parameterized type
704
+ * - The typeParams values are invalid
705
+ */
706
+ function expandParameterizedNativeType(input) {
707
+ const { nativeType, codecId, typeParams } = input;
708
+ if (!typeParams || !codecId) return nativeType;
709
+ if (LENGTH_CODEC_IDS.has(codecId)) {
710
+ const length = typeParams["length"];
711
+ if (isValidTypeParamNumber(length)) return `${nativeType}(${length})`;
712
+ return nativeType;
713
+ }
714
+ if (codecId === PG_NUMERIC_CODEC_ID) {
715
+ const precision = typeParams["precision"];
716
+ const scale = typeParams["scale"];
717
+ if (isValidTypeParamNumber(precision)) {
718
+ if (isValidTypeParamNumber(scale)) return `${nativeType}(${precision},${scale})`;
719
+ return `${nativeType}(${precision})`;
720
+ }
721
+ return nativeType;
722
+ }
723
+ if (TEMPORAL_PRECISION_CODEC_IDS.has(codecId)) {
724
+ const precision = typeParams["precision"];
725
+ if (isValidTypeParamNumber(precision)) return `${nativeType}(${precision})`;
726
+ return nativeType;
727
+ }
728
+ return nativeType;
729
+ }
730
+ /** Creates a type import spec for codec types */
731
+ const codecTypeImport = (named) => ({
732
+ package: "@prisma-next/adapter-postgres/codec-types",
733
+ named,
734
+ alias: named
735
+ });
736
+ /** Creates a precision-based TypeScript type renderer for temporal types */
737
+ const precisionRenderer = (typeName) => ({
738
+ kind: "function",
739
+ render: (params) => {
740
+ const precision = params["precision"];
741
+ return typeof precision === "number" ? `${typeName}<${precision}>` : typeName;
742
+ }
743
+ });
744
+ /** Creates control hooks with just expandNativeType for parameterized types */
745
+ const parameterizedTypeHooks = { expandNativeType: expandParameterizedNativeType };
746
+ /**
747
+ * Validates that a type expression string is safe to embed in generated .d.ts files.
748
+ * Rejects expressions containing patterns that could inject executable code.
749
+ */
750
+ function isSafeTypeExpression(expr) {
751
+ return !/import\s*\(|require\s*\(|declare\s|export\s|eval\s*\(/.test(expr);
752
+ }
753
+ function renderJsonTypeExpression(params) {
754
+ const typeName = params["type"];
755
+ if (typeof typeName === "string" && typeName.trim().length > 0) {
756
+ const trimmed = typeName.trim();
757
+ if (!isSafeTypeExpression(trimmed)) return "JsonValue";
758
+ return trimmed;
759
+ }
760
+ const schema = params["schemaJson"];
761
+ if (schema && typeof schema === "object") {
762
+ const rendered = renderTypeScriptTypeFromJsonSchema(schema);
763
+ if (!isSafeTypeExpression(rendered)) return "JsonValue";
764
+ return rendered;
765
+ }
766
+ return "JsonValue";
767
+ }
768
+ const postgresAdapterDescriptorMeta = {
769
+ kind: "adapter",
770
+ familyId: "sql",
771
+ targetId: "postgres",
772
+ id: "postgres",
773
+ version: "0.0.1",
774
+ capabilities: {
775
+ postgres: {
776
+ orderBy: true,
777
+ limit: true,
778
+ lateral: true,
779
+ jsonAgg: true,
780
+ returning: true
781
+ },
782
+ sql: { enums: true }
783
+ },
784
+ types: {
785
+ codecTypes: {
786
+ import: {
787
+ package: "@prisma-next/adapter-postgres/codec-types",
788
+ named: "CodecTypes",
789
+ alias: "PgTypes"
790
+ },
791
+ parameterized: {
792
+ [SQL_CHAR_CODEC_ID]: "Char<{{length}}>",
793
+ [SQL_VARCHAR_CODEC_ID]: "Varchar<{{length}}>",
794
+ [PG_CHAR_CODEC_ID]: "Char<{{length}}>",
795
+ [PG_VARCHAR_CODEC_ID]: "Varchar<{{length}}>",
796
+ [PG_NUMERIC_CODEC_ID]: {
797
+ kind: "function",
798
+ render: (params) => {
799
+ const precision = params["precision"];
800
+ if (typeof precision !== "number") throw new Error("pg/numeric@1 renderer expects precision");
801
+ const scale = params["scale"];
802
+ return typeof scale === "number" ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;
803
+ }
804
+ },
805
+ [PG_BIT_CODEC_ID]: "Bit<{{length}}>",
806
+ [PG_VARBIT_CODEC_ID]: "VarBit<{{length}}>",
807
+ [PG_TIMESTAMP_CODEC_ID]: precisionRenderer("Timestamp"),
808
+ [PG_TIMESTAMPTZ_CODEC_ID]: precisionRenderer("Timestamptz"),
809
+ [PG_TIME_CODEC_ID]: precisionRenderer("Time"),
810
+ [PG_TIMETZ_CODEC_ID]: precisionRenderer("Timetz"),
811
+ [PG_INTERVAL_CODEC_ID]: precisionRenderer("Interval"),
812
+ [PG_ENUM_CODEC_ID]: {
813
+ kind: "function",
814
+ render: (params) => {
815
+ const values = params["values"];
816
+ if (!Array.isArray(values)) throw new Error("pg/enum@1 renderer expects values array");
817
+ return values.map((value) => `'${String(value).replace(/'/g, "\\'")}'`).join(" | ");
818
+ }
819
+ },
820
+ [PG_JSON_CODEC_ID]: {
821
+ kind: "function",
822
+ render: renderJsonTypeExpression
823
+ },
824
+ [PG_JSONB_CODEC_ID]: {
825
+ kind: "function",
826
+ render: renderJsonTypeExpression
827
+ }
828
+ },
829
+ typeImports: [
830
+ {
831
+ package: "@prisma-next/adapter-postgres/codec-types",
832
+ named: "JsonValue",
833
+ alias: "JsonValue"
834
+ },
835
+ codecTypeImport("Char"),
836
+ codecTypeImport("Varchar"),
837
+ codecTypeImport("Numeric"),
838
+ codecTypeImport("Bit"),
839
+ codecTypeImport("VarBit"),
840
+ codecTypeImport("Timestamp"),
841
+ codecTypeImport("Timestamptz"),
842
+ codecTypeImport("Time"),
843
+ codecTypeImport("Timetz"),
844
+ codecTypeImport("Interval")
845
+ ],
846
+ controlPlaneHooks: {
847
+ [SQL_CHAR_CODEC_ID]: parameterizedTypeHooks,
848
+ [SQL_VARCHAR_CODEC_ID]: parameterizedTypeHooks,
849
+ [PG_CHAR_CODEC_ID]: parameterizedTypeHooks,
850
+ [PG_VARCHAR_CODEC_ID]: parameterizedTypeHooks,
851
+ [PG_NUMERIC_CODEC_ID]: parameterizedTypeHooks,
852
+ [PG_BIT_CODEC_ID]: parameterizedTypeHooks,
853
+ [PG_VARBIT_CODEC_ID]: parameterizedTypeHooks,
854
+ [PG_TIMESTAMP_CODEC_ID]: parameterizedTypeHooks,
855
+ [PG_TIMESTAMPTZ_CODEC_ID]: parameterizedTypeHooks,
856
+ [PG_TIME_CODEC_ID]: parameterizedTypeHooks,
857
+ [PG_TIMETZ_CODEC_ID]: parameterizedTypeHooks,
858
+ [PG_INTERVAL_CODEC_ID]: parameterizedTypeHooks,
859
+ [PG_ENUM_CODEC_ID]: pgEnumControlHooks
860
+ }
861
+ },
862
+ storage: [
863
+ {
864
+ typeId: PG_TEXT_CODEC_ID,
865
+ familyId: "sql",
866
+ targetId: "postgres",
867
+ nativeType: "text"
868
+ },
869
+ {
870
+ typeId: SQL_CHAR_CODEC_ID,
871
+ familyId: "sql",
872
+ targetId: "postgres",
873
+ nativeType: "character"
874
+ },
875
+ {
876
+ typeId: SQL_VARCHAR_CODEC_ID,
877
+ familyId: "sql",
878
+ targetId: "postgres",
879
+ nativeType: "character varying"
880
+ },
881
+ {
882
+ typeId: SQL_INT_CODEC_ID,
883
+ familyId: "sql",
884
+ targetId: "postgres",
885
+ nativeType: "int4"
886
+ },
887
+ {
888
+ typeId: SQL_FLOAT_CODEC_ID,
889
+ familyId: "sql",
890
+ targetId: "postgres",
891
+ nativeType: "float8"
892
+ },
893
+ {
894
+ typeId: PG_CHAR_CODEC_ID,
895
+ familyId: "sql",
896
+ targetId: "postgres",
897
+ nativeType: "character"
898
+ },
899
+ {
900
+ typeId: PG_VARCHAR_CODEC_ID,
901
+ familyId: "sql",
902
+ targetId: "postgres",
903
+ nativeType: "character varying"
904
+ },
905
+ {
906
+ typeId: PG_INT_CODEC_ID,
907
+ familyId: "sql",
908
+ targetId: "postgres",
909
+ nativeType: "int4"
910
+ },
911
+ {
912
+ typeId: PG_FLOAT_CODEC_ID,
913
+ familyId: "sql",
914
+ targetId: "postgres",
915
+ nativeType: "float8"
916
+ },
917
+ {
918
+ typeId: PG_INT4_CODEC_ID,
919
+ familyId: "sql",
920
+ targetId: "postgres",
921
+ nativeType: "int4"
922
+ },
923
+ {
924
+ typeId: PG_INT2_CODEC_ID,
925
+ familyId: "sql",
926
+ targetId: "postgres",
927
+ nativeType: "int2"
928
+ },
929
+ {
930
+ typeId: PG_INT8_CODEC_ID,
931
+ familyId: "sql",
932
+ targetId: "postgres",
933
+ nativeType: "int8"
934
+ },
935
+ {
936
+ typeId: PG_FLOAT4_CODEC_ID,
937
+ familyId: "sql",
938
+ targetId: "postgres",
939
+ nativeType: "float4"
940
+ },
941
+ {
942
+ typeId: PG_FLOAT8_CODEC_ID,
943
+ familyId: "sql",
944
+ targetId: "postgres",
945
+ nativeType: "float8"
946
+ },
947
+ {
948
+ typeId: PG_NUMERIC_CODEC_ID,
949
+ familyId: "sql",
950
+ targetId: "postgres",
951
+ nativeType: "numeric"
952
+ },
953
+ {
954
+ typeId: PG_TIMESTAMP_CODEC_ID,
955
+ familyId: "sql",
956
+ targetId: "postgres",
957
+ nativeType: "timestamp"
958
+ },
959
+ {
960
+ typeId: PG_TIMESTAMPTZ_CODEC_ID,
961
+ familyId: "sql",
962
+ targetId: "postgres",
963
+ nativeType: "timestamptz"
964
+ },
965
+ {
966
+ typeId: PG_TIME_CODEC_ID,
967
+ familyId: "sql",
968
+ targetId: "postgres",
969
+ nativeType: "time"
970
+ },
971
+ {
972
+ typeId: PG_TIMETZ_CODEC_ID,
973
+ familyId: "sql",
974
+ targetId: "postgres",
975
+ nativeType: "timetz"
976
+ },
977
+ {
978
+ typeId: PG_BOOL_CODEC_ID,
979
+ familyId: "sql",
980
+ targetId: "postgres",
981
+ nativeType: "bool"
982
+ },
983
+ {
984
+ typeId: PG_BIT_CODEC_ID,
985
+ familyId: "sql",
986
+ targetId: "postgres",
987
+ nativeType: "bit"
988
+ },
989
+ {
990
+ typeId: PG_VARBIT_CODEC_ID,
991
+ familyId: "sql",
992
+ targetId: "postgres",
993
+ nativeType: "bit varying"
994
+ },
995
+ {
996
+ typeId: PG_INTERVAL_CODEC_ID,
997
+ familyId: "sql",
998
+ targetId: "postgres",
999
+ nativeType: "interval"
1000
+ },
1001
+ {
1002
+ typeId: PG_JSON_CODEC_ID,
1003
+ familyId: "sql",
1004
+ targetId: "postgres",
1005
+ nativeType: "json"
1006
+ },
1007
+ {
1008
+ typeId: PG_JSONB_CODEC_ID,
1009
+ familyId: "sql",
1010
+ targetId: "postgres",
1011
+ nativeType: "jsonb"
1012
+ }
1013
+ ]
1014
+ }
1015
+ };
1016
+
1017
+ //#endregion
1018
+ //#region ../../6-adapters/postgres/dist/control.mjs
1019
+ /**
1020
+ * Pre-compiled regex patterns for performance.
1021
+ * These are compiled once at module load time rather than on each function call.
1022
+ */
1023
+ const NEXTVAL_PATTERN = /^nextval\s*\(/i;
1024
+ const TIMESTAMP_PATTERN = /^(now\s*\(\s*\)|CURRENT_TIMESTAMP|clock_timestamp\s*\(\s*\))$/i;
1025
+ const UUID_PATTERN = /^gen_random_uuid\s*\(\s*\)$/i;
1026
+ const UUID_OSSP_PATTERN = /^uuid_generate_v4\s*\(\s*\)$/i;
1027
+ const TRUE_PATTERN = /^true$/i;
1028
+ const FALSE_PATTERN = /^false$/i;
1029
+ const NUMERIC_PATTERN = /^-?\d+(\.\d+)?$/;
1030
+ const STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:"[^"]+"|[\w\s]+)(?:\(\d+\))?)?$/;
1031
+ /**
1032
+ * Parses a raw Postgres column default expression into a normalized ColumnDefault.
1033
+ * This enables semantic comparison between contract defaults and introspected schema defaults.
1034
+ *
1035
+ * Used by the migration diff layer to normalize raw database defaults during comparison,
1036
+ * keeping the introspection layer focused on faithful data capture.
1037
+ *
1038
+ * @param rawDefault - Raw default expression from information_schema.columns.column_default
1039
+ * @param _nativeType - Native column type (currently unused, reserved for future type-aware parsing)
1040
+ * @returns Normalized ColumnDefault or undefined if the expression cannot be parsed
1041
+ */
1042
+ function parsePostgresDefault(rawDefault, _nativeType) {
1043
+ const trimmed = rawDefault.trim();
1044
+ const normalizedType = _nativeType?.toLowerCase();
1045
+ const isBigInt = normalizedType === "bigint" || normalizedType === "int8";
1046
+ if (NEXTVAL_PATTERN.test(trimmed)) return {
1047
+ kind: "function",
1048
+ expression: "autoincrement()"
1049
+ };
1050
+ if (TIMESTAMP_PATTERN.test(trimmed)) return {
1051
+ kind: "function",
1052
+ expression: "now()"
1053
+ };
1054
+ if (UUID_PATTERN.test(trimmed)) return {
1055
+ kind: "function",
1056
+ expression: "gen_random_uuid()"
1057
+ };
1058
+ if (UUID_OSSP_PATTERN.test(trimmed)) return {
1059
+ kind: "function",
1060
+ expression: "gen_random_uuid()"
1061
+ };
1062
+ if (TRUE_PATTERN.test(trimmed)) return {
1063
+ kind: "literal",
1064
+ value: true
1065
+ };
1066
+ if (FALSE_PATTERN.test(trimmed)) return {
1067
+ kind: "literal",
1068
+ value: false
1069
+ };
1070
+ if (NUMERIC_PATTERN.test(trimmed)) {
1071
+ if (isBigInt) return {
1072
+ kind: "literal",
1073
+ value: {
1074
+ $type: "bigint",
1075
+ value: trimmed
1076
+ }
1077
+ };
1078
+ return {
1079
+ kind: "literal",
1080
+ value: Number(trimmed)
1081
+ };
1082
+ }
1083
+ const stringMatch = trimmed.match(STRING_LITERAL_PATTERN);
1084
+ if (stringMatch?.[1] !== void 0) {
1085
+ const unescaped = stringMatch[1].replace(/''/g, "'");
1086
+ if (normalizedType === "json" || normalizedType === "jsonb") try {
1087
+ return {
1088
+ kind: "literal",
1089
+ value: JSON.parse(unescaped)
1090
+ };
1091
+ } catch {}
1092
+ return {
1093
+ kind: "literal",
1094
+ value: unescaped
1095
+ };
1096
+ }
1097
+ return {
1098
+ kind: "function",
1099
+ expression: trimmed
1100
+ };
1101
+ }
1102
+ /**
1103
+ * Postgres control plane adapter for control-plane operations like introspection.
1104
+ * Provides target-specific implementations for control-plane domain actions.
1105
+ */
1106
+ var PostgresControlAdapter = class {
1107
+ familyId = "sql";
1108
+ targetId = "postgres";
1109
+ /**
1110
+ * @deprecated Use targetId instead
1111
+ */
1112
+ target = "postgres";
1113
+ /**
1114
+ * Target-specific normalizer for raw Postgres default expressions.
1115
+ * Used by schema verification to normalize raw defaults before comparison.
1116
+ */
1117
+ normalizeDefault = parsePostgresDefault;
1118
+ /**
1119
+ * Target-specific normalizer for Postgres schema native type names.
1120
+ * Used by schema verification to normalize introspected type names
1121
+ * before comparison with contract native types.
1122
+ */
1123
+ normalizeNativeType = normalizeSchemaNativeType;
1124
+ /**
1125
+ * Introspects a Postgres database schema and returns a raw SqlSchemaIR.
1126
+ *
1127
+ * This is a pure schema discovery operation that queries the Postgres catalog
1128
+ * and returns the schema structure without type mapping or contract enrichment.
1129
+ * Type mapping and enrichment are handled separately by enrichment helpers.
1130
+ *
1131
+ * Uses batched queries to minimize database round trips (7 queries instead of 5T+3).
1132
+ *
1133
+ * @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries
1134
+ * @param contractIR - Optional contract IR for contract-guided introspection (filtering, optimization)
1135
+ * @param schema - Schema name to introspect (defaults to 'public')
1136
+ * @returns Promise resolving to SqlSchemaIR representing the live database schema
1137
+ */
1138
+ async introspect(driver, _contractIR, schema = "public") {
1139
+ const [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult, extensionsResult] = await Promise.all([
1140
+ driver.query(`SELECT table_name
1141
+ FROM information_schema.tables
1142
+ WHERE table_schema = $1
1143
+ AND table_type = 'BASE TABLE'
1144
+ ORDER BY table_name`, [schema]),
1145
+ driver.query(`SELECT
1146
+ c.table_name,
1147
+ column_name,
1148
+ data_type,
1149
+ udt_name,
1150
+ is_nullable,
1151
+ character_maximum_length,
1152
+ numeric_precision,
1153
+ numeric_scale,
1154
+ column_default,
1155
+ format_type(a.atttypid, a.atttypmod) AS formatted_type
1156
+ FROM information_schema.columns c
1157
+ JOIN pg_catalog.pg_class cl
1158
+ ON cl.relname = c.table_name
1159
+ JOIN pg_catalog.pg_namespace ns
1160
+ ON ns.nspname = c.table_schema
1161
+ AND ns.oid = cl.relnamespace
1162
+ JOIN pg_catalog.pg_attribute a
1163
+ ON a.attrelid = cl.oid
1164
+ AND a.attname = c.column_name
1165
+ AND a.attnum > 0
1166
+ AND NOT a.attisdropped
1167
+ WHERE c.table_schema = $1
1168
+ ORDER BY c.table_name, c.ordinal_position`, [schema]),
1169
+ driver.query(`SELECT
1170
+ tc.table_name,
1171
+ tc.constraint_name,
1172
+ kcu.column_name,
1173
+ kcu.ordinal_position
1174
+ FROM information_schema.table_constraints tc
1175
+ JOIN information_schema.key_column_usage kcu
1176
+ ON tc.constraint_name = kcu.constraint_name
1177
+ AND tc.table_schema = kcu.table_schema
1178
+ AND tc.table_name = kcu.table_name
1179
+ WHERE tc.table_schema = $1
1180
+ AND tc.constraint_type = 'PRIMARY KEY'
1181
+ ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),
1182
+ driver.query(`SELECT
1183
+ tc.table_name,
1184
+ tc.constraint_name,
1185
+ kcu.column_name,
1186
+ kcu.ordinal_position,
1187
+ ref_ns.nspname AS referenced_table_schema,
1188
+ ref_cl.relname AS referenced_table_name,
1189
+ ref_att.attname AS referenced_column_name,
1190
+ rc.delete_rule,
1191
+ rc.update_rule
1192
+ FROM information_schema.table_constraints tc
1193
+ JOIN information_schema.key_column_usage kcu
1194
+ ON tc.constraint_name = kcu.constraint_name
1195
+ AND tc.table_schema = kcu.table_schema
1196
+ AND tc.table_name = kcu.table_name
1197
+ JOIN pg_catalog.pg_constraint pgc
1198
+ ON pgc.conname = tc.constraint_name
1199
+ AND pgc.connamespace = (
1200
+ SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema
1201
+ )
1202
+ JOIN pg_catalog.pg_class ref_cl
1203
+ ON ref_cl.oid = pgc.confrelid
1204
+ JOIN pg_catalog.pg_namespace ref_ns
1205
+ ON ref_ns.oid = ref_cl.relnamespace
1206
+ JOIN pg_catalog.pg_attribute ref_att
1207
+ ON ref_att.attrelid = pgc.confrelid
1208
+ AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]
1209
+ JOIN information_schema.referential_constraints rc
1210
+ ON rc.constraint_name = tc.constraint_name
1211
+ AND rc.constraint_schema = tc.table_schema
1212
+ WHERE tc.table_schema = $1
1213
+ AND tc.constraint_type = 'FOREIGN KEY'
1214
+ ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
1215
+ driver.query(`SELECT
1216
+ tc.table_name,
1217
+ tc.constraint_name,
1218
+ kcu.column_name,
1219
+ kcu.ordinal_position
1220
+ FROM information_schema.table_constraints tc
1221
+ JOIN information_schema.key_column_usage kcu
1222
+ ON tc.constraint_name = kcu.constraint_name
1223
+ AND tc.table_schema = kcu.table_schema
1224
+ AND tc.table_name = kcu.table_name
1225
+ WHERE tc.table_schema = $1
1226
+ AND tc.constraint_type = 'UNIQUE'
1227
+ ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
1228
+ driver.query(`SELECT
1229
+ i.tablename,
1230
+ i.indexname,
1231
+ ix.indisunique,
1232
+ a.attname,
1233
+ a.attnum
1234
+ FROM pg_indexes i
1235
+ JOIN pg_class ic ON ic.relname = i.indexname
1236
+ JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1
1237
+ JOIN pg_index ix ON ix.indexrelid = ic.oid
1238
+ JOIN pg_class t ON t.oid = ix.indrelid
1239
+ JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1
1240
+ LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0
1241
+ WHERE i.schemaname = $1
1242
+ AND NOT EXISTS (
1243
+ SELECT 1
1244
+ FROM information_schema.table_constraints tc
1245
+ WHERE tc.table_schema = $1
1246
+ AND tc.table_name = i.tablename
1247
+ AND tc.constraint_name = i.indexname
1248
+ )
1249
+ ORDER BY i.tablename, i.indexname, a.attnum`, [schema]),
1250
+ driver.query(`SELECT extname
1251
+ FROM pg_extension
1252
+ ORDER BY extname`, [])
1253
+ ]);
1254
+ const columnsByTable = groupBy(columnsResult.rows, "table_name");
1255
+ const pksByTable = groupBy(pkResult.rows, "table_name");
1256
+ const fksByTable = groupBy(fkResult.rows, "table_name");
1257
+ const uniquesByTable = groupBy(uniqueResult.rows, "table_name");
1258
+ const indexesByTable = groupBy(indexResult.rows, "tablename");
1259
+ const pkConstraintsByTable = /* @__PURE__ */ new Map();
1260
+ for (const row of pkResult.rows) {
1261
+ let constraints = pkConstraintsByTable.get(row.table_name);
1262
+ if (!constraints) {
1263
+ constraints = /* @__PURE__ */ new Set();
1264
+ pkConstraintsByTable.set(row.table_name, constraints);
1265
+ }
1266
+ constraints.add(row.constraint_name);
1267
+ }
1268
+ const tables = {};
1269
+ for (const tableRow of tablesResult.rows) {
1270
+ const tableName = tableRow.table_name;
1271
+ const columns = {};
1272
+ for (const colRow of columnsByTable.get(tableName) ?? []) {
1273
+ let nativeType = colRow.udt_name;
1274
+ const formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;
1275
+ if (formattedType) nativeType = formattedType;
1276
+ else if (colRow.data_type === "character varying" || colRow.data_type === "character") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;
1277
+ else nativeType = colRow.data_type;
1278
+ else if (colRow.data_type === "numeric" || colRow.data_type === "decimal") if (colRow.numeric_precision && colRow.numeric_scale !== null) nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;
1279
+ else if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;
1280
+ else nativeType = colRow.data_type;
1281
+ else nativeType = colRow.udt_name || colRow.data_type;
1282
+ columns[colRow.column_name] = {
1283
+ name: colRow.column_name,
1284
+ nativeType,
1285
+ nullable: colRow.is_nullable === "YES",
1286
+ ...ifDefined("default", colRow.column_default ?? void 0)
1287
+ };
1288
+ }
1289
+ const pkRows = [...pksByTable.get(tableName) ?? []];
1290
+ const primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);
1291
+ const primaryKey = primaryKeyColumns.length > 0 ? {
1292
+ columns: primaryKeyColumns,
1293
+ ...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}
1294
+ } : void 0;
1295
+ const foreignKeysMap = /* @__PURE__ */ new Map();
1296
+ for (const fkRow of fksByTable.get(tableName) ?? []) {
1297
+ const existing = foreignKeysMap.get(fkRow.constraint_name);
1298
+ if (existing) {
1299
+ existing.columns.push(fkRow.column_name);
1300
+ existing.referencedColumns.push(fkRow.referenced_column_name);
1301
+ } else foreignKeysMap.set(fkRow.constraint_name, {
1302
+ columns: [fkRow.column_name],
1303
+ referencedTable: fkRow.referenced_table_name,
1304
+ referencedColumns: [fkRow.referenced_column_name],
1305
+ name: fkRow.constraint_name,
1306
+ deleteRule: fkRow.delete_rule,
1307
+ updateRule: fkRow.update_rule
1308
+ });
1309
+ }
1310
+ const foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({
1311
+ columns: Object.freeze([...fk.columns]),
1312
+ referencedTable: fk.referencedTable,
1313
+ referencedColumns: Object.freeze([...fk.referencedColumns]),
1314
+ name: fk.name,
1315
+ ...ifDefined("onDelete", mapReferentialAction(fk.deleteRule)),
1316
+ ...ifDefined("onUpdate", mapReferentialAction(fk.updateRule))
1317
+ }));
1318
+ const pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();
1319
+ const uniquesMap = /* @__PURE__ */ new Map();
1320
+ for (const uniqueRow of uniquesByTable.get(tableName) ?? []) {
1321
+ if (pkConstraints.has(uniqueRow.constraint_name)) continue;
1322
+ const existing = uniquesMap.get(uniqueRow.constraint_name);
1323
+ if (existing) existing.columns.push(uniqueRow.column_name);
1324
+ else uniquesMap.set(uniqueRow.constraint_name, {
1325
+ columns: [uniqueRow.column_name],
1326
+ name: uniqueRow.constraint_name
1327
+ });
1328
+ }
1329
+ const uniques = Array.from(uniquesMap.values()).map((uq) => ({
1330
+ columns: Object.freeze([...uq.columns]),
1331
+ name: uq.name
1332
+ }));
1333
+ const indexesMap = /* @__PURE__ */ new Map();
1334
+ for (const idxRow of indexesByTable.get(tableName) ?? []) {
1335
+ if (!idxRow.attname) continue;
1336
+ const existing = indexesMap.get(idxRow.indexname);
1337
+ if (existing) existing.columns.push(idxRow.attname);
1338
+ else indexesMap.set(idxRow.indexname, {
1339
+ columns: [idxRow.attname],
1340
+ name: idxRow.indexname,
1341
+ unique: idxRow.indisunique
1342
+ });
1343
+ }
1344
+ const indexes = Array.from(indexesMap.values()).map((idx) => ({
1345
+ columns: Object.freeze([...idx.columns]),
1346
+ name: idx.name,
1347
+ unique: idx.unique
1348
+ }));
1349
+ tables[tableName] = {
1350
+ name: tableName,
1351
+ columns,
1352
+ ...ifDefined("primaryKey", primaryKey),
1353
+ foreignKeys,
1354
+ uniques,
1355
+ indexes
1356
+ };
1357
+ }
1358
+ const extensions = extensionsResult.rows.map((row) => row.extname);
1359
+ const storageTypes = await pgEnumControlHooks.introspectTypes?.({
1360
+ driver,
1361
+ schemaName: schema
1362
+ }) ?? {};
1363
+ return {
1364
+ tables,
1365
+ extensions,
1366
+ annotations: { pg: {
1367
+ schema,
1368
+ version: await this.getPostgresVersion(driver),
1369
+ ...ifDefined("storageTypes", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)
1370
+ } }
1371
+ };
1372
+ }
1373
+ /**
1374
+ * Gets the Postgres version from the database.
1375
+ */
1376
+ async getPostgresVersion(driver) {
1377
+ return ((await driver.query("SELECT version() AS version", [])).rows[0]?.version ?? "").match(/PostgreSQL (\d+\.\d+)/)?.[1] ?? "unknown";
1378
+ }
1379
+ };
1380
+ /**
1381
+ * Pre-computed lookup map for simple prefix-based type normalization.
1382
+ * Maps short Postgres type names to their canonical SQL names.
1383
+ * Using a Map for O(1) lookup instead of multiple startsWith checks.
1384
+ */
1385
+ const TYPE_PREFIX_MAP = new Map([
1386
+ ["varchar", "character varying"],
1387
+ ["bpchar", "character"],
1388
+ ["varbit", "bit varying"]
1389
+ ]);
1390
+ /**
1391
+ * Normalizes a Postgres schema native type to its canonical form for comparison.
1392
+ *
1393
+ * Uses a pre-computed lookup map for simple prefix replacements (O(1))
1394
+ * and handles complex temporal type normalization separately.
1395
+ */
1396
+ function normalizeSchemaNativeType(nativeType) {
1397
+ const trimmed = nativeType.trim();
1398
+ for (const [prefix, replacement] of TYPE_PREFIX_MAP) if (trimmed.startsWith(prefix)) return replacement + trimmed.slice(prefix.length);
1399
+ if (trimmed.includes(" with time zone")) {
1400
+ if (trimmed.startsWith("timestamp")) return `timestamptz${trimmed.slice(9).replace(" with time zone", "")}`;
1401
+ if (trimmed.startsWith("time")) return `timetz${trimmed.slice(4).replace(" with time zone", "")}`;
1402
+ }
1403
+ if (trimmed.includes(" without time zone")) return trimmed.replace(" without time zone", "");
1404
+ return trimmed;
1405
+ }
1406
+ function normalizeFormattedType(formattedType, dataType, udtName) {
1407
+ if (formattedType === "integer") return "int4";
1408
+ if (formattedType === "smallint") return "int2";
1409
+ if (formattedType === "bigint") return "int8";
1410
+ if (formattedType === "real") return "float4";
1411
+ if (formattedType === "double precision") return "float8";
1412
+ if (formattedType === "boolean") return "bool";
1413
+ if (formattedType.startsWith("varchar")) return formattedType.replace("varchar", "character varying");
1414
+ if (formattedType.startsWith("bpchar")) return formattedType.replace("bpchar", "character");
1415
+ if (formattedType.startsWith("varbit")) return formattedType.replace("varbit", "bit varying");
1416
+ if (dataType === "timestamp with time zone" || udtName === "timestamptz") return formattedType.replace("timestamp", "timestamptz").replace(" with time zone", "").trim();
1417
+ if (dataType === "timestamp without time zone" || udtName === "timestamp") return formattedType.replace(" without time zone", "").trim();
1418
+ if (dataType === "time with time zone" || udtName === "timetz") return formattedType.replace("time", "timetz").replace(" with time zone", "").trim();
1419
+ if (dataType === "time without time zone" || udtName === "time") return formattedType.replace(" without time zone", "").trim();
1420
+ if (formattedType.startsWith("\"") && formattedType.endsWith("\"")) return formattedType.slice(1, -1);
1421
+ return formattedType;
1422
+ }
1423
+ const PG_REFERENTIAL_ACTION_MAP = {
1424
+ "NO ACTION": "noAction",
1425
+ RESTRICT: "restrict",
1426
+ CASCADE: "cascade",
1427
+ "SET NULL": "setNull",
1428
+ "SET DEFAULT": "setDefault"
1429
+ };
1430
+ /**
1431
+ * Maps a Postgres referential action rule to the canonical SqlReferentialAction.
1432
+ * Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.
1433
+ * Throws for unrecognized rules to prevent silent data loss.
1434
+ */
1435
+ function mapReferentialAction(rule) {
1436
+ const mapped = PG_REFERENTIAL_ACTION_MAP[rule];
1437
+ if (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: "${rule}". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);
1438
+ if (mapped === "noAction") return void 0;
1439
+ return mapped;
1440
+ }
1441
+ /**
1442
+ * Groups an array of objects by a specified key.
1443
+ * Returns a Map for O(1) lookup by group key.
1444
+ */
1445
+ function groupBy(items, key) {
1446
+ const map = /* @__PURE__ */ new Map();
1447
+ for (const item of items) {
1448
+ const groupKey = item[key];
1449
+ let group = map.get(groupKey);
1450
+ if (!group) {
1451
+ group = [];
1452
+ map.set(groupKey, group);
1453
+ }
1454
+ group.push(item);
1455
+ }
1456
+ return map;
1457
+ }
1458
+ var control_default$1 = {
1459
+ ...postgresAdapterDescriptorMeta,
1460
+ operationSignatures: () => [],
1461
+ create() {
1462
+ return new PostgresControlAdapter();
1463
+ }
1464
+ };
1465
+
1466
+ //#endregion
1467
+ //#region src/core/migrations/planner-reconciliation.ts
1468
+ function buildReconciliationPlan(options) {
1469
+ const operations = [];
1470
+ const conflicts = [];
1471
+ const { mode } = options;
1472
+ const seenOperationIds = /* @__PURE__ */ new Set();
1473
+ for (const issue of sortSchemaIssues(options.issues)) {
1474
+ if (isAdditiveIssue(issue)) continue;
1475
+ const operation = buildReconciliationOperationFromIssue({
1476
+ issue,
1477
+ contract: options.contract,
1478
+ schemaName: options.schemaName,
1479
+ mode
1480
+ });
1481
+ if (operation) {
1482
+ if (!seenOperationIds.has(operation.id)) {
1483
+ seenOperationIds.add(operation.id);
1484
+ if (options.policy.allowedOperationClasses.includes(operation.operationClass)) operations.push(operation);
1485
+ else {
1486
+ const conflict = convertIssueToConflict(issue);
1487
+ if (conflict) conflicts.push(conflict);
1488
+ }
1489
+ }
1490
+ } else {
1491
+ const conflict = convertIssueToConflict(issue);
1492
+ if (conflict) conflicts.push(conflict);
1493
+ }
1494
+ }
1495
+ return {
1496
+ operations,
1497
+ conflicts: conflicts.sort(conflictComparator)
1498
+ };
1499
+ }
1500
+ function isAdditiveIssue(issue) {
1501
+ switch (issue.kind) {
1502
+ case "type_missing":
1503
+ case "type_values_mismatch":
1504
+ case "missing_table":
1505
+ case "missing_column":
1506
+ case "extension_missing": return true;
1507
+ case "primary_key_mismatch": return issue.actual === void 0;
1508
+ case "unique_constraint_mismatch":
1509
+ case "index_mismatch":
1510
+ case "foreign_key_mismatch": return issue.indexOrConstraint === void 0;
1511
+ default: return false;
1512
+ }
1513
+ }
1514
+ function buildReconciliationOperationFromIssue(options) {
1515
+ const { issue, contract, schemaName, mode } = options;
1516
+ switch (issue.kind) {
1517
+ case "extra_table":
1518
+ if (!mode.allowDestructive || !issue.table) return null;
1519
+ return buildDropTableOperation(schemaName, issue.table);
1520
+ case "extra_column":
1521
+ if (!mode.allowDestructive || !issue.table || !issue.column) return null;
1522
+ return buildDropColumnOperation(schemaName, issue.table, issue.column);
1523
+ case "extra_index":
1524
+ if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) return null;
1525
+ return buildDropIndexOperation(schemaName, issue.table, issue.indexOrConstraint);
1526
+ case "extra_foreign_key":
1527
+ case "extra_unique_constraint": {
1528
+ if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) return null;
1529
+ const constraintKind = issue.kind === "extra_foreign_key" ? "foreignKey" : "unique";
1530
+ return buildDropConstraintOperation(schemaName, issue.table, issue.indexOrConstraint, constraintKind);
1531
+ }
1532
+ case "extra_primary_key": {
1533
+ if (!mode.allowDestructive || !issue.table) return null;
1534
+ const constraintName = issue.indexOrConstraint ?? `${issue.table}_pkey`;
1535
+ return buildDropConstraintOperation(schemaName, issue.table, constraintName, "primaryKey");
1536
+ }
1537
+ case "nullability_mismatch":
1538
+ if (!issue.table || !issue.column) return null;
1539
+ if (issue.expected === "true") return mode.allowWidening ? buildDropNotNullOperation(schemaName, issue.table, issue.column) : null;
1540
+ return mode.allowDestructive ? buildSetNotNullOperation(schemaName, issue.table, issue.column) : null;
1541
+ case "type_mismatch": {
1542
+ if (!mode.allowDestructive || !issue.table || !issue.column) return null;
1543
+ const contractColumn = getContractColumn(contract, issue.table, issue.column);
1544
+ if (!contractColumn) return null;
1545
+ return buildAlterColumnTypeOperation(schemaName, issue.table, issue.column, contractColumn);
1546
+ }
1547
+ default: return null;
1548
+ }
1549
+ }
1550
+ function getContractColumn(contract, tableName, columnName) {
1551
+ const table = contract.storage.tables[tableName];
1552
+ if (!table) return null;
1553
+ return table.columns[columnName] ?? null;
1554
+ }
1555
+ function buildDropTableOperation(schemaName, tableName) {
1556
+ return {
1557
+ id: `dropTable.${tableName}`,
1558
+ label: `Drop table ${tableName}`,
1559
+ summary: `Drops extra table ${tableName}`,
1560
+ operationClass: "destructive",
1561
+ target: {
1562
+ id: "postgres",
1563
+ details: buildTargetDetails("table", tableName, schemaName)
1564
+ },
1565
+ precheck: [{
1566
+ description: `ensure table "${tableName}" exists`,
1567
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`
1568
+ }],
1569
+ execute: [{
1570
+ description: `drop table "${tableName}"`,
1571
+ sql: `DROP TABLE ${qualifyTableName(schemaName, tableName)}`
1572
+ }],
1573
+ postcheck: [{
1574
+ description: `verify table "${tableName}" is removed`,
1575
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`
1576
+ }]
1577
+ };
1578
+ }
1579
+ function buildDropColumnOperation(schemaName, tableName, columnName) {
1580
+ return {
1581
+ id: `dropColumn.${tableName}.${columnName}`,
1582
+ label: `Drop column ${columnName} from ${tableName}`,
1583
+ summary: `Drops extra column ${columnName} from table ${tableName}`,
1584
+ operationClass: "destructive",
1585
+ target: {
1586
+ id: "postgres",
1587
+ details: buildTargetDetails("column", columnName, schemaName, tableName)
1588
+ },
1589
+ precheck: [{
1590
+ description: `ensure column "${columnName}" exists`,
1591
+ sql: columnExistsCheck({
1592
+ schema: schemaName,
1593
+ table: tableName,
1594
+ column: columnName
1595
+ })
1596
+ }],
1597
+ execute: [{
1598
+ description: `drop column "${columnName}"`,
1599
+ sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`
1600
+ }],
1601
+ postcheck: [{
1602
+ description: `verify column "${columnName}" is removed`,
1603
+ sql: columnExistsCheck({
1604
+ schema: schemaName,
1605
+ table: tableName,
1606
+ column: columnName,
1607
+ exists: false
1608
+ })
1609
+ }]
1610
+ };
1611
+ }
1612
+ function buildDropIndexOperation(schemaName, tableName, indexName) {
1613
+ return {
1614
+ id: `dropIndex.${tableName}.${indexName}`,
1615
+ label: `Drop index ${indexName} on ${tableName}`,
1616
+ summary: `Drops extra index ${indexName} on table ${tableName}`,
1617
+ operationClass: "destructive",
1618
+ target: {
1619
+ id: "postgres",
1620
+ details: buildTargetDetails("index", indexName, schemaName, tableName)
1621
+ },
1622
+ precheck: [{
1623
+ description: `ensure index "${indexName}" exists`,
1624
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`
1625
+ }],
1626
+ execute: [{
1627
+ description: `drop index "${indexName}"`,
1628
+ sql: `DROP INDEX ${qualifyTableName(schemaName, indexName)}`
1629
+ }],
1630
+ postcheck: [{
1631
+ description: `verify index "${indexName}" is removed`,
1632
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`
1633
+ }]
1634
+ };
1635
+ }
1636
+ function buildDropConstraintOperation(schemaName, tableName, constraintName, constraintKind) {
1637
+ return {
1638
+ id: `dropConstraint.${tableName}.${constraintName}`,
1639
+ label: `Drop constraint ${constraintName} on ${tableName}`,
1640
+ summary: `Drops extra constraint ${constraintName} on table ${tableName}`,
1641
+ operationClass: "destructive",
1642
+ target: {
1643
+ id: "postgres",
1644
+ details: buildTargetDetails(constraintKind, constraintName, schemaName, tableName)
1645
+ },
1646
+ precheck: [{
1647
+ description: `ensure constraint "${constraintName}" exists`,
1648
+ sql: constraintExistsCheck({
1649
+ constraintName,
1650
+ schema: schemaName
1651
+ })
1652
+ }],
1653
+ execute: [{
1654
+ description: `drop constraint "${constraintName}"`,
1655
+ sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
1656
+ DROP CONSTRAINT ${quoteIdentifier(constraintName)}`
1657
+ }],
1658
+ postcheck: [{
1659
+ description: `verify constraint "${constraintName}" is removed`,
1660
+ sql: constraintExistsCheck({
1661
+ constraintName,
1662
+ schema: schemaName,
1663
+ exists: false
1664
+ })
1665
+ }]
1666
+ };
1667
+ }
1668
+ function buildDropNotNullOperation(schemaName, tableName, columnName) {
1669
+ return {
1670
+ id: `alterNullability.${tableName}.${columnName}`,
1671
+ label: `Relax nullability for ${columnName} on ${tableName}`,
1672
+ summary: `Drops NOT NULL constraint for ${columnName} on table ${tableName}`,
1673
+ operationClass: "widening",
1674
+ target: {
1675
+ id: "postgres",
1676
+ details: buildTargetDetails("column", columnName, schemaName, tableName)
1677
+ },
1678
+ precheck: [{
1679
+ description: `ensure column "${columnName}" exists`,
1680
+ sql: columnExistsCheck({
1681
+ schema: schemaName,
1682
+ table: tableName,
1683
+ column: columnName
1684
+ })
1685
+ }],
1686
+ execute: [{
1687
+ description: `drop NOT NULL from "${columnName}"`,
1688
+ sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
1689
+ ALTER COLUMN ${quoteIdentifier(columnName)} DROP NOT NULL`
1690
+ }],
1691
+ postcheck: [{
1692
+ description: `verify "${columnName}" is nullable`,
1693
+ sql: columnNullabilityCheck({
1694
+ schema: schemaName,
1695
+ table: tableName,
1696
+ column: columnName,
1697
+ nullable: true
1698
+ })
1699
+ }]
1700
+ };
1701
+ }
1702
+ function buildSetNotNullOperation(schemaName, tableName, columnName) {
1703
+ const qualified = qualifyTableName(schemaName, tableName);
1704
+ return {
1705
+ id: `alterNullability.${tableName}.${columnName}`,
1706
+ label: `Enforce NOT NULL for ${columnName} on ${tableName}`,
1707
+ summary: `Sets NOT NULL on ${columnName} for table ${tableName}`,
1708
+ operationClass: "destructive",
1709
+ target: {
1710
+ id: "postgres",
1711
+ details: buildTargetDetails("column", columnName, schemaName, tableName)
1712
+ },
1713
+ precheck: [{
1714
+ description: `ensure column "${columnName}" exists`,
1715
+ sql: columnExistsCheck({
1716
+ schema: schemaName,
1717
+ table: tableName,
1718
+ column: columnName
1719
+ })
1720
+ }, {
1721
+ description: `ensure "${columnName}" has no NULL values`,
1722
+ sql: `SELECT NOT EXISTS (
1723
+ SELECT 1 FROM ${qualified}
1724
+ WHERE ${quoteIdentifier(columnName)} IS NULL
1725
+ LIMIT 1
1726
+ )`
1727
+ }],
1728
+ execute: [{
1729
+ description: `set NOT NULL on "${columnName}"`,
1730
+ sql: `ALTER TABLE ${qualified}
1731
+ ALTER COLUMN ${quoteIdentifier(columnName)} SET NOT NULL`
1732
+ }],
1733
+ postcheck: [{
1734
+ description: `verify "${columnName}" is NOT NULL`,
1735
+ sql: columnNullabilityCheck({
1736
+ schema: schemaName,
1737
+ table: tableName,
1738
+ column: columnName,
1739
+ nullable: false
1740
+ })
1741
+ }]
1742
+ };
1743
+ }
1744
+ function buildAlterColumnTypeOperation(schemaName, tableName, columnName, column) {
1745
+ const qualified = qualifyTableName(schemaName, tableName);
1746
+ const expectedType = buildColumnTypeSql(column);
1747
+ return {
1748
+ id: `alterType.${tableName}.${columnName}`,
1749
+ label: `Alter type for ${columnName} on ${tableName}`,
1750
+ summary: `Changes type of ${columnName} to ${expectedType}`,
1751
+ operationClass: "destructive",
1752
+ target: {
1753
+ id: "postgres",
1754
+ details: buildTargetDetails("column", columnName, schemaName, tableName)
1755
+ },
1756
+ meta: {
1757
+ warning: "TABLE_REWRITE",
1758
+ detail: "ALTER COLUMN TYPE requires a full table rewrite and acquires an ACCESS EXCLUSIVE lock. On large tables, this can cause significant downtime."
1759
+ },
1760
+ precheck: [{
1761
+ description: `ensure column "${columnName}" exists`,
1762
+ sql: columnExistsCheck({
1763
+ schema: schemaName,
1764
+ table: tableName,
1765
+ column: columnName
1766
+ })
1767
+ }],
1768
+ execute: [{
1769
+ description: `alter type of "${columnName}"`,
1770
+ sql: `ALTER TABLE ${qualified}
1771
+ ALTER COLUMN ${quoteIdentifier(columnName)}
1772
+ TYPE ${expectedType}
1773
+ USING ${quoteIdentifier(columnName)}::${expectedType}`
1774
+ }],
1775
+ postcheck: [{
1776
+ description: `verify column "${columnName}" exists after type change`,
1777
+ sql: columnExistsCheck({
1778
+ schema: schemaName,
1779
+ table: tableName,
1780
+ column: columnName
1781
+ })
1782
+ }]
1783
+ };
1784
+ }
1785
+ function convertIssueToConflict(issue) {
1786
+ switch (issue.kind) {
1787
+ case "type_mismatch": return buildConflict("typeMismatch", issue);
1788
+ case "nullability_mismatch": return buildConflict("nullabilityConflict", issue);
1789
+ case "default_missing":
1790
+ case "default_mismatch":
1791
+ case "extra_table":
1792
+ case "extra_column":
1793
+ case "extra_primary_key":
1794
+ case "extra_foreign_key":
1795
+ case "extra_unique_constraint":
1796
+ case "extra_index": return buildConflict("missingButNonAdditive", issue);
1797
+ case "primary_key_mismatch":
1798
+ case "unique_constraint_mismatch":
1799
+ case "index_mismatch": return buildConflict("indexIncompatible", issue);
1800
+ case "foreign_key_mismatch": return buildConflict("foreignKeyConflict", issue);
1801
+ default: return null;
1802
+ }
1803
+ }
1804
+ function buildConflict(kind, issue) {
1805
+ const location = buildConflictLocation(issue);
1806
+ const meta = issue.expected || issue.actual ? Object.freeze({
1807
+ ...ifDefined("expected", issue.expected),
1808
+ ...ifDefined("actual", issue.actual)
1809
+ }) : void 0;
1810
+ return {
1811
+ kind,
1812
+ summary: issue.message,
1813
+ ...ifDefined("location", location),
1814
+ ...ifDefined("meta", meta)
1815
+ };
1816
+ }
1817
+ function sortSchemaIssues(issues) {
1818
+ return [...issues].sort((a, b) => {
1819
+ const kindCompare = a.kind.localeCompare(b.kind);
1820
+ if (kindCompare !== 0) return kindCompare;
1821
+ const tableCompare = compareStrings(a.table, b.table);
1822
+ if (tableCompare !== 0) return tableCompare;
1823
+ const columnCompare = compareStrings(a.column, b.column);
1824
+ if (columnCompare !== 0) return columnCompare;
1825
+ return compareStrings(a.indexOrConstraint, b.indexOrConstraint);
1826
+ });
1827
+ }
1828
+ function buildConflictLocation(issue) {
1829
+ const location = {
1830
+ ...ifDefined("table", issue.table),
1831
+ ...ifDefined("column", issue.column),
1832
+ ...ifDefined("constraint", issue.indexOrConstraint)
1833
+ };
1834
+ return Object.keys(location).length > 0 ? location : void 0;
1835
+ }
1836
+ function conflictComparator(a, b) {
1837
+ if (a.kind !== b.kind) return a.kind < b.kind ? -1 : 1;
1838
+ const aLocation = a.location ?? {};
1839
+ const bLocation = b.location ?? {};
1840
+ const tableCompare = compareStrings(aLocation.table, bLocation.table);
1841
+ if (tableCompare !== 0) return tableCompare;
1842
+ const columnCompare = compareStrings(aLocation.column, bLocation.column);
1843
+ if (columnCompare !== 0) return columnCompare;
1844
+ const constraintCompare = compareStrings(aLocation.constraint, bLocation.constraint);
1845
+ if (constraintCompare !== 0) return constraintCompare;
1846
+ return compareStrings(a.summary, b.summary);
1847
+ }
1848
+ function compareStrings(a, b) {
1849
+ if (a === b) return 0;
1850
+ if (a === void 0) return -1;
1851
+ if (b === void 0) return 1;
1852
+ return a < b ? -1 : 1;
1853
+ }
1854
+
1855
+ //#endregion
1856
+ //#region src/core/migrations/planner.ts
1857
+ const DEFAULT_PLANNER_CONFIG = { defaultSchema: "public" };
1858
+ function createPostgresMigrationPlanner(config = {}) {
1859
+ return new PostgresMigrationPlanner({
1860
+ ...DEFAULT_PLANNER_CONFIG,
1861
+ ...config
1862
+ });
1863
+ }
1864
+ var PostgresMigrationPlanner = class {
1865
+ constructor(config) {
1866
+ this.config = config;
1867
+ }
1868
+ plan(options) {
1869
+ const schemaName = options.schemaName ?? this.config.defaultSchema;
1870
+ const policyResult = this.ensureAdditivePolicy(options.policy);
1871
+ if (policyResult) return policyResult;
1872
+ const planningMode = this.resolvePlanningMode(options.policy);
1873
+ const schemaIssues = this.collectSchemaIssues(options, planningMode.includeExtraObjects);
1874
+ const codecHooks = extractCodecControlHooks(options.frameworkComponents);
1875
+ const operations = [];
1876
+ const reconciliationPlan = buildReconciliationPlan({
1877
+ contract: options.contract,
1878
+ issues: schemaIssues,
1879
+ schemaName,
1880
+ mode: planningMode,
1881
+ policy: options.policy
1882
+ });
1883
+ if (reconciliationPlan.conflicts.length > 0) return plannerFailure(reconciliationPlan.conflicts);
1884
+ const storageTypePlan = this.buildStorageTypeOperations(options, schemaName, codecHooks);
1885
+ if (storageTypePlan.conflicts.length > 0) return plannerFailure(storageTypePlan.conflicts);
1886
+ const sortedTables = sortedEntries(options.contract.storage.tables);
1887
+ const schemaLookups = buildSchemaLookupMap(options.schema);
1888
+ operations.push(...this.buildDatabaseDependencyOperations(options), ...storageTypePlan.operations, ...reconciliationPlan.operations, ...this.buildTableOperations(sortedTables, options.schema, schemaName), ...this.buildColumnOperations(sortedTables, options.schema, schemaName), ...this.buildPrimaryKeyOperations(sortedTables, options.schema, schemaName), ...this.buildUniqueOperations(sortedTables, schemaLookups, schemaName), ...this.buildIndexOperations(sortedTables, schemaLookups, schemaName), ...this.buildFkBackingIndexOperations(sortedTables, schemaLookups, schemaName), ...this.buildForeignKeyOperations(sortedTables, schemaLookups, schemaName));
1889
+ return plannerSuccess(createMigrationPlan({
1890
+ targetId: "postgres",
1891
+ origin: null,
1892
+ destination: {
1893
+ storageHash: options.contract.storageHash,
1894
+ ...ifDefined("profileHash", options.contract.profileHash)
1895
+ },
1896
+ operations
1897
+ }));
1898
+ }
1899
+ ensureAdditivePolicy(policy) {
1900
+ if (!policy.allowedOperationClasses.includes("additive")) return plannerFailure([{
1901
+ kind: "unsupportedOperation",
1902
+ summary: "Migration planner requires additive operations be allowed",
1903
+ why: "The planner requires the \"additive\" operation class to be allowed in the policy."
1904
+ }]);
1905
+ return null;
1906
+ }
1907
+ /**
1908
+ * Builds migration operations from component-owned database dependencies.
1909
+ * These operations install database-side persistence structures declared by components.
1910
+ */
1911
+ buildDatabaseDependencyOperations(options) {
1912
+ const dependencies = this.collectDependencies(options);
1913
+ const operations = [];
1914
+ const seenDependencyIds = /* @__PURE__ */ new Set();
1915
+ const seenOperationIds = /* @__PURE__ */ new Set();
1916
+ for (const dependency of dependencies) {
1917
+ if (seenDependencyIds.has(dependency.id)) continue;
1918
+ seenDependencyIds.add(dependency.id);
1919
+ if (dependency.verifyDatabaseDependencyInstalled(options.schema).length === 0) continue;
1920
+ for (const installOp of dependency.install) {
1921
+ if (seenOperationIds.has(installOp.id)) continue;
1922
+ seenOperationIds.add(installOp.id);
1923
+ operations.push(installOp);
1924
+ }
1925
+ }
1926
+ return operations;
1927
+ }
1928
+ buildStorageTypeOperations(options, schemaName, codecHooks) {
1929
+ const operations = [];
1930
+ const conflicts = [];
1931
+ const storageTypes = options.contract.storage.types ?? {};
1932
+ for (const [typeName, typeInstance] of sortedEntries(storageTypes)) {
1933
+ const planResult = codecHooks.get(typeInstance.codecId)?.planTypeOperations?.({
1934
+ typeName,
1935
+ typeInstance,
1936
+ contract: options.contract,
1937
+ schema: options.schema,
1938
+ schemaName,
1939
+ policy: options.policy
1940
+ });
1941
+ if (!planResult) continue;
1942
+ for (const operation of planResult.operations) {
1943
+ if (!options.policy.allowedOperationClasses.includes(operation.operationClass)) {
1944
+ conflicts.push({
1945
+ kind: "missingButNonAdditive",
1946
+ summary: `Storage type "${typeName}" requires "${operation.operationClass}" operation "${operation.id}"`,
1947
+ location: { type: typeName }
1948
+ });
1949
+ continue;
1950
+ }
1951
+ operations.push({
1952
+ ...operation,
1953
+ target: {
1954
+ id: operation.target.id,
1955
+ details: this.buildTargetDetails("type", typeName, schemaName)
1956
+ }
1957
+ });
1958
+ }
1959
+ }
1960
+ return {
1961
+ operations,
1962
+ conflicts
1963
+ };
1964
+ }
1965
+ collectDependencies(options) {
1966
+ const components = options.frameworkComponents;
1967
+ if (components.length === 0) return [];
1968
+ const deps = [];
1969
+ for (const component of components) {
1970
+ if (!isSqlDependencyProvider(component)) continue;
1971
+ const initDeps = component.databaseDependencies?.init;
1972
+ if (initDeps && initDeps.length > 0) deps.push(...initDeps);
1973
+ }
1974
+ return sortDependencies(deps);
1975
+ }
1976
+ buildTableOperations(tables, schema, schemaName) {
1977
+ const operations = [];
1978
+ for (const [tableName, table] of tables) {
1979
+ if (schema.tables[tableName]) continue;
1980
+ const qualified = qualifyTableName(schemaName, tableName);
1981
+ operations.push({
1982
+ id: `table.${tableName}`,
1983
+ label: `Create table ${tableName}`,
1984
+ summary: `Creates table ${tableName} with required columns`,
1985
+ operationClass: "additive",
1986
+ target: {
1987
+ id: "postgres",
1988
+ details: this.buildTargetDetails("table", tableName, schemaName)
1989
+ },
1990
+ precheck: [{
1991
+ description: `ensure table "${tableName}" does not exist`,
1992
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`
1993
+ }],
1994
+ execute: [{
1995
+ description: `create table "${tableName}"`,
1996
+ sql: buildCreateTableSql(qualified, table)
1997
+ }],
1998
+ postcheck: [{
1999
+ description: `verify table "${tableName}" exists`,
2000
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`
2001
+ }]
2002
+ });
2003
+ }
2004
+ return operations;
2005
+ }
2006
+ buildColumnOperations(tables, schema, schemaName) {
2007
+ const operations = [];
2008
+ for (const [tableName, table] of tables) {
2009
+ const schemaTable = schema.tables[tableName];
2010
+ if (!schemaTable) continue;
2011
+ for (const [columnName, column] of sortedEntries(table.columns)) {
2012
+ if (schemaTable.columns[columnName]) continue;
2013
+ operations.push(this.buildAddColumnOperation(schemaName, tableName, columnName, column));
2014
+ }
2015
+ }
2016
+ return operations;
2017
+ }
2018
+ buildAddColumnOperation(schema, tableName, columnName, column) {
2019
+ const qualified = qualifyTableName(schema, tableName);
2020
+ const notNull = column.nullable === false;
2021
+ const hasDefault = column.default !== void 0;
2022
+ const requiresEmptyTable = notNull && !hasDefault;
2023
+ const precheck = [{
2024
+ description: `ensure column "${columnName}" is missing`,
2025
+ sql: columnExistsCheck({
2026
+ schema,
2027
+ table: tableName,
2028
+ column: columnName,
2029
+ exists: false
2030
+ })
2031
+ }, ...requiresEmptyTable ? [{
2032
+ description: `ensure table "${tableName}" is empty before adding NOT NULL column without default`,
2033
+ sql: tableIsEmptyCheck(qualified)
2034
+ }] : []];
2035
+ const execute = [{
2036
+ description: `add column "${columnName}"`,
2037
+ sql: buildAddColumnSql(qualified, columnName, column)
2038
+ }];
2039
+ const postcheck = [{
2040
+ description: `verify column "${columnName}" exists`,
2041
+ sql: columnExistsCheck({
2042
+ schema,
2043
+ table: tableName,
2044
+ column: columnName
2045
+ })
2046
+ }, ...notNull ? [{
2047
+ description: `verify column "${columnName}" is NOT NULL`,
2048
+ sql: columnNullabilityCheck({
2049
+ schema,
2050
+ table: tableName,
2051
+ column: columnName,
2052
+ nullable: false
2053
+ })
2054
+ }] : []];
2055
+ return {
2056
+ id: `column.${tableName}.${columnName}`,
2057
+ label: `Add column ${columnName} to ${tableName}`,
2058
+ summary: `Adds column ${columnName} to table ${tableName}`,
2059
+ operationClass: "additive",
2060
+ target: {
2061
+ id: "postgres",
2062
+ details: this.buildTargetDetails("table", tableName, schema)
2063
+ },
2064
+ precheck,
2065
+ execute,
2066
+ postcheck
2067
+ };
2068
+ }
2069
+ buildPrimaryKeyOperations(tables, schema, schemaName) {
2070
+ const operations = [];
2071
+ for (const [tableName, table] of tables) {
2072
+ if (!table.primaryKey) continue;
2073
+ const schemaTable = schema.tables[tableName];
2074
+ if (!schemaTable || schemaTable.primaryKey) continue;
2075
+ const constraintName = table.primaryKey.name ?? `${tableName}_pkey`;
2076
+ operations.push({
2077
+ id: `primaryKey.${tableName}.${constraintName}`,
2078
+ label: `Add primary key ${constraintName} on ${tableName}`,
2079
+ summary: `Adds primary key ${constraintName} on ${tableName}`,
2080
+ operationClass: "additive",
2081
+ target: {
2082
+ id: "postgres",
2083
+ details: this.buildTargetDetails("table", tableName, schemaName)
2084
+ },
2085
+ precheck: [{
2086
+ description: `ensure primary key does not exist on "${tableName}"`,
2087
+ sql: tableHasPrimaryKeyCheck(schemaName, tableName, false)
2088
+ }],
2089
+ execute: [{
2090
+ description: `add primary key "${constraintName}"`,
2091
+ sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
2092
+ ADD CONSTRAINT ${quoteIdentifier(constraintName)}
2093
+ PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(", ")})`
2094
+ }],
2095
+ postcheck: [{
2096
+ description: `verify primary key "${constraintName}" exists`,
2097
+ sql: tableHasPrimaryKeyCheck(schemaName, tableName, true, constraintName)
2098
+ }]
2099
+ });
2100
+ }
2101
+ return operations;
2102
+ }
2103
+ buildUniqueOperations(tables, schemaLookups, schemaName) {
2104
+ const operations = [];
2105
+ for (const [tableName, table] of tables) {
2106
+ const lookup = schemaLookups.get(tableName);
2107
+ for (const unique of table.uniques) {
2108
+ if (lookup && hasUniqueConstraint(lookup, unique.columns)) continue;
2109
+ const constraintName = unique.name ?? `${tableName}_${unique.columns.join("_")}_key`;
2110
+ operations.push({
2111
+ id: `unique.${tableName}.${constraintName}`,
2112
+ label: `Add unique constraint ${constraintName} on ${tableName}`,
2113
+ summary: `Adds unique constraint ${constraintName} on ${tableName}`,
2114
+ operationClass: "additive",
2115
+ target: {
2116
+ id: "postgres",
2117
+ details: this.buildTargetDetails("unique", constraintName, schemaName, tableName)
2118
+ },
2119
+ precheck: [{
2120
+ description: `ensure unique constraint "${constraintName}" is missing`,
2121
+ sql: constraintExistsCheck({
2122
+ constraintName,
2123
+ schema: schemaName,
2124
+ exists: false
2125
+ })
2126
+ }],
2127
+ execute: [{
2128
+ description: `add unique constraint "${constraintName}"`,
2129
+ sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
2130
+ ADD CONSTRAINT ${quoteIdentifier(constraintName)}
2131
+ UNIQUE (${unique.columns.map(quoteIdentifier).join(", ")})`
2132
+ }],
2133
+ postcheck: [{
2134
+ description: `verify unique constraint "${constraintName}" exists`,
2135
+ sql: constraintExistsCheck({
2136
+ constraintName,
2137
+ schema: schemaName
2138
+ })
2139
+ }]
2140
+ });
2141
+ }
2142
+ }
2143
+ return operations;
2144
+ }
2145
+ buildIndexOperations(tables, schemaLookups, schemaName) {
2146
+ const operations = [];
2147
+ for (const [tableName, table] of tables) {
2148
+ const lookup = schemaLookups.get(tableName);
2149
+ for (const index of table.indexes) {
2150
+ if (lookup && hasIndex(lookup, index.columns)) continue;
2151
+ const indexName = index.name ?? `${tableName}_${index.columns.join("_")}_idx`;
2152
+ operations.push({
2153
+ id: `index.${tableName}.${indexName}`,
2154
+ label: `Create index ${indexName} on ${tableName}`,
2155
+ summary: `Creates index ${indexName} on ${tableName}`,
2156
+ operationClass: "additive",
2157
+ target: {
2158
+ id: "postgres",
2159
+ details: this.buildTargetDetails("index", indexName, schemaName, tableName)
2160
+ },
2161
+ precheck: [{
2162
+ description: `ensure index "${indexName}" is missing`,
2163
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`
2164
+ }],
2165
+ execute: [{
2166
+ description: `create index "${indexName}"`,
2167
+ sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(schemaName, tableName)} (${index.columns.map(quoteIdentifier).join(", ")})`
2168
+ }],
2169
+ postcheck: [{
2170
+ description: `verify index "${indexName}" exists`,
2171
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`
2172
+ }]
2173
+ });
2174
+ }
2175
+ }
2176
+ return operations;
2177
+ }
2178
+ /**
2179
+ * Generates FK-backing index operations for FKs with `index: true`,
2180
+ * but only when no matching user-declared index exists in `contractTable.indexes`.
2181
+ */
2182
+ buildFkBackingIndexOperations(tables, schemaLookups, schemaName) {
2183
+ const operations = [];
2184
+ for (const [tableName, table] of tables) {
2185
+ const lookup = schemaLookups.get(tableName);
2186
+ const declaredIndexColumns = new Set(table.indexes.map((idx) => idx.columns.join(",")));
2187
+ for (const fk of table.foreignKeys) {
2188
+ if (fk.index === false) continue;
2189
+ if (declaredIndexColumns.has(fk.columns.join(","))) continue;
2190
+ if (lookup && hasIndex(lookup, fk.columns)) continue;
2191
+ const indexName = `${tableName}_${fk.columns.join("_")}_idx`;
2192
+ operations.push({
2193
+ id: `index.${tableName}.${indexName}`,
2194
+ label: `Create FK-backing index ${indexName} on ${tableName}`,
2195
+ summary: `Creates FK-backing index ${indexName} on ${tableName}`,
2196
+ operationClass: "additive",
2197
+ target: {
2198
+ id: "postgres",
2199
+ details: this.buildTargetDetails("index", indexName, schemaName, tableName)
2200
+ },
2201
+ precheck: [{
2202
+ description: `ensure index "${indexName}" is missing`,
2203
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`
2204
+ }],
2205
+ execute: [{
2206
+ description: `create FK-backing index "${indexName}"`,
2207
+ sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(schemaName, tableName)} (${fk.columns.map(quoteIdentifier).join(", ")})`
2208
+ }],
2209
+ postcheck: [{
2210
+ description: `verify index "${indexName}" exists`,
2211
+ sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`
2212
+ }]
2213
+ });
2214
+ }
2215
+ }
2216
+ return operations;
2217
+ }
2218
+ buildForeignKeyOperations(tables, schemaLookups, schemaName) {
2219
+ const operations = [];
2220
+ for (const [tableName, table] of tables) {
2221
+ const lookup = schemaLookups.get(tableName);
2222
+ for (const foreignKey of table.foreignKeys) {
2223
+ if (foreignKey.constraint === false) continue;
2224
+ if (lookup && hasForeignKey(lookup, foreignKey)) continue;
2225
+ const fkName = foreignKey.name ?? `${tableName}_${foreignKey.columns.join("_")}_fkey`;
2226
+ operations.push({
2227
+ id: `foreignKey.${tableName}.${fkName}`,
2228
+ label: `Add foreign key ${fkName} on ${tableName}`,
2229
+ summary: `Adds foreign key ${fkName} referencing ${foreignKey.references.table}`,
2230
+ operationClass: "additive",
2231
+ target: {
2232
+ id: "postgres",
2233
+ details: this.buildTargetDetails("foreignKey", fkName, schemaName, tableName)
2234
+ },
2235
+ precheck: [{
2236
+ description: `ensure foreign key "${fkName}" is missing`,
2237
+ sql: constraintExistsCheck({
2238
+ constraintName: fkName,
2239
+ schema: schemaName,
2240
+ exists: false
2241
+ })
2242
+ }],
2243
+ execute: [{
2244
+ description: `add foreign key "${fkName}"`,
2245
+ sql: buildForeignKeySql(schemaName, tableName, fkName, foreignKey)
2246
+ }],
2247
+ postcheck: [{
2248
+ description: `verify foreign key "${fkName}" exists`,
2249
+ sql: constraintExistsCheck({
2250
+ constraintName: fkName,
2251
+ schema: schemaName
2252
+ })
2253
+ }]
2254
+ });
2255
+ }
2256
+ }
2257
+ return operations;
2258
+ }
2259
+ buildTargetDetails(objectType, name, schema, table) {
2260
+ return buildTargetDetails(objectType, name, schema, table);
2261
+ }
2262
+ resolvePlanningMode(policy) {
2263
+ const allowWidening = policy.allowedOperationClasses.includes("widening");
2264
+ const allowDestructive = policy.allowedOperationClasses.includes("destructive");
2265
+ return {
2266
+ includeExtraObjects: allowWidening || allowDestructive,
2267
+ allowWidening,
2268
+ allowDestructive
2269
+ };
2270
+ }
2271
+ collectSchemaIssues(options, strict) {
2272
+ return verifySqlSchema({
2273
+ contract: options.contract,
2274
+ schema: options.schema,
2275
+ strict,
2276
+ typeMetadataRegistry: /* @__PURE__ */ new Map(),
2277
+ frameworkComponents: options.frameworkComponents,
2278
+ normalizeDefault: parsePostgresDefault,
2279
+ normalizeNativeType: normalizeSchemaNativeType
2280
+ }).schema.issues;
2281
+ }
2282
+ };
2283
+ function isSqlDependencyProvider(component) {
2284
+ if (typeof component !== "object" || component === null) return false;
2285
+ const record = component;
2286
+ if (Object.hasOwn(record, "familyId") && record["familyId"] !== "sql") return false;
2287
+ if (!Object.hasOwn(record, "databaseDependencies")) return false;
2288
+ const deps = record["databaseDependencies"];
2289
+ return deps === void 0 || typeof deps === "object" && deps !== null;
2290
+ }
2291
+ function sortDependencies(dependencies) {
2292
+ if (dependencies.length <= 1) return dependencies;
2293
+ return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));
2294
+ }
2295
+ function buildCreateTableSql(qualifiedTableName, table) {
2296
+ const columnDefinitions = Object.entries(table.columns).map(([columnName, column]) => {
2297
+ return [
2298
+ quoteIdentifier(columnName),
2299
+ buildColumnTypeSql(column),
2300
+ buildColumnDefaultSql(column.default, column),
2301
+ column.nullable ? "" : "NOT NULL"
2302
+ ].filter(Boolean).join(" ");
2303
+ });
2304
+ const constraintDefinitions = [];
2305
+ if (table.primaryKey) constraintDefinitions.push(`PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(", ")})`);
2306
+ return `CREATE TABLE ${qualifiedTableName} (\n ${[...columnDefinitions, ...constraintDefinitions].join(",\n ")}\n)`;
2307
+ }
2308
+ /**
2309
+ * Pattern for safe PostgreSQL type names.
2310
+ * Allows letters, digits, underscores, spaces (for "double precision", "character varying"),
2311
+ * and trailing [] for array types.
2312
+ */
2313
+ const SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*(\[\])?$/;
2314
+ function assertSafeNativeType(nativeType) {
2315
+ if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) throw new Error(`Unsafe native type name in contract: "${nativeType}". Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*(\\[\\])?\$/`);
2316
+ }
2317
+ /**
2318
+ * Sanity check against accidental SQL injection from malformed contract files.
2319
+ * Rejects semicolons, SQL comment tokens, and dollar-quoting.
2320
+ * Not a comprehensive security boundary — the contract is developer-authored.
2321
+ */
2322
+ function assertSafeDefaultExpression(expression) {
2323
+ if (expression.includes(";") || /--|\/\*|\$\$|\bSELECT\b/i.test(expression)) throw new Error(`Unsafe default expression in contract: "${expression}". Default expressions must not contain semicolons, SQL comment tokens, dollar-quoting, or subqueries.`);
2324
+ }
2325
+ /**
2326
+ * Builds the column type SQL, handling autoincrement as a special case.
2327
+ * For autoincrement on int4/int8, we use SERIAL/BIGSERIAL types.
2328
+ */
2329
+ function buildColumnTypeSql(column) {
2330
+ const columnDefault = column.default;
2331
+ if (columnDefault?.kind === "function" && columnDefault.expression === "autoincrement()") {
2332
+ if (column.nativeType === "int4" || column.nativeType === "integer") return "SERIAL";
2333
+ if (column.nativeType === "int8" || column.nativeType === "bigint") return "BIGSERIAL";
2334
+ if (column.nativeType === "int2" || column.nativeType === "smallint") return "SMALLSERIAL";
2335
+ }
2336
+ if (column.typeRef) return quoteIdentifier(column.nativeType);
2337
+ assertSafeNativeType(column.nativeType);
2338
+ return renderParameterizedTypeSql(column) ?? column.nativeType;
2339
+ }
2340
+ /**
2341
+ * Renders parameterized type SQL for a column, returning null if no expansion is needed.
2342
+ *
2343
+ * Uses the shared expandParameterizedNativeType utility from the postgres adapter.
2344
+ * Returns null when the column has no typeParams, allowing the caller to fall back
2345
+ * to the base nativeType.
2346
+ */
2347
+ function renderParameterizedTypeSql(column) {
2348
+ if (!column.typeParams) return null;
2349
+ const expanded = expandParameterizedNativeType({
2350
+ nativeType: column.nativeType,
2351
+ codecId: column.codecId,
2352
+ typeParams: column.typeParams
2353
+ });
2354
+ return expanded !== column.nativeType ? expanded : null;
2355
+ }
2356
+ /**
2357
+ * Builds the DEFAULT clause for a column definition.
2358
+ * Returns empty string if no default is defined.
2359
+ *
2360
+ * Note: autoincrement is handled specially via SERIAL types, so we skip it here.
2361
+ */
2362
+ function buildColumnDefaultSql(columnDefault, column) {
2363
+ if (!columnDefault) return "";
2364
+ switch (columnDefault.kind) {
2365
+ case "literal": return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;
2366
+ case "function":
2367
+ if (columnDefault.expression === "autoincrement()") return "";
2368
+ assertSafeDefaultExpression(columnDefault.expression);
2369
+ return `DEFAULT (${columnDefault.expression})`;
2370
+ case "sequence": return `DEFAULT nextval(${quoteIdentifier(columnDefault.name)}::regclass)`;
2371
+ }
2372
+ }
2373
+ function renderDefaultLiteral(value, column) {
2374
+ const isJsonColumn = column?.nativeType === "json" || column?.nativeType === "jsonb";
2375
+ if (value instanceof Date) return `'${escapeLiteral(value.toISOString())}'`;
2376
+ if (!isJsonColumn && isTaggedBigInt(value)) {
2377
+ if (!/^-?\d+$/.test(value.value)) throw new Error(`Invalid tagged bigint value: "${value.value}" is not a valid integer`);
2378
+ return value.value;
2379
+ }
2380
+ if (typeof value === "bigint") return value.toString();
2381
+ if (typeof value === "string") return `'${escapeLiteral(value)}'`;
2382
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
2383
+ if (value === null) return "NULL";
2384
+ const json = JSON.stringify(value);
2385
+ if (isJsonColumn) return `'${escapeLiteral(json)}'::${column.nativeType}`;
2386
+ return `'${escapeLiteral(json)}'`;
2387
+ }
2388
+ function buildTargetDetails(objectType, name, schema, table) {
2389
+ return {
2390
+ schema,
2391
+ objectType,
2392
+ name,
2393
+ ...ifDefined("table", table)
2394
+ };
2395
+ }
2396
+ function qualifyTableName(schema, table) {
2397
+ return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;
2398
+ }
2399
+ function toRegclassLiteral(schema, name) {
2400
+ return `'${escapeLiteral(`${quoteIdentifier(schema)}.${quoteIdentifier(name)}`)}'`;
2401
+ }
2402
+ function sortedEntries(record) {
2403
+ return Object.entries(record).sort(([a], [b]) => a.localeCompare(b));
2404
+ }
2405
+ function constraintExistsCheck({ constraintName, schema, exists = true }) {
2406
+ return `SELECT ${exists ? "EXISTS" : "NOT EXISTS"} (
2407
+ SELECT 1 FROM pg_constraint c
2408
+ JOIN pg_namespace n ON c.connamespace = n.oid
2409
+ WHERE c.conname = '${escapeLiteral(constraintName)}'
2410
+ AND n.nspname = '${escapeLiteral(schema)}'
2411
+ )`;
2412
+ }
2413
+ function columnExistsCheck({ schema, table, column, exists = true }) {
2414
+ return `SELECT ${exists ? "" : "NOT "}EXISTS (
2415
+ SELECT 1
2416
+ FROM information_schema.columns
2417
+ WHERE table_schema = '${escapeLiteral(schema)}'
2418
+ AND table_name = '${escapeLiteral(table)}'
2419
+ AND column_name = '${escapeLiteral(column)}'
2420
+ )`;
2421
+ }
2422
+ function columnNullabilityCheck({ schema, table, column, nullable }) {
2423
+ const expected = nullable ? "YES" : "NO";
2424
+ return `SELECT EXISTS (
2425
+ SELECT 1
2426
+ FROM information_schema.columns
2427
+ WHERE table_schema = '${escapeLiteral(schema)}'
2428
+ AND table_name = '${escapeLiteral(table)}'
2429
+ AND column_name = '${escapeLiteral(column)}'
2430
+ AND is_nullable = '${expected}'
2431
+ )`;
2432
+ }
2433
+ function tableIsEmptyCheck(qualifiedTableName) {
2434
+ return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;
2435
+ }
2436
+ function buildAddColumnSql(qualifiedTableName, columnName, column) {
2437
+ const typeSql = buildColumnTypeSql(column);
2438
+ const defaultSql = buildColumnDefaultSql(column.default, column);
2439
+ return [
2440
+ `ALTER TABLE ${qualifiedTableName}`,
2441
+ `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,
2442
+ defaultSql,
2443
+ column.nullable ? "" : "NOT NULL"
2444
+ ].filter(Boolean).join(" ");
2445
+ }
2446
+ function tableHasPrimaryKeyCheck(schema, table, exists, constraintName) {
2447
+ const comparison = exists ? "" : "NOT ";
2448
+ const constraintFilter = constraintName ? `AND c2.relname = '${escapeLiteral(constraintName)}'` : "";
2449
+ return `SELECT ${comparison}EXISTS (
2450
+ SELECT 1
2451
+ FROM pg_index i
2452
+ JOIN pg_class c ON c.oid = i.indrelid
2453
+ JOIN pg_namespace n ON n.oid = c.relnamespace
2454
+ LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid
2455
+ WHERE n.nspname = '${escapeLiteral(schema)}'
2456
+ AND c.relname = '${escapeLiteral(table)}'
2457
+ AND i.indisprimary
2458
+ ${constraintFilter}
2459
+ )`;
2460
+ }
2461
+ function buildSchemaLookupMap(schema) {
2462
+ const map = /* @__PURE__ */ new Map();
2463
+ for (const [tableName, table] of Object.entries(schema.tables)) map.set(tableName, buildSchemaTableLookup(table));
2464
+ return map;
2465
+ }
2466
+ function buildSchemaTableLookup(table) {
2467
+ return {
2468
+ uniqueKeys: new Set(table.uniques.map((u) => u.columns.join(","))),
2469
+ indexKeys: new Set(table.indexes.map((i) => i.columns.join(","))),
2470
+ uniqueIndexKeys: new Set(table.indexes.filter((i) => i.unique).map((i) => i.columns.join(","))),
2471
+ fkKeys: new Set(table.foreignKeys.map((fk) => `${fk.columns.join(",")}|${fk.referencedTable}|${fk.referencedColumns.join(",")}`))
2472
+ };
2473
+ }
2474
+ function hasUniqueConstraint(lookup, columns) {
2475
+ const key = columns.join(",");
2476
+ return lookup.uniqueKeys.has(key) || lookup.uniqueIndexKeys.has(key);
2477
+ }
2478
+ function hasIndex(lookup, columns) {
2479
+ const key = columns.join(",");
2480
+ return lookup.indexKeys.has(key) || lookup.uniqueKeys.has(key);
2481
+ }
2482
+ function hasForeignKey(lookup, fk) {
2483
+ return lookup.fkKeys.has(`${fk.columns.join(",")}|${fk.references.table}|${fk.references.columns.join(",")}`);
2484
+ }
2485
+ const REFERENTIAL_ACTION_SQL = {
2486
+ noAction: "NO ACTION",
2487
+ restrict: "RESTRICT",
2488
+ cascade: "CASCADE",
2489
+ setNull: "SET NULL",
2490
+ setDefault: "SET DEFAULT"
2491
+ };
2492
+ function buildForeignKeySql(schemaName, tableName, fkName, foreignKey) {
2493
+ let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
2494
+ ADD CONSTRAINT ${quoteIdentifier(fkName)}
2495
+ FOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(", ")})
2496
+ REFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns.map(quoteIdentifier).join(", ")})`;
2497
+ if (foreignKey.onDelete !== void 0) {
2498
+ const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];
2499
+ if (!action) throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);
2500
+ sql += `\nON DELETE ${action}`;
2501
+ }
2502
+ if (foreignKey.onUpdate !== void 0) {
2503
+ const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];
2504
+ if (!action) throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);
2505
+ sql += `\nON UPDATE ${action}`;
2506
+ }
2507
+ return sql;
2508
+ }
2509
+
2510
+ //#endregion
2511
+ //#region src/core/migrations/statement-builders.ts
2512
+ const ensurePrismaContractSchemaStatement = {
2513
+ sql: "create schema if not exists prisma_contract",
2514
+ params: []
2515
+ };
2516
+ const ensureMarkerTableStatement = {
2517
+ sql: `create table if not exists prisma_contract.marker (
2518
+ id smallint primary key default 1,
2519
+ core_hash text not null,
2520
+ profile_hash text not null,
2521
+ contract_json jsonb,
2522
+ canonical_version int,
2523
+ updated_at timestamptz not null default now(),
2524
+ app_tag text,
2525
+ meta jsonb not null default '{}'
2526
+ )`,
2527
+ params: []
2528
+ };
2529
+ const ensureLedgerTableStatement = {
2530
+ sql: `create table if not exists prisma_contract.ledger (
2531
+ id bigserial primary key,
2532
+ created_at timestamptz not null default now(),
2533
+ origin_core_hash text,
2534
+ origin_profile_hash text,
2535
+ destination_core_hash text not null,
2536
+ destination_profile_hash text,
2537
+ contract_json_before jsonb,
2538
+ contract_json_after jsonb,
2539
+ operations jsonb not null
2540
+ )`,
2541
+ params: []
2542
+ };
2543
+ function buildWriteMarkerStatements(input) {
2544
+ const params = [
2545
+ 1,
2546
+ input.storageHash,
2547
+ input.profileHash,
2548
+ jsonParam(input.contractJson),
2549
+ input.canonicalVersion ?? null,
2550
+ input.appTag ?? null,
2551
+ jsonParam(input.meta ?? {})
2552
+ ];
2553
+ return {
2554
+ insert: {
2555
+ sql: `insert into prisma_contract.marker (
2556
+ id,
2557
+ core_hash,
2558
+ profile_hash,
2559
+ contract_json,
2560
+ canonical_version,
2561
+ updated_at,
2562
+ app_tag,
2563
+ meta
2564
+ ) values (
2565
+ $1,
2566
+ $2,
2567
+ $3,
2568
+ $4::jsonb,
2569
+ $5,
2570
+ now(),
2571
+ $6,
2572
+ $7::jsonb
2573
+ )`,
2574
+ params
2575
+ },
2576
+ update: {
2577
+ sql: `update prisma_contract.marker set
2578
+ core_hash = $2,
2579
+ profile_hash = $3,
2580
+ contract_json = $4::jsonb,
2581
+ canonical_version = $5,
2582
+ updated_at = now(),
2583
+ app_tag = $6,
2584
+ meta = $7::jsonb
2585
+ where id = $1`,
2586
+ params
2587
+ }
2588
+ };
2589
+ }
2590
+ function buildLedgerInsertStatement(input) {
2591
+ return {
2592
+ sql: `insert into prisma_contract.ledger (
2593
+ origin_core_hash,
2594
+ origin_profile_hash,
2595
+ destination_core_hash,
2596
+ destination_profile_hash,
2597
+ contract_json_before,
2598
+ contract_json_after,
2599
+ operations
2600
+ ) values (
2601
+ $1,
2602
+ $2,
2603
+ $3,
2604
+ $4,
2605
+ $5::jsonb,
2606
+ $6::jsonb,
2607
+ $7::jsonb
2608
+ )`,
2609
+ params: [
2610
+ input.originStorageHash ?? null,
2611
+ input.originProfileHash ?? null,
2612
+ input.destinationStorageHash,
2613
+ input.destinationProfileHash ?? null,
2614
+ jsonParam(input.contractJsonBefore),
2615
+ jsonParam(input.contractJsonAfter),
2616
+ jsonParam(input.operations)
2617
+ ]
2618
+ };
2619
+ }
2620
+ function jsonParam(value) {
2621
+ return JSON.stringify(value ?? null, bigintJsonReplacer);
2622
+ }
2623
+
2624
+ //#endregion
2625
+ //#region src/core/migrations/runner.ts
2626
+ const DEFAULT_CONFIG = { defaultSchema: "public" };
2627
+ const LOCK_DOMAIN = "prisma_next.contract.marker";
2628
+ /**
2629
+ * Deep clones and freezes a record object to prevent mutation.
2630
+ * Recursively clones nested objects and arrays to ensure complete isolation.
2631
+ */
2632
+ function cloneAndFreezeRecord(value) {
2633
+ const cloned = {};
2634
+ for (const [key, val] of Object.entries(value)) if (val === null || val === void 0) cloned[key] = val;
2635
+ else if (Array.isArray(val)) cloned[key] = Object.freeze([...val]);
2636
+ else if (typeof val === "object") cloned[key] = cloneAndFreezeRecord(val);
2637
+ else cloned[key] = val;
2638
+ return Object.freeze(cloned);
2639
+ }
2640
+ function createPostgresMigrationRunner(family, config = {}) {
2641
+ return new PostgresMigrationRunner(family, {
2642
+ ...DEFAULT_CONFIG,
2643
+ ...config
2644
+ });
2645
+ }
2646
+ var PostgresMigrationRunner = class {
2647
+ constructor(family, config) {
2648
+ this.family = family;
2649
+ this.config = config;
2650
+ }
2651
+ async execute(options) {
2652
+ const schema = options.schemaName ?? this.config.defaultSchema;
2653
+ const driver = options.driver;
2654
+ const lockKey = `${LOCK_DOMAIN}:${schema}`;
2655
+ const destinationCheck = this.ensurePlanMatchesDestinationContract(options.plan.destination, options.destinationContract);
2656
+ if (!destinationCheck.ok) return destinationCheck;
2657
+ const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
2658
+ if (!policyCheck.ok) return policyCheck;
2659
+ await this.beginTransaction(driver);
2660
+ let committed = false;
2661
+ try {
2662
+ await this.acquireLock(driver, lockKey);
2663
+ await this.ensureControlTables(driver);
2664
+ const existingMarker = await readMarker(driver);
2665
+ const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
2666
+ if (!markerCheck.ok) return markerCheck;
2667
+ const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
2668
+ let applyValue;
2669
+ if (markerAtDestination) applyValue = {
2670
+ operationsExecuted: 0,
2671
+ executedOperations: []
2672
+ };
2673
+ else {
2674
+ const applyResult = await this.applyPlan(driver, options);
2675
+ if (!applyResult.ok) return applyResult;
2676
+ applyValue = applyResult.value;
2677
+ }
2678
+ const schemaIR = await this.family.introspect({
2679
+ driver,
2680
+ contractIR: options.destinationContract
2681
+ });
2682
+ const schemaVerifyResult = verifySqlSchema({
2683
+ contract: options.destinationContract,
2684
+ schema: schemaIR,
2685
+ strict: options.strictVerification ?? true,
2686
+ context: options.context ?? {},
2687
+ typeMetadataRegistry: this.family.typeMetadataRegistry,
2688
+ frameworkComponents: options.frameworkComponents,
2689
+ normalizeDefault: parsePostgresDefault,
2690
+ normalizeNativeType: normalizeSchemaNativeType
2691
+ });
2692
+ if (!schemaVerifyResult.ok) return runnerFailure("SCHEMA_VERIFY_FAILED", schemaVerifyResult.summary, {
2693
+ why: "The resulting database schema does not satisfy the destination contract.",
2694
+ meta: { issues: schemaVerifyResult.schema.issues }
2695
+ });
2696
+ await this.upsertMarker(driver, options, existingMarker);
2697
+ await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);
2698
+ await this.commitTransaction(driver);
2699
+ committed = true;
2700
+ return runnerSuccess({
2701
+ operationsPlanned: options.plan.operations.length,
2702
+ operationsExecuted: applyValue.operationsExecuted
2703
+ });
2704
+ } finally {
2705
+ if (!committed) await this.rollbackTransaction(driver);
2706
+ }
2707
+ }
2708
+ async applyPlan(driver, options) {
2709
+ const checks = options.executionChecks;
2710
+ const runPrechecks = checks?.prechecks !== false;
2711
+ const runPostchecks = checks?.postchecks !== false;
2712
+ const runIdempotency = checks?.idempotencyChecks !== false;
2713
+ let operationsExecuted = 0;
2714
+ const executedOperations = [];
2715
+ for (const operation of options.plan.operations) {
2716
+ options.callbacks?.onOperationStart?.(operation);
2717
+ try {
2718
+ if (runPostchecks && runIdempotency) {
2719
+ if (await this.expectationsAreSatisfied(driver, operation.postcheck)) {
2720
+ executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));
2721
+ continue;
2722
+ }
2723
+ }
2724
+ if (runPrechecks) {
2725
+ const precheckResult = await this.runExpectationSteps(driver, operation.precheck, operation, "precheck");
2726
+ if (!precheckResult.ok) return precheckResult;
2727
+ }
2728
+ const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);
2729
+ if (!executeResult.ok) return executeResult;
2730
+ if (runPostchecks) {
2731
+ const postcheckResult = await this.runExpectationSteps(driver, operation.postcheck, operation, "postcheck");
2732
+ if (!postcheckResult.ok) return postcheckResult;
2733
+ }
2734
+ executedOperations.push(operation);
2735
+ operationsExecuted += 1;
2736
+ } finally {
2737
+ options.callbacks?.onOperationComplete?.(operation);
2738
+ }
2739
+ }
2740
+ return ok({
2741
+ operationsExecuted,
2742
+ executedOperations
2743
+ });
2744
+ }
2745
+ async ensureControlTables(driver) {
2746
+ await this.executeStatement(driver, ensurePrismaContractSchemaStatement);
2747
+ await this.executeStatement(driver, ensureMarkerTableStatement);
2748
+ await this.executeStatement(driver, ensureLedgerTableStatement);
2749
+ }
2750
+ async runExpectationSteps(driver, steps, operation, phase) {
2751
+ for (const step of steps) {
2752
+ const result = await driver.query(step.sql);
2753
+ if (!this.stepResultIsTrue(result.rows)) return runnerFailure(phase === "precheck" ? "PRECHECK_FAILED" : "POSTCHECK_FAILED", `Operation ${operation.id} failed during ${phase}: ${step.description}`, { meta: {
2754
+ operationId: operation.id,
2755
+ phase,
2756
+ stepDescription: step.description
2757
+ } });
2758
+ }
2759
+ return okVoid();
2760
+ }
2761
+ async runExecuteSteps(driver, steps, operation) {
2762
+ for (const step of steps) try {
2763
+ await driver.query(step.sql);
2764
+ } catch (error) {
2765
+ if (SqlQueryError.is(error)) return runnerFailure("EXECUTION_FAILED", `Operation ${operation.id} failed during execution: ${step.description}`, {
2766
+ why: error.message,
2767
+ meta: {
2768
+ operationId: operation.id,
2769
+ stepDescription: step.description,
2770
+ sql: step.sql,
2771
+ sqlState: error.sqlState,
2772
+ constraint: error.constraint,
2773
+ table: error.table,
2774
+ column: error.column,
2775
+ detail: error.detail
2776
+ }
2777
+ });
2778
+ throw error;
2779
+ }
2780
+ return okVoid();
2781
+ }
2782
+ stepResultIsTrue(rows) {
2783
+ if (!rows || rows.length === 0) return false;
2784
+ const firstRow = rows[0];
2785
+ const firstValue = firstRow ? Object.values(firstRow)[0] : void 0;
2786
+ if (typeof firstValue === "boolean") return firstValue;
2787
+ if (typeof firstValue === "number") return firstValue !== 0;
2788
+ if (typeof firstValue === "string") {
2789
+ const lower = firstValue.toLowerCase();
2790
+ if (lower === "t" || lower === "true" || lower === "1") return true;
2791
+ if (lower === "f" || lower === "false" || lower === "0") return false;
2792
+ return firstValue.length > 0;
2793
+ }
2794
+ return Boolean(firstValue);
2795
+ }
2796
+ async expectationsAreSatisfied(driver, steps) {
2797
+ if (steps.length === 0) return false;
2798
+ for (const step of steps) {
2799
+ const result = await driver.query(step.sql);
2800
+ if (!this.stepResultIsTrue(result.rows)) return false;
2801
+ }
2802
+ return true;
2803
+ }
2804
+ createPostcheckPreSatisfiedSkipRecord(operation) {
2805
+ const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : void 0;
2806
+ const runnerMeta = Object.freeze({
2807
+ skipped: true,
2808
+ reason: "postcheck_pre_satisfied"
2809
+ });
2810
+ const mergedMeta = Object.freeze({
2811
+ ...clonedMeta ?? {},
2812
+ runner: runnerMeta
2813
+ });
2814
+ const frozenPostcheck = Object.freeze([...operation.postcheck]);
2815
+ return Object.freeze({
2816
+ id: operation.id,
2817
+ label: operation.label,
2818
+ ...ifDefined("summary", operation.summary),
2819
+ operationClass: operation.operationClass,
2820
+ target: operation.target,
2821
+ precheck: Object.freeze([]),
2822
+ execute: Object.freeze([]),
2823
+ postcheck: frozenPostcheck,
2824
+ ...ifDefined("meta", operation.meta || mergedMeta ? mergedMeta : void 0)
2825
+ });
2826
+ }
2827
+ markerMatchesDestination(marker, plan) {
2828
+ if (!marker) return false;
2829
+ if (marker.storageHash !== plan.destination.storageHash) return false;
2830
+ if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) return false;
2831
+ return true;
2832
+ }
2833
+ enforcePolicyCompatibility(policy, operations) {
2834
+ const allowedClasses = new Set(policy.allowedOperationClasses);
2835
+ for (const operation of operations) if (!allowedClasses.has(operation.operationClass)) return runnerFailure("POLICY_VIOLATION", `Operation ${operation.id} has class "${operation.operationClass}" which is not allowed by policy.`, {
2836
+ why: `Policy only allows: ${policy.allowedOperationClasses.join(", ")}.`,
2837
+ meta: {
2838
+ operationId: operation.id,
2839
+ operationClass: operation.operationClass,
2840
+ allowedClasses: policy.allowedOperationClasses
2841
+ }
2842
+ });
2843
+ return okVoid();
2844
+ }
2845
+ ensureMarkerCompatibility(marker, plan) {
2846
+ const origin = plan.origin ?? null;
2847
+ if (!origin) return okVoid();
2848
+ if (!marker) return runnerFailure("MARKER_ORIGIN_MISMATCH", `Missing contract marker: expected origin storage hash ${origin.storageHash}.`, { meta: { expectedOriginStorageHash: origin.storageHash } });
2849
+ if (marker.storageHash !== origin.storageHash) return runnerFailure("MARKER_ORIGIN_MISMATCH", `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`, { meta: {
2850
+ markerStorageHash: marker.storageHash,
2851
+ expectedOriginStorageHash: origin.storageHash
2852
+ } });
2853
+ if (origin.profileHash && marker.profileHash !== origin.profileHash) return runnerFailure("MARKER_ORIGIN_MISMATCH", `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`, { meta: {
2854
+ markerProfileHash: marker.profileHash,
2855
+ expectedOriginProfileHash: origin.profileHash
2856
+ } });
2857
+ return okVoid();
2858
+ }
2859
+ ensurePlanMatchesDestinationContract(destination, contract) {
2860
+ if (destination.storageHash !== contract.storageHash) return runnerFailure("DESTINATION_CONTRACT_MISMATCH", `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storageHash}).`, { meta: {
2861
+ planStorageHash: destination.storageHash,
2862
+ contractStorageHash: contract.storageHash
2863
+ } });
2864
+ if (destination.profileHash && contract.profileHash && destination.profileHash !== contract.profileHash) return runnerFailure("DESTINATION_CONTRACT_MISMATCH", `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`, { meta: {
2865
+ planProfileHash: destination.profileHash,
2866
+ contractProfileHash: contract.profileHash
2867
+ } });
2868
+ return okVoid();
2869
+ }
2870
+ async upsertMarker(driver, options, existingMarker) {
2871
+ const writeStatements = buildWriteMarkerStatements({
2872
+ storageHash: options.plan.destination.storageHash,
2873
+ profileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
2874
+ contractJson: options.destinationContract,
2875
+ canonicalVersion: null,
2876
+ meta: {}
2877
+ });
2878
+ const statement = existingMarker ? writeStatements.update : writeStatements.insert;
2879
+ await this.executeStatement(driver, statement);
2880
+ }
2881
+ async recordLedgerEntry(driver, options, existingMarker, executedOperations) {
2882
+ const ledgerStatement = buildLedgerInsertStatement({
2883
+ originStorageHash: existingMarker?.storageHash ?? null,
2884
+ originProfileHash: existingMarker?.profileHash ?? null,
2885
+ destinationStorageHash: options.plan.destination.storageHash,
2886
+ destinationProfileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
2887
+ contractJsonBefore: existingMarker?.contractJson ?? null,
2888
+ contractJsonAfter: options.destinationContract,
2889
+ operations: executedOperations
2890
+ });
2891
+ await this.executeStatement(driver, ledgerStatement);
2892
+ }
2893
+ async acquireLock(driver, key) {
2894
+ await driver.query("select pg_advisory_xact_lock(hashtext($1))", [key]);
2895
+ }
2896
+ async beginTransaction(driver) {
2897
+ await driver.query("BEGIN");
2898
+ }
2899
+ async commitTransaction(driver) {
2900
+ await driver.query("COMMIT");
2901
+ }
2902
+ async rollbackTransaction(driver) {
2903
+ await driver.query("ROLLBACK");
2904
+ }
2905
+ async executeStatement(driver, statement) {
2906
+ if (statement.params.length > 0) {
2907
+ await driver.query(statement.sql, statement.params);
2908
+ return;
2909
+ }
2910
+ await driver.query(statement.sql);
2911
+ }
2912
+ };
2913
+
2914
+ //#endregion
2915
+ //#region src/exports/control.ts
2916
+ const postgresTargetDescriptor = {
2917
+ ...postgresTargetDescriptorMeta,
2918
+ operationSignatures: () => [],
2919
+ migrations: {
2920
+ createPlanner(_family) {
2921
+ return createPostgresMigrationPlanner();
2922
+ },
2923
+ createRunner(family) {
2924
+ return createPostgresMigrationRunner(family);
2925
+ },
2926
+ contractToSchema(contract) {
2927
+ return contractToSchemaIR(contract ? contract.storage : { tables: {} }, expandParameterizedNativeType);
2928
+ }
2929
+ },
2930
+ create() {
2931
+ return {
2932
+ familyId: "sql",
2933
+ targetId: "postgres"
2934
+ };
2935
+ },
2936
+ createPlanner(_family) {
2937
+ return createPostgresMigrationPlanner();
2938
+ },
2939
+ createRunner(family) {
2940
+ return createPostgresMigrationRunner(family);
2941
+ }
2942
+ };
2943
+ var control_default = postgresTargetDescriptor;
2944
+
2945
+ //#endregion
2946
+ export { control_default as default };
2947
+ //# sourceMappingURL=control.mjs.map