@prisma-next/target-postgres 0.3.0-dev.10 → 0.3.0-dev.113

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