@prisma-next/target-postgres 0.3.0-dev.41 → 0.3.0-dev.43

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.
package/README.md CHANGED
@@ -34,7 +34,7 @@ This package spans multiple planes:
34
34
 
35
35
  This package provides the Postgres implementation of the SQL migration planner/runner used by `prisma-next db init`:
36
36
 
37
- - **Planner** (`src/core/migrations/planner.ts`): produces an additive-only `MigrationPlan` to bring the database schema in line with a destination contract. Extra unrelated schema is tolerated; non-additive mismatches (type/nullability/constraint incompatibilities) surface as structured conflicts. Storage type operations (from codec-owned hooks) are emitted before table operations when `storage.types` are present. The planner respects the contract's `foreignKeys` configuration: when `foreignKeys.constraints` is `false`, FK constraint operations are skipped; when `foreignKeys.indexes` is `false`, FK-backing indexes are omitted. See [ADR 161](../../../docs/architecture%20docs/adrs/ADR%20161%20-%20Explicit%20foreign%20key%20constraint%20and%20index%20configuration.md).
37
+ - **Planner** (`src/core/migrations/planner.ts`): produces an additive-only `MigrationPlan` to bring the database schema in line with a destination contract. Extra unrelated schema is tolerated; non-additive mismatches (type/nullability/constraint incompatibilities) surface as structured conflicts. Storage type operations (from codec-owned hooks) are emitted before table operations when `storage.types` are present. The planner respects the contract's `foreignKeys` configuration: when `foreignKeys.constraints` is `false`, FK constraint operations are skipped; when `foreignKeys.indexes` is `false`, FK-backing indexes are omitted. See [ADR 161](../../../docs/architecture%20docs/adrs/ADR%20161%20-%20Explicit%20foreign%20key%20constraint%20and%20index%20configuration.md). The planner also emits `ON DELETE` and `ON UPDATE` referential action clauses when specified on foreign keys (see [ADR 162](../../../docs/architecture%20docs/adrs/ADR%20162%20-%20Referential%20actions%20for%20foreign%20keys.md)).
38
38
  - **Runner** (`src/core/migrations/runner.ts`): executes a plan under an advisory lock, verifies the post-state schema, then writes the contract marker and appends a ledger entry in the `prisma_contract` schema.
39
39
 
40
40
  For the CLI orchestration, see `packages/1-framework/3-tooling/cli/src/commands/db-init.ts`.
@@ -154,6 +154,7 @@ This package ships a mix of fast planner unit tests and slower runner integratio
154
154
  - **Test files**:
155
155
  - `test/migrations/planner.behavior.test.ts`: Planner unit tests (classification, conflicts, dependency ops)
156
156
  - `test/migrations/planner.fk-config.test.ts`: Planner unit tests for FK constraint/index configuration combinations
157
+ - `test/migrations/planner.referential-actions.test.ts`: Planner unit tests for ON DELETE/ON UPDATE DDL emission
157
158
  - `test/migrations/planner.integration.test.ts`: Planner integration tests
158
159
  - `test/migrations/runner.*.integration.test.ts`: Runner integration tests (basic, errors, idempotency, policy)
159
160
 
@@ -1 +1 @@
1
- {"version":3,"file":"control.d.mts","names":[],"sources":["../src/core/migrations/planner.ts","../src/exports/control.ts"],"sourcesContent":[],"mappings":";;;KAwCK,cAAA;UAuBY,yBAAA;EAvBZ,SAAA,MAAA,EAAc,MAAA;EAuBF,SAAA,UAAA,EAEM,cAFmB;;;;;;cCjDpC,0BAA0B,uCAAuC"}
1
+ {"version":3,"file":"control.d.mts","names":[],"sources":["../src/core/migrations/planner.ts","../src/exports/control.ts"],"sourcesContent":[],"mappings":";;;KAyCK,cAAA;UAuBY,yBAAA;EAvBZ,SAAA,MAAA,EAAc,MAAA;EAuBF,SAAA,UAAA,EAEM,cAFmB;;;;;;cClDpC,0BAA0B,uCAAuC"}
package/dist/control.mjs CHANGED
@@ -8,31 +8,6 @@ import { readMarker } from "@prisma-next/family-sql/verify";
8
8
  import { SqlQueryError } from "@prisma-next/sql-errors";
9
9
  import { ok, okVoid } from "@prisma-next/utils/result";
10
10
 
11
- //#region ../../6-adapters/postgres/dist/codec-ids-Bsm9c7ns.mjs
12
- const PG_TEXT_CODEC_ID = "pg/text@1";
13
- const PG_ENUM_CODEC_ID = "pg/enum@1";
14
- const PG_CHAR_CODEC_ID = "pg/char@1";
15
- const PG_VARCHAR_CODEC_ID = "pg/varchar@1";
16
- const PG_INT_CODEC_ID = "pg/int@1";
17
- const PG_INT2_CODEC_ID = "pg/int2@1";
18
- const PG_INT4_CODEC_ID = "pg/int4@1";
19
- const PG_INT8_CODEC_ID = "pg/int8@1";
20
- const PG_FLOAT_CODEC_ID = "pg/float@1";
21
- const PG_FLOAT4_CODEC_ID = "pg/float4@1";
22
- const PG_FLOAT8_CODEC_ID = "pg/float8@1";
23
- const PG_NUMERIC_CODEC_ID = "pg/numeric@1";
24
- const PG_BOOL_CODEC_ID = "pg/bool@1";
25
- const PG_BIT_CODEC_ID = "pg/bit@1";
26
- const PG_VARBIT_CODEC_ID = "pg/varbit@1";
27
- const PG_TIMESTAMP_CODEC_ID = "pg/timestamp@1";
28
- const PG_TIMESTAMPTZ_CODEC_ID = "pg/timestamptz@1";
29
- const PG_TIME_CODEC_ID = "pg/time@1";
30
- const PG_TIMETZ_CODEC_ID = "pg/timetz@1";
31
- const PG_INTERVAL_CODEC_ID = "pg/interval@1";
32
- const PG_JSON_CODEC_ID = "pg/json@1";
33
- const PG_JSONB_CODEC_ID = "pg/jsonb@1";
34
-
35
- //#endregion
36
11
  //#region ../../6-adapters/postgres/dist/sql-utils-CSfAGEwF.mjs
37
12
  /**
38
13
  * Shared SQL utility functions for the Postgres adapter.
@@ -108,6 +83,31 @@ function validateEnumValueLength(value, enumTypeName) {
108
83
  if (value.length > MAX_IDENTIFIER_LENGTH$1) throw new SqlEscapeError(`Enum value "${value.slice(0, 20)}..." for type "${enumTypeName}" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH$1}-character label limit`, value, "literal");
109
84
  }
110
85
 
86
+ //#endregion
87
+ //#region ../../6-adapters/postgres/dist/codec-ids-Bsm9c7ns.mjs
88
+ const PG_TEXT_CODEC_ID = "pg/text@1";
89
+ const PG_ENUM_CODEC_ID = "pg/enum@1";
90
+ const PG_CHAR_CODEC_ID = "pg/char@1";
91
+ const PG_VARCHAR_CODEC_ID = "pg/varchar@1";
92
+ const PG_INT_CODEC_ID = "pg/int@1";
93
+ const PG_INT2_CODEC_ID = "pg/int2@1";
94
+ const PG_INT4_CODEC_ID = "pg/int4@1";
95
+ const PG_INT8_CODEC_ID = "pg/int8@1";
96
+ const PG_FLOAT_CODEC_ID = "pg/float@1";
97
+ const PG_FLOAT4_CODEC_ID = "pg/float4@1";
98
+ const PG_FLOAT8_CODEC_ID = "pg/float8@1";
99
+ const PG_NUMERIC_CODEC_ID = "pg/numeric@1";
100
+ const PG_BOOL_CODEC_ID = "pg/bool@1";
101
+ const PG_BIT_CODEC_ID = "pg/bit@1";
102
+ const PG_VARBIT_CODEC_ID = "pg/varbit@1";
103
+ const PG_TIMESTAMP_CODEC_ID = "pg/timestamp@1";
104
+ const PG_TIMESTAMPTZ_CODEC_ID = "pg/timestamptz@1";
105
+ const PG_TIME_CODEC_ID = "pg/time@1";
106
+ const PG_TIMETZ_CODEC_ID = "pg/timetz@1";
107
+ const PG_INTERVAL_CODEC_ID = "pg/interval@1";
108
+ const PG_JSON_CODEC_ID = "pg/json@1";
109
+ const PG_JSONB_CODEC_ID = "pg/jsonb@1";
110
+
111
111
  //#endregion
112
112
  //#region ../../6-adapters/postgres/dist/descriptor-meta-ilnFI7bx.mjs
113
113
  const ENUM_INTROSPECT_QUERY = `
@@ -1184,17 +1184,31 @@ var PostgresControlAdapter = class {
1184
1184
  tc.constraint_name,
1185
1185
  kcu.column_name,
1186
1186
  kcu.ordinal_position,
1187
- ccu.table_schema AS referenced_table_schema,
1188
- ccu.table_name AS referenced_table_name,
1189
- ccu.column_name AS referenced_column_name
1187
+ ref_ns.nspname AS referenced_table_schema,
1188
+ ref_cl.relname AS referenced_table_name,
1189
+ ref_att.attname AS referenced_column_name,
1190
+ rc.delete_rule,
1191
+ rc.update_rule
1190
1192
  FROM information_schema.table_constraints tc
1191
1193
  JOIN information_schema.key_column_usage kcu
1192
1194
  ON tc.constraint_name = kcu.constraint_name
1193
1195
  AND tc.table_schema = kcu.table_schema
1194
1196
  AND tc.table_name = kcu.table_name
1195
- JOIN information_schema.constraint_column_usage ccu
1196
- ON ccu.constraint_name = tc.constraint_name
1197
- AND ccu.table_schema = tc.table_schema
1197
+ JOIN pg_catalog.pg_constraint pgc
1198
+ ON pgc.conname = tc.constraint_name
1199
+ AND pgc.connamespace = (
1200
+ SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema
1201
+ )
1202
+ JOIN pg_catalog.pg_class ref_cl
1203
+ ON ref_cl.oid = pgc.confrelid
1204
+ JOIN pg_catalog.pg_namespace ref_ns
1205
+ ON ref_ns.oid = ref_cl.relnamespace
1206
+ JOIN pg_catalog.pg_attribute ref_att
1207
+ ON ref_att.attrelid = pgc.confrelid
1208
+ AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]
1209
+ JOIN information_schema.referential_constraints rc
1210
+ ON rc.constraint_name = tc.constraint_name
1211
+ AND rc.constraint_schema = tc.table_schema
1198
1212
  WHERE tc.table_schema = $1
1199
1213
  AND tc.constraint_type = 'FOREIGN KEY'
1200
1214
  ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),
@@ -1288,14 +1302,18 @@ var PostgresControlAdapter = class {
1288
1302
  columns: [fkRow.column_name],
1289
1303
  referencedTable: fkRow.referenced_table_name,
1290
1304
  referencedColumns: [fkRow.referenced_column_name],
1291
- name: fkRow.constraint_name
1305
+ name: fkRow.constraint_name,
1306
+ deleteRule: fkRow.delete_rule,
1307
+ updateRule: fkRow.update_rule
1292
1308
  });
1293
1309
  }
1294
1310
  const foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({
1295
1311
  columns: Object.freeze([...fk.columns]),
1296
1312
  referencedTable: fk.referencedTable,
1297
1313
  referencedColumns: Object.freeze([...fk.referencedColumns]),
1298
- name: fk.name
1314
+ name: fk.name,
1315
+ ...ifDefined("onDelete", mapReferentialAction(fk.deleteRule)),
1316
+ ...ifDefined("onUpdate", mapReferentialAction(fk.updateRule))
1299
1317
  }));
1300
1318
  const pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();
1301
1319
  const uniquesMap = /* @__PURE__ */ new Map();
@@ -1402,6 +1420,24 @@ function normalizeFormattedType(formattedType, dataType, udtName) {
1402
1420
  if (formattedType.startsWith("\"") && formattedType.endsWith("\"")) return formattedType.slice(1, -1);
1403
1421
  return formattedType;
1404
1422
  }
1423
+ const PG_REFERENTIAL_ACTION_MAP = {
1424
+ "NO ACTION": "noAction",
1425
+ RESTRICT: "restrict",
1426
+ CASCADE: "cascade",
1427
+ "SET NULL": "setNull",
1428
+ "SET DEFAULT": "setDefault"
1429
+ };
1430
+ /**
1431
+ * Maps a Postgres referential action rule to the canonical SqlReferentialAction.
1432
+ * Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.
1433
+ * Throws for unrecognized rules to prevent silent data loss.
1434
+ */
1435
+ function mapReferentialAction(rule) {
1436
+ const mapped = PG_REFERENTIAL_ACTION_MAP[rule];
1437
+ if (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: "${rule}". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);
1438
+ if (mapped === "noAction") return void 0;
1439
+ return mapped;
1440
+ }
1405
1441
  /**
1406
1442
  * Groups an array of objects by a specified key.
1407
1443
  * Returns a Map for O(1) lookup by group key.
@@ -1806,10 +1842,7 @@ UNIQUE (${unique.columns.map(quoteIdentifier).join(", ")})`
1806
1842
  }],
1807
1843
  execute: [{
1808
1844
  description: `add foreign key "${fkName}"`,
1809
- sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
1810
- ADD CONSTRAINT ${quoteIdentifier(fkName)}
1811
- FOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(", ")})
1812
- REFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns.map(quoteIdentifier).join(", ")})`
1845
+ sql: buildForeignKeySql(schemaName, tableName, fkName, foreignKey)
1813
1846
  }],
1814
1847
  postcheck: [{
1815
1848
  description: `verify foreign key "${fkName}" exists`,
@@ -2088,6 +2121,30 @@ function compareStrings(a, b) {
2088
2121
  if (b === void 0) return 1;
2089
2122
  return a < b ? -1 : 1;
2090
2123
  }
2124
+ const REFERENTIAL_ACTION_SQL = {
2125
+ noAction: "NO ACTION",
2126
+ restrict: "RESTRICT",
2127
+ cascade: "CASCADE",
2128
+ setNull: "SET NULL",
2129
+ setDefault: "SET DEFAULT"
2130
+ };
2131
+ function buildForeignKeySql(schemaName, tableName, fkName, foreignKey) {
2132
+ let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
2133
+ ADD CONSTRAINT ${quoteIdentifier(fkName)}
2134
+ FOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(", ")})
2135
+ REFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns.map(quoteIdentifier).join(", ")})`;
2136
+ if (foreignKey.onDelete !== void 0) {
2137
+ const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];
2138
+ if (!action) throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);
2139
+ sql += `\nON DELETE ${action}`;
2140
+ }
2141
+ if (foreignKey.onUpdate !== void 0) {
2142
+ const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];
2143
+ if (!action) throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);
2144
+ sql += `\nON UPDATE ${action}`;
2145
+ }
2146
+ return sql;
2147
+ }
2091
2148
 
2092
2149
  //#endregion
2093
2150
  //#region src/core/migrations/statement-builders.ts
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":["MAX_IDENTIFIER_LENGTH","control_default","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","deps: PlannerDatabaseDependency[]","constraintDefinitions: string[]","location: {\n table?: string;\n column?: string;\n constraint?: string;\n }","ensurePrismaContractSchemaStatement: SqlStatement","ensureMarkerTableStatement: SqlStatement","ensureLedgerTableStatement: SqlStatement","params: readonly unknown[]","DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../../../6-adapters/postgres/dist/codec-ids-Bsm9c7ns.mjs","../../../6-adapters/postgres/dist/sql-utils-CSfAGEwF.mjs","../../../6-adapters/postgres/dist/descriptor-meta-ilnFI7bx.mjs","../../../6-adapters/postgres/dist/control.mjs","../src/core/migrations/planner.ts","../src/core/migrations/statement-builders.ts","../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import { SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_VARCHAR_CODEC_ID } from \"@prisma-next/sql-relational-core/ast\";\n\n//#region src/core/codec-ids.ts\nconst PG_TEXT_CODEC_ID = \"pg/text@1\";\nconst PG_ENUM_CODEC_ID = \"pg/enum@1\";\nconst PG_CHAR_CODEC_ID = \"pg/char@1\";\nconst PG_VARCHAR_CODEC_ID = \"pg/varchar@1\";\nconst PG_INT_CODEC_ID = \"pg/int@1\";\nconst PG_INT2_CODEC_ID = \"pg/int2@1\";\nconst PG_INT4_CODEC_ID = \"pg/int4@1\";\nconst PG_INT8_CODEC_ID = \"pg/int8@1\";\nconst PG_FLOAT_CODEC_ID = \"pg/float@1\";\nconst PG_FLOAT4_CODEC_ID = \"pg/float4@1\";\nconst PG_FLOAT8_CODEC_ID = \"pg/float8@1\";\nconst PG_NUMERIC_CODEC_ID = \"pg/numeric@1\";\nconst PG_BOOL_CODEC_ID = \"pg/bool@1\";\nconst PG_BIT_CODEC_ID = \"pg/bit@1\";\nconst PG_VARBIT_CODEC_ID = \"pg/varbit@1\";\nconst PG_TIMESTAMP_CODEC_ID = \"pg/timestamp@1\";\nconst PG_TIMESTAMPTZ_CODEC_ID = \"pg/timestamptz@1\";\nconst PG_TIME_CODEC_ID = \"pg/time@1\";\nconst PG_TIMETZ_CODEC_ID = \"pg/timetz@1\";\nconst PG_INTERVAL_CODEC_ID = \"pg/interval@1\";\nconst PG_JSON_CODEC_ID = \"pg/json@1\";\nconst PG_JSONB_CODEC_ID = \"pg/jsonb@1\";\n\n//#endregion\nexport { SQL_CHAR_CODEC_ID as C, SQL_VARCHAR_CODEC_ID as E, PG_VARCHAR_CODEC_ID as S, SQL_INT_CODEC_ID as T, PG_TIMESTAMPTZ_CODEC_ID as _, PG_FLOAT4_CODEC_ID as a, PG_TIME_CODEC_ID as b, PG_INT2_CODEC_ID as c, PG_INTERVAL_CODEC_ID as d, PG_INT_CODEC_ID as f, PG_TEXT_CODEC_ID as g, PG_NUMERIC_CODEC_ID as h, PG_ENUM_CODEC_ID as i, PG_INT4_CODEC_ID as l, PG_JSON_CODEC_ID as m, PG_BOOL_CODEC_ID as n, PG_FLOAT8_CODEC_ID as o, PG_JSONB_CODEC_ID as p, PG_CHAR_CODEC_ID as r, PG_FLOAT_CODEC_ID as s, PG_BIT_CODEC_ID as t, PG_INT8_CODEC_ID as u, PG_TIMESTAMP_CODEC_ID as v, SQL_FLOAT_CODEC_ID as w, PG_VARBIT_CODEC_ID as x, PG_TIMETZ_CODEC_ID as y };\n//# sourceMappingURL=codec-ids-Bsm9c7ns.mjs.map","//#region src/core/sql-utils.ts\n/**\n* Shared SQL utility functions for the Postgres adapter.\n*\n* These functions handle safe SQL identifier and literal escaping\n* with security validations to prevent injection and encoding issues.\n*/\n/**\n* Error thrown when an invalid SQL identifier or literal is detected.\n* Boundary layers map this to structured envelopes.\n*/\nvar SqlEscapeError = class extends Error {\n\tconstructor(message, value, kind) {\n\t\tsuper(message);\n\t\tthis.value = value;\n\t\tthis.kind = kind;\n\t\tthis.name = \"SqlEscapeError\";\n\t}\n};\n/**\n* Maximum length for PostgreSQL identifiers (NAMEDATALEN - 1).\n*/\nconst MAX_IDENTIFIER_LENGTH = 63;\n/**\n* Validates and quotes a PostgreSQL identifier (table, column, type, schema names).\n*\n* Security validations:\n* - Rejects null bytes which could cause truncation or unexpected behavior\n* - Rejects empty identifiers\n* - Warns on identifiers exceeding PostgreSQL's 63-character limit\n*\n* @throws {SqlEscapeError} If the identifier contains null bytes or is empty\n*/\nfunction quoteIdentifier(identifier) {\n\tif (identifier.length === 0) throw new SqlEscapeError(\"Identifier cannot be empty\", identifier, \"identifier\");\n\tif (identifier.includes(\"\\0\")) throw new SqlEscapeError(\"Identifier cannot contain null bytes\", identifier.replace(/\\0/g, \"\\\\0\"), \"identifier\");\n\tif (identifier.length > MAX_IDENTIFIER_LENGTH) console.warn(`Identifier \"${identifier.slice(0, 20)}...\" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character limit and will be truncated`);\n\treturn `\"${identifier.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n/**\n* Escapes a string literal for safe use in SQL statements.\n*\n* Security validations:\n* - Rejects null bytes which could cause truncation or unexpected behavior\n*\n* Note: This assumes PostgreSQL's `standard_conforming_strings` is ON (default since PG 9.1).\n* Backslashes are treated as literal characters, not escape sequences.\n*\n* @throws {SqlEscapeError} If the value contains null bytes\n*/\nfunction escapeLiteral(value) {\n\tif (value.includes(\"\\0\")) throw new SqlEscapeError(\"Literal value cannot contain null bytes\", value.replace(/\\0/g, \"\\\\0\"), \"literal\");\n\treturn value.replace(/'/g, \"''\");\n}\n/**\n* Builds a qualified name (schema.object) with proper quoting.\n*/\nfunction qualifyName(schemaName, objectName) {\n\treturn `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n/**\n* Validates that an enum value doesn't exceed PostgreSQL's label length limit.\n*\n* PostgreSQL enum labels have a maximum length of NAMEDATALEN-1 (63 bytes by default).\n* Unlike identifiers, enum labels that exceed this limit cause an error rather than\n* silent truncation.\n*\n* @param value - The enum value to validate\n* @param enumTypeName - Name of the enum type (for error messages)\n* @throws {SqlEscapeError} If the value exceeds the maximum length\n*/\nfunction validateEnumValueLength(value, enumTypeName) {\n\tif (value.length > MAX_IDENTIFIER_LENGTH) throw new SqlEscapeError(`Enum value \"${value.slice(0, 20)}...\" for type \"${enumTypeName}\" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character label limit`, value, \"literal\");\n}\n\n//#endregion\nexport { validateEnumValueLength as a, quoteIdentifier as i, escapeLiteral as n, qualifyName as r, SqlEscapeError as t };\n//# sourceMappingURL=sql-utils-CSfAGEwF.mjs.map","import { C as SQL_CHAR_CODEC_ID, E as SQL_VARCHAR_CODEC_ID, S as PG_VARCHAR_CODEC_ID, T as SQL_INT_CODEC_ID, _ as PG_TIMESTAMPTZ_CODEC_ID, a as PG_FLOAT4_CODEC_ID, b as PG_TIME_CODEC_ID, c as PG_INT2_CODEC_ID, d as PG_INTERVAL_CODEC_ID, f as PG_INT_CODEC_ID, g as PG_TEXT_CODEC_ID, h as PG_NUMERIC_CODEC_ID, i as PG_ENUM_CODEC_ID, l as PG_INT4_CODEC_ID, m as PG_JSON_CODEC_ID, n as PG_BOOL_CODEC_ID, o as PG_FLOAT8_CODEC_ID, p as PG_JSONB_CODEC_ID, r as PG_CHAR_CODEC_ID, s as PG_FLOAT_CODEC_ID, t as PG_BIT_CODEC_ID, u as PG_INT8_CODEC_ID, v as PG_TIMESTAMP_CODEC_ID, w as SQL_FLOAT_CODEC_ID, x as PG_VARBIT_CODEC_ID, y as PG_TIMETZ_CODEC_ID } from \"./codec-ids-Bsm9c7ns.mjs\";\nimport { a as validateEnumValueLength, i as quoteIdentifier, n as escapeLiteral, r as qualifyName } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { arraysEqual } from \"@prisma-next/family-sql/schema-verify\";\n\n//#region src/core/enum-control-hooks.ts\nconst ENUM_INTROSPECT_QUERY = `\n SELECT\n n.nspname AS schema_name,\n t.typname AS type_name,\n array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n JOIN pg_enum e ON t.oid = e.enumtypid\n WHERE n.nspname = $1\n GROUP BY n.nspname, t.typname\n ORDER BY n.nspname, t.typname\n`;\n/**\n* Type guard for string arrays. Used for runtime validation of introspected data.\n*/\nfunction isStringArray(value) {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n/**\n* Parses a PostgreSQL array value into a JavaScript string array.\n*\n* PostgreSQL's `pg` library may return `array_agg` results either as:\n* - A JavaScript array (when type parsers are configured)\n* - A string in PostgreSQL array literal format: `{value1,value2,...}`\n*\n* Handles PostgreSQL's quoting rules for array elements:\n* - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted\n* - Inside quoted elements, `\\\"` represents `\"` and `\\\\` represents `\\`\n*\n* @param value - The value to parse (array or PostgreSQL array string)\n* @returns A string array, or null if the value cannot be parsed\n*/\nfunction parsePostgresArray(value) {\n\tif (isStringArray(value)) return value;\n\tif (typeof value === \"string\" && value.startsWith(\"{\") && value.endsWith(\"}\")) {\n\t\tconst inner = value.slice(1, -1);\n\t\tif (inner === \"\") return [];\n\t\treturn parseArrayElements(inner);\n\t}\n\treturn null;\n}\nfunction parseArrayElements(input) {\n\tconst result = [];\n\tlet i = 0;\n\twhile (i < input.length) {\n\t\tif (input[i] === \",\") {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (input[i] === \"\\\"\") {\n\t\t\ti++;\n\t\t\tlet element = \"\";\n\t\t\twhile (i < input.length && input[i] !== \"\\\"\") {\n\t\t\t\tif (input[i] === \"\\\\\" && i + 1 < input.length) {\n\t\t\t\t\ti++;\n\t\t\t\t\telement += input[i];\n\t\t\t\t} else element += input[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tresult.push(element);\n\t\t} else {\n\t\t\tconst nextComma = input.indexOf(\",\", i);\n\t\t\tif (nextComma === -1) {\n\t\t\t\tresult.push(input.slice(i).trim());\n\t\t\t\ti = input.length;\n\t\t\t} else {\n\t\t\t\tresult.push(input.slice(i, nextComma).trim());\n\t\t\t\ti = nextComma;\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n/**\n* Extracts enum values from a StorageTypeInstance.\n* Returns null if values are missing or invalid.\n*/\nfunction getEnumValues(typeInstance) {\n\tconst values = typeInstance.typeParams?.[\"values\"];\n\treturn isStringArray(values) ? values : null;\n}\n/**\n* Reads existing enum values from the schema IR for a given native type.\n* Uses optional chaining to simplify navigation through the annotations structure.\n*/\nfunction readExistingEnumValues(schema, nativeType) {\n\tconst existing = ((schema.annotations?.[\"pg\"])?.[\"storageTypes\"])?.[nativeType];\n\tif (!existing || existing.codecId !== PG_ENUM_CODEC_ID) return null;\n\treturn getEnumValues(existing);\n}\n/**\n* Determines what changes are needed to transform existing enum values to desired values.\n*\n* Returns one of:\n* - `unchanged`: No changes needed, values match exactly\n* - `add_values`: New values can be safely appended (PostgreSQL supports this)\n* - `rebuild`: Full enum rebuild required (value removal, reordering, or both)\n*\n* Note: PostgreSQL enums can only have values added (not removed or reordered) without\n* a full type rebuild involving temp type creation and column migration.\n*\n* @param existing - Current enum values in the database\n* @param desired - Target enum values from the contract\n* @returns The type of change required\n*/\nfunction determineEnumDiff(existing, desired) {\n\tif (arraysEqual(existing, desired)) return { kind: \"unchanged\" };\n\tconst existingSet = new Set(existing);\n\tconst desiredSet = new Set(desired);\n\tconst missingValues = desired.filter((value) => !existingSet.has(value));\n\tconst removedValues = existing.filter((value) => !desiredSet.has(value));\n\tconst orderMismatch = missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);\n\tif (removedValues.length > 0 || orderMismatch) return {\n\t\tkind: \"rebuild\",\n\t\tremovedValues\n\t};\n\treturn {\n\t\tkind: \"add_values\",\n\t\tvalues: missingValues\n\t};\n}\nfunction enumTypeExistsCheck(schemaName, typeName, exists = true) {\n\treturn `SELECT ${exists ? \"EXISTS\" : \"NOT EXISTS\"} (\n SELECT 1\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = '${escapeLiteral(schemaName)}'\n AND t.typname = '${escapeLiteral(typeName)}'\n)`;\n}\nfunction buildCreateEnumOperation(typeName, nativeType, schemaName, values) {\n\tfor (const value of values) validateEnumValueLength(value, typeName);\n\tconst literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst qualifiedType = qualifyName(schemaName, nativeType);\n\treturn {\n\t\tid: `type.${typeName}`,\n\t\tlabel: `Create type ${typeName}`,\n\t\tsummary: `Creates enum type ${typeName}`,\n\t\toperationClass: \"additive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${nativeType}\" does not exist`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType, false)\n\t\t}],\n\t\texecute: [{\n\t\t\tdescription: `create type \"${nativeType}\"`,\n\t\t\tsql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`\n\t\t}],\n\t\tpostcheck: [{\n\t\t\tdescription: `verify type \"${nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType)\n\t\t}]\n\t};\n}\n/**\n* Computes the optimal position for inserting a new enum value to maintain\n* the desired order relative to existing values.\n*\n* PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.\n* This function finds the best reference value by:\n* 1. Looking for the nearest preceding value that already exists\n* 2. Falling back to the nearest following value if no preceding exists\n* 3. Defaulting to end-of-list if no reference is found\n*\n* @param options.desired - The target ordered list of all enum values\n* @param options.desiredIndex - Index of the value being inserted in the desired list\n* @param options.current - Current list of enum values (being built up incrementally)\n* @returns SQL clause (e.g., \" AFTER 'x'\") and insert position for tracking\n*/\nfunction computeInsertPosition(options) {\n\tconst { desired, desiredIndex, current } = options;\n\tconst currentSet = new Set(current);\n\tconst previous = desired.slice(0, desiredIndex).reverse().find((candidate) => currentSet.has(candidate));\n\tconst next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));\n\treturn {\n\t\tclause: previous ? ` AFTER '${escapeLiteral(previous)}'` : next ? ` BEFORE '${escapeLiteral(next)}'` : \"\",\n\t\tinsertAt: previous ? current.indexOf(previous) + 1 : next ? current.indexOf(next) : current.length\n\t};\n}\n/**\n* Builds operations to add new enum values to an existing PostgreSQL enum type.\n*\n* Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.\n* Values are inserted in the correct order using BEFORE/AFTER positioning to match\n* the desired final order.\n*\n* This is a safe, non-destructive operation - existing data is not affected.\n*\n* @param options.typeName - Contract-level type name (e.g., 'Role')\n* @param options.nativeType - PostgreSQL type name (e.g., 'role')\n* @param options.schemaName - PostgreSQL schema (e.g., 'public')\n* @param options.desired - Target ordered list of all enum values\n* @param options.existing - Current enum values in the database\n* @returns Array of migration operations to add each missing value\n*/\nfunction buildAddValueOperations(options) {\n\tconst { typeName, nativeType, schemaName } = options;\n\tconst current = [...options.existing];\n\tconst currentSet = new Set(current);\n\tconst operations = [];\n\tfor (let index = 0; index < options.desired.length; index += 1) {\n\t\tconst value = options.desired[index];\n\t\tif (value === void 0) continue;\n\t\tif (currentSet.has(value)) continue;\n\t\tvalidateEnumValueLength(value, typeName);\n\t\tconst { clause, insertAt } = computeInsertPosition({\n\t\t\tdesired: options.desired,\n\t\t\tdesiredIndex: index,\n\t\t\tcurrent\n\t\t});\n\t\toperations.push({\n\t\t\tid: `type.${typeName}.value.${value}`,\n\t\t\tlabel: `Add value ${value} to ${typeName}`,\n\t\t\tsummary: `Adds enum value ${value} to ${typeName}`,\n\t\t\toperationClass: \"widening\",\n\t\t\ttarget: { id: \"postgres\" },\n\t\t\tprecheck: [],\n\t\t\texecute: [{\n\t\t\t\tdescription: `add value \"${value}\" if not exists`,\n\t\t\t\tsql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(value)}'${clause}`\n\t\t\t}],\n\t\t\tpostcheck: []\n\t\t});\n\t\tcurrent.splice(insertAt, 0, value);\n\t\tcurrentSet.add(value);\n\t}\n\treturn operations;\n}\n/**\n* Collects columns using the enum type from the contract (desired state).\n* Used for type-safe reference tracking.\n*/\nfunction collectEnumColumnsFromContract(contract, typeName, nativeType) {\n\tconst columns = [];\n\tfor (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({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects columns using the enum type from the schema IR (live database state).\n* This ensures we find ALL dependent columns, including those added outside the contract\n* (e.g., manual DDL), which is critical for safe enum rebuild operations.\n*/\nfunction collectEnumColumnsFromSchema(schema, nativeType) {\n\tconst columns = [];\n\tfor (const [tableName, table] of Object.entries(schema.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.nativeType === nativeType) columns.push({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects all columns using the enum type from both contract AND live database.\n* Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.\n*\n* This is critical for data integrity: if a column exists in the database using\n* this enum but is not in the contract (e.g., added via manual DDL), we must\n* still migrate it to avoid DROP TYPE failures.\n*/\nfunction collectAllEnumColumns(contract, schema, typeName, nativeType) {\n\tconst contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);\n\tconst schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst result = [];\n\tfor (const col of [...contractColumns, ...schemaColumns]) {\n\t\tconst key = `${col.table}.${col.column}`;\n\t\tif (!seen.has(key)) {\n\t\t\tseen.add(key);\n\t\t\tresult.push(col);\n\t\t}\n\t}\n\treturn result.sort((a, b) => {\n\t\tconst tableCompare = a.table.localeCompare(b.table);\n\t\treturn tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);\n\t});\n}\n/**\n* Builds a SQL check to verify a column's type matches an expected type.\n*/\nfunction columnTypeCheck(options) {\n\treturn `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(options.schemaName)}'\n AND table_name = '${escapeLiteral(options.tableName)}'\n AND column_name = '${escapeLiteral(options.columnName)}'\n AND udt_name = '${escapeLiteral(options.expectedType)}'\n)`;\n}\n/** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */\nconst MAX_IDENTIFIER_LENGTH = 63;\n/** Suffix added to enum type names during rebuild operations */\nconst REBUILD_SUFFIX = \"__pn_rebuild\";\n/**\n* Builds an SQL check to verify no rows contain any of the removed enum values.\n* This prevents data loss during enum rebuild operations.\n*\n* @param schemaName - PostgreSQL schema name\n* @param tableName - Table containing the enum column\n* @param columnName - Column using the enum type\n* @param removedValues - Array of enum values being removed\n* @returns SQL query that returns true if no rows contain removed values\n*/\nfunction noRemovedValuesExistCheck(schemaName, tableName, columnName, removedValues) {\n\tif (removedValues.length === 0) return \"SELECT true\";\n\tconst valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(\", \");\n\treturn `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualifyName(schemaName, tableName)}\n WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})\n LIMIT 1\n)`;\n}\n/**\n* Builds a migration operation to recreate a PostgreSQL enum type with updated values.\n*\n* This is required when:\n* - Enum values are removed (PostgreSQL doesn't support direct removal)\n* - Enum values are reordered (PostgreSQL doesn't support reordering)\n*\n* The operation:\n* 1. Creates a new enum type with the desired values (temp name)\n* 2. Migrates all columns to use the new type via text cast\n* 3. Drops the original type\n* 4. Renames the temp type to the original name\n*\n* IMPORTANT: If values are being removed and data exists using those values,\n* the operation will fail at the precheck stage with a clear error message.\n* This prevents silent data loss.\n*\n* @param options.typeName - Contract-level type name\n* @param options.nativeType - PostgreSQL type name\n* @param options.schemaName - PostgreSQL schema\n* @param options.values - Desired final enum values\n* @param options.removedValues - Values being removed (for data loss checks)\n* @param options.contract - Full contract for column discovery\n* @param options.schema - Current schema IR for column discovery\n* @returns Migration operation for full enum rebuild\n*/\nfunction buildRecreateEnumOperation(options) {\n\tconst tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;\n\tif (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {\n\t\tconst maxBaseLength = MAX_IDENTIFIER_LENGTH - 12;\n\t\tthrow 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).`);\n\t}\n\tconst qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);\n\tconst qualifiedTemp = qualifyName(options.schemaName, tempTypeName);\n\tconst literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst columnRefs = collectAllEnumColumns(options.contract, options.schema, options.typeName, options.nativeType);\n\tconst alterColumns = columnRefs.map((ref) => ({\n\t\tdescription: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,\n\t\tsql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}\nALTER COLUMN ${quoteIdentifier(ref.column)}\nTYPE ${qualifiedTemp}\nUSING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`\n\t}));\n\tconst postchecks = [\n\t\t{\n\t\t\tdescription: `verify type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t},\n\t\t{\n\t\t\tdescription: `verify temp type \"${tempTypeName}\" was removed`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, tempTypeName, false)\n\t\t},\n\t\t...columnRefs.map((ref) => ({\n\t\t\tdescription: `verify ${ref.table}.${ref.column} uses type \"${options.nativeType}\"`,\n\t\t\tsql: columnTypeCheck({\n\t\t\t\tschemaName: options.schemaName,\n\t\t\t\ttableName: ref.table,\n\t\t\t\tcolumnName: ref.column,\n\t\t\t\texpectedType: options.nativeType\n\t\t\t})\n\t\t}))\n\t];\n\treturn {\n\t\tid: `type.${options.typeName}.rebuild`,\n\t\tlabel: `Rebuild type ${options.typeName}`,\n\t\tsummary: `Recreates enum type ${options.typeName} with updated values`,\n\t\toperationClass: \"destructive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t}, ...options.removedValues.length > 0 ? columnRefs.map((ref) => ({\n\t\t\tdescription: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(\", \")})`,\n\t\t\tsql: noRemovedValuesExistCheck(options.schemaName, ref.table, ref.column, options.removedValues)\n\t\t})) : []],\n\t\texecute: [\n\t\t\t{\n\t\t\t\tdescription: `drop orphaned temp type \"${tempTypeName}\" if exists`,\n\t\t\t\tsql: `DROP TYPE IF EXISTS ${qualifiedTemp}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `create temp type \"${tempTypeName}\"`,\n\t\t\t\tsql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`\n\t\t\t},\n\t\t\t...alterColumns,\n\t\t\t{\n\t\t\t\tdescription: `drop type \"${options.nativeType}\"`,\n\t\t\t\tsql: `DROP TYPE ${qualifiedOriginal}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `rename type \"${tempTypeName}\" to \"${options.nativeType}\"`,\n\t\t\t\tsql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`\n\t\t\t}\n\t\t],\n\t\tpostcheck: postchecks\n\t};\n}\n/**\n* Postgres enum hooks for planning, verifying, and introspecting `storage.types`.\n*/\nconst pgEnumControlHooks = {\n\tplanTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired || desired.length === 0) return { operations: [] };\n\t\tconst schemaNamespace = schemaName ?? \"public\";\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return { operations: [buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired)] };\n\t\tconst diff = determineEnumDiff(existing, desired);\n\t\tif (diff.kind === \"unchanged\") return { operations: [] };\n\t\tif (diff.kind === \"rebuild\") return { operations: [buildRecreateEnumOperation({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tvalues: desired,\n\t\t\tremovedValues: diff.removedValues,\n\t\t\tcontract,\n\t\t\tschema\n\t\t})] };\n\t\treturn { operations: buildAddValueOperations({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tdesired,\n\t\t\texisting\n\t\t}) };\n\t},\n\tverifyType: ({ typeName, typeInstance, schema }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired) return [];\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return [{\n\t\t\tkind: \"type_missing\",\n\t\t\ttable: \"\",\n\t\t\ttypeName,\n\t\t\tmessage: `Type \"${typeName}\" is missing from database`\n\t\t}];\n\t\tif (!arraysEqual(existing, desired)) return [{\n\t\t\tkind: \"type_values_mismatch\",\n\t\t\ttable: \"\",\n\t\t\ttypeName,\n\t\t\texpected: desired.join(\", \"),\n\t\t\tactual: existing.join(\", \"),\n\t\t\tmessage: `Type \"${typeName}\" values do not match contract`\n\t\t}];\n\t\treturn [];\n\t},\n\tintrospectTypes: async ({ driver, schemaName }) => {\n\t\tconst namespace = schemaName ?? \"public\";\n\t\tconst result = await driver.query(ENUM_INTROSPECT_QUERY, [namespace]);\n\t\tconst types = {};\n\t\tfor (const row of result.rows) {\n\t\t\tconst values = parsePostgresArray(row.values);\n\t\t\tif (!values) throw new Error(`Failed to parse enum values for type \"${row.type_name}\": unexpected format: ${JSON.stringify(row.values)}`);\n\t\t\ttypes[row.type_name] = {\n\t\t\t\tcodecId: PG_ENUM_CODEC_ID,\n\t\t\t\tnativeType: row.type_name,\n\t\t\t\ttypeParams: { values }\n\t\t\t};\n\t\t}\n\t\treturn types;\n\t}\n};\n\n//#endregion\n//#region src/core/json-schema-type-expression.ts\nconst MAX_DEPTH = 32;\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction escapeStringLiteral(str) {\n\treturn str.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\\\\r\");\n}\nfunction quotePropertyKey(key) {\n\treturn /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;\n}\nfunction renderLiteral(value) {\n\tif (typeof value === \"string\") return `'${escapeStringLiteral(value)}'`;\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (value === null) return \"null\";\n\treturn \"unknown\";\n}\nfunction renderUnion(items, depth) {\n\treturn items.map((item) => render(item, depth)).join(\" | \");\n}\nfunction renderObjectType(schema, depth) {\n\tconst properties = isRecord(schema[\"properties\"]) ? schema[\"properties\"] : {};\n\tconst required = Array.isArray(schema[\"required\"]) ? new Set(schema[\"required\"].filter((key) => typeof key === \"string\")) : /* @__PURE__ */ new Set();\n\tconst keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));\n\tif (keys.length === 0) {\n\t\tconst additionalProperties = schema[\"additionalProperties\"];\n\t\tif (additionalProperties === true || additionalProperties === void 0) return \"Record<string, unknown>\";\n\t\treturn `Record<string, ${render(additionalProperties, depth)}>`;\n\t}\n\treturn `{ ${keys.map((key) => {\n\t\tconst valueSchema = properties[key];\n\t\tconst optionalMarker = required.has(key) ? \"\" : \"?\";\n\t\treturn `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;\n\t}).join(\"; \")} }`;\n}\nfunction renderArrayType(schema, depth) {\n\tif (Array.isArray(schema[\"items\"])) return `readonly [${schema[\"items\"].map((item) => render(item, depth)).join(\", \")}]`;\n\tif (schema[\"items\"] !== void 0) {\n\t\tconst itemType = render(schema[\"items\"], depth);\n\t\treturn itemType.includes(\" | \") || itemType.includes(\" & \") ? `(${itemType})[]` : `${itemType}[]`;\n\t}\n\treturn \"unknown[]\";\n}\nfunction render(schema, depth) {\n\tif (depth > MAX_DEPTH || !isRecord(schema)) return \"JsonValue\";\n\tconst nextDepth = depth + 1;\n\tif (\"const\" in schema) return renderLiteral(schema[\"const\"]);\n\tif (Array.isArray(schema[\"enum\"])) return schema[\"enum\"].map((value) => renderLiteral(value)).join(\" | \");\n\tif (Array.isArray(schema[\"oneOf\"])) return renderUnion(schema[\"oneOf\"], nextDepth);\n\tif (Array.isArray(schema[\"anyOf\"])) return renderUnion(schema[\"anyOf\"], nextDepth);\n\tif (Array.isArray(schema[\"allOf\"])) return schema[\"allOf\"].map((item) => render(item, nextDepth)).join(\" & \");\n\tif (Array.isArray(schema[\"type\"])) return schema[\"type\"].map((item) => render({\n\t\t...schema,\n\t\ttype: item\n\t}, nextDepth)).join(\" | \");\n\tswitch (schema[\"type\"]) {\n\t\tcase \"string\": return \"string\";\n\t\tcase \"number\":\n\t\tcase \"integer\": return \"number\";\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"null\": return \"null\";\n\t\tcase \"array\": return renderArrayType(schema, nextDepth);\n\t\tcase \"object\": return renderObjectType(schema, nextDepth);\n\t\tdefault: break;\n\t}\n\treturn \"JsonValue\";\n}\nfunction renderTypeScriptTypeFromJsonSchema(schema) {\n\treturn render(schema, 0);\n}\n\n//#endregion\n//#region src/core/parameterized-types.ts\n/**\n* Shared utility for expanding parameterized Postgres types to their full SQL representation.\n*\n* This module provides a single source of truth for type expansion logic, used by:\n* - Schema verification (verify-sql-schema.ts) via the expandNativeType codec control hook\n* - Migration planner (planner.ts) via direct import\n*\n* @module\n*/\n/** Set of codec IDs that use the 'length' parameter */\nconst LENGTH_CODEC_IDS = new Set([\n\tSQL_CHAR_CODEC_ID,\n\tSQL_VARCHAR_CODEC_ID,\n\tPG_CHAR_CODEC_ID,\n\tPG_VARCHAR_CODEC_ID,\n\tPG_BIT_CODEC_ID,\n\tPG_VARBIT_CODEC_ID\n]);\n/** Set of codec IDs that use the 'precision' parameter for temporal types */\nconst TEMPORAL_PRECISION_CODEC_IDS = new Set([\n\tPG_TIMESTAMP_CODEC_ID,\n\tPG_TIMESTAMPTZ_CODEC_ID,\n\tPG_TIME_CODEC_ID,\n\tPG_TIMETZ_CODEC_ID,\n\tPG_INTERVAL_CODEC_ID\n]);\n/**\n* Validates that a value is a valid type parameter number.\n* Type parameters must be finite, non-negative integers.\n*/\nfunction isValidTypeParamNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\n/**\n* Expands a parameterized native type to its full SQL representation.\n*\n* For example:\n* - { nativeType: 'character varying', typeParams: { length: 255 } } -> 'character varying(255)'\n* - { nativeType: 'numeric', typeParams: { precision: 10, scale: 2 } } -> 'numeric(10,2)'\n* - { nativeType: 'timestamp without time zone', typeParams: { precision: 3 } } -> 'timestamp without time zone(3)'\n*\n* Returns the original nativeType if:\n* - No typeParams are provided\n* - No codecId is provided\n* - The codecId is not a known parameterized type\n* - The typeParams values are invalid\n*/\nfunction expandParameterizedNativeType(input) {\n\tconst { nativeType, codecId, typeParams } = input;\n\tif (!typeParams || !codecId) return nativeType;\n\tif (LENGTH_CODEC_IDS.has(codecId)) {\n\t\tconst length = typeParams[\"length\"];\n\t\tif (isValidTypeParamNumber(length)) return `${nativeType}(${length})`;\n\t\treturn nativeType;\n\t}\n\tif (codecId === PG_NUMERIC_CODEC_ID) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tconst scale = typeParams[\"scale\"];\n\t\tif (isValidTypeParamNumber(precision)) {\n\t\t\tif (isValidTypeParamNumber(scale)) return `${nativeType}(${precision},${scale})`;\n\t\t\treturn `${nativeType}(${precision})`;\n\t\t}\n\t\treturn nativeType;\n\t}\n\tif (TEMPORAL_PRECISION_CODEC_IDS.has(codecId)) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (isValidTypeParamNumber(precision)) return `${nativeType}(${precision})`;\n\t\treturn nativeType;\n\t}\n\treturn nativeType;\n}\n\n//#endregion\n//#region src/core/descriptor-meta.ts\n/** Creates a type import spec for codec types */\nconst codecTypeImport = (named) => ({\n\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\tnamed,\n\talias: named\n});\n/** Creates a precision-based TypeScript type renderer for temporal types */\nconst precisionRenderer = (typeName) => ({\n\tkind: \"function\",\n\trender: (params) => {\n\t\tconst precision = params[\"precision\"];\n\t\treturn typeof precision === \"number\" ? `${typeName}<${precision}>` : typeName;\n\t}\n});\n/** Creates control hooks with just expandNativeType for parameterized types */\nconst parameterizedTypeHooks = { expandNativeType: expandParameterizedNativeType };\n/**\n* Validates that a type expression string is safe to embed in generated .d.ts files.\n* Rejects expressions containing patterns that could inject executable code.\n*/\nfunction isSafeTypeExpression(expr) {\n\treturn !/import\\s*\\(|require\\s*\\(|declare\\s|export\\s|eval\\s*\\(/.test(expr);\n}\nfunction renderJsonTypeExpression(params) {\n\tconst typeName = params[\"type\"];\n\tif (typeof typeName === \"string\" && typeName.trim().length > 0) {\n\t\tconst trimmed = typeName.trim();\n\t\tif (!isSafeTypeExpression(trimmed)) return \"JsonValue\";\n\t\treturn trimmed;\n\t}\n\tconst schema = params[\"schemaJson\"];\n\tif (schema && typeof schema === \"object\") {\n\t\tconst rendered = renderTypeScriptTypeFromJsonSchema(schema);\n\t\tif (!isSafeTypeExpression(rendered)) return \"JsonValue\";\n\t\treturn rendered;\n\t}\n\treturn \"JsonValue\";\n}\nconst postgresAdapterDescriptorMeta = {\n\tkind: \"adapter\",\n\tfamilyId: \"sql\",\n\ttargetId: \"postgres\",\n\tid: \"postgres\",\n\tversion: \"0.0.1\",\n\tcapabilities: {\n\t\tpostgres: {\n\t\t\torderBy: true,\n\t\t\tlimit: true,\n\t\t\tlateral: true,\n\t\t\tjsonAgg: true,\n\t\t\treturning: true\n\t\t},\n\t\tsql: { enums: true }\n\t},\n\ttypes: {\n\t\tcodecTypes: {\n\t\t\timport: {\n\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\tnamed: \"CodecTypes\",\n\t\t\t\talias: \"PgTypes\"\n\t\t\t},\n\t\t\tparameterized: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: \"Char<{{length}}>\",\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: \"Varchar<{{length}}>\",\n\t\t\t\t[PG_CHAR_CODEC_ID]: \"Char<{{length}}>\",\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: \"Varchar<{{length}}>\",\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: (params) => {\n\t\t\t\t\t\tconst precision = params[\"precision\"];\n\t\t\t\t\t\tif (typeof precision !== \"number\") throw new Error(\"pg/numeric@1 renderer expects precision\");\n\t\t\t\t\t\tconst scale = params[\"scale\"];\n\t\t\t\t\t\treturn typeof scale === \"number\" ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t[PG_BIT_CODEC_ID]: \"Bit<{{length}}>\",\n\t\t\t\t[PG_VARBIT_CODEC_ID]: \"VarBit<{{length}}>\",\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: precisionRenderer(\"Timestamp\"),\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: precisionRenderer(\"Timestamptz\"),\n\t\t\t\t[PG_TIME_CODEC_ID]: precisionRenderer(\"Time\"),\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: precisionRenderer(\"Timetz\"),\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: precisionRenderer(\"Interval\"),\n\t\t\t\t[PG_ENUM_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: (params) => {\n\t\t\t\t\t\tconst values = params[\"values\"];\n\t\t\t\t\t\tif (!Array.isArray(values)) throw new Error(\"pg/enum@1 renderer expects values array\");\n\t\t\t\t\t\treturn values.map((value) => `'${String(value).replace(/'/g, \"\\\\'\")}'`).join(\" | \");\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t[PG_JSON_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: renderJsonTypeExpression\n\t\t\t\t},\n\t\t\t\t[PG_JSONB_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: renderJsonTypeExpression\n\t\t\t\t}\n\t\t\t},\n\t\t\ttypeImports: [\n\t\t\t\t{\n\t\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\t\tnamed: \"JsonValue\",\n\t\t\t\t\talias: \"JsonValue\"\n\t\t\t\t},\n\t\t\t\tcodecTypeImport(\"Char\"),\n\t\t\t\tcodecTypeImport(\"Varchar\"),\n\t\t\t\tcodecTypeImport(\"Numeric\"),\n\t\t\t\tcodecTypeImport(\"Bit\"),\n\t\t\t\tcodecTypeImport(\"VarBit\"),\n\t\t\t\tcodecTypeImport(\"Timestamp\"),\n\t\t\t\tcodecTypeImport(\"Timestamptz\"),\n\t\t\t\tcodecTypeImport(\"Time\"),\n\t\t\t\tcodecTypeImport(\"Timetz\"),\n\t\t\t\tcodecTypeImport(\"Interval\")\n\t\t\t],\n\t\t\tcontrolPlaneHooks: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_CHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_BIT_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_VARBIT_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIME_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_ENUM_CODEC_ID]: pgEnumControlHooks\n\t\t\t}\n\t\t},\n\t\tstorage: [\n\t\t\t{\n\t\t\t\ttypeId: PG_TEXT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"text\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT2_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int2\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_NUMERIC_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"numeric\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMP_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamp\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMPTZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamptz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIME_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"time\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMETZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timetz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BOOL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bool\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARBIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INTERVAL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"interval\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSON_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"json\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSONB_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"jsonb\"\n\t\t\t}\n\t\t]\n\t}\n};\n\n//#endregion\nexport { expandParameterizedNativeType as n, pgEnumControlHooks as r, postgresAdapterDescriptorMeta as t };\n//# sourceMappingURL=descriptor-meta-ilnFI7bx.mjs.map","import \"./codec-ids-Bsm9c7ns.mjs\";\nimport { i as quoteIdentifier, n as escapeLiteral, r as qualifyName, t as SqlEscapeError } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { n as expandParameterizedNativeType, r as pgEnumControlHooks, t as postgresAdapterDescriptorMeta } from \"./descriptor-meta-ilnFI7bx.mjs\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/core/default-normalizer.ts\n/**\n* Pre-compiled regex patterns for performance.\n* These are compiled once at module load time rather than on each function call.\n*/\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst TIMESTAMP_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP|clock_timestamp\\s*\\(\\s*\\))$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n/**\n* Parses a raw Postgres column default expression into a normalized ColumnDefault.\n* This enables semantic comparison between contract defaults and introspected schema defaults.\n*\n* Used by the migration diff layer to normalize raw database defaults during comparison,\n* keeping the introspection layer focused on faithful data capture.\n*\n* @param rawDefault - Raw default expression from information_schema.columns.column_default\n* @param _nativeType - Native column type (currently unused, reserved for future type-aware parsing)\n* @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n*/\nfunction parsePostgresDefault(rawDefault, _nativeType) {\n\tconst trimmed = rawDefault.trim();\n\tconst normalizedType = _nativeType?.toLowerCase();\n\tconst isBigInt = normalizedType === \"bigint\" || normalizedType === \"int8\";\n\tif (NEXTVAL_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"autoincrement()\"\n\t};\n\tif (TIMESTAMP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"now()\"\n\t};\n\tif (UUID_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (UUID_OSSP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (TRUE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: true\n\t};\n\tif (FALSE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: false\n\t};\n\tif (NUMERIC_PATTERN.test(trimmed)) {\n\t\tif (isBigInt) return {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: {\n\t\t\t\t$type: \"bigint\",\n\t\t\t\tvalue: trimmed\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: Number(trimmed)\n\t\t};\n\t}\n\tconst stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n\tif (stringMatch?.[1] !== void 0) {\n\t\tconst unescaped = stringMatch[1].replace(/''/g, \"'\");\n\t\tif (normalizedType === \"json\" || normalizedType === \"jsonb\") try {\n\t\t\treturn {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: JSON.parse(unescaped)\n\t\t\t};\n\t\t} catch {}\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: unescaped\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"function\",\n\t\texpression: trimmed\n\t};\n}\n\n//#endregion\n//#region src/core/control-adapter.ts\n/**\n* Postgres control plane adapter for control-plane operations like introspection.\n* Provides target-specific implementations for control-plane domain actions.\n*/\nvar PostgresControlAdapter = class {\n\tfamilyId = \"sql\";\n\ttargetId = \"postgres\";\n\t/**\n\t* @deprecated Use targetId instead\n\t*/\n\ttarget = \"postgres\";\n\t/**\n\t* Target-specific normalizer for raw Postgres default expressions.\n\t* Used by schema verification to normalize raw defaults before comparison.\n\t*/\n\tnormalizeDefault = parsePostgresDefault;\n\t/**\n\t* Target-specific normalizer for Postgres schema native type names.\n\t* Used by schema verification to normalize introspected type names\n\t* before comparison with contract native types.\n\t*/\n\tnormalizeNativeType = normalizeSchemaNativeType;\n\t/**\n\t* Introspects a Postgres database schema and returns a raw SqlSchemaIR.\n\t*\n\t* This is a pure schema discovery operation that queries the Postgres catalog\n\t* and returns the schema structure without type mapping or contract enrichment.\n\t* Type mapping and enrichment are handled separately by enrichment helpers.\n\t*\n\t* Uses batched queries to minimize database round trips (7 queries instead of 5T+3).\n\t*\n\t* @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries\n\t* @param contractIR - Optional contract IR for contract-guided introspection (filtering, optimization)\n\t* @param schema - Schema name to introspect (defaults to 'public')\n\t* @returns Promise resolving to SqlSchemaIR representing the live database schema\n\t*/\n\tasync introspect(driver, _contractIR, schema = \"public\") {\n\t\tconst [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult, extensionsResult] = await Promise.all([\n\t\t\tdriver.query(`SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`, [schema]),\n\t\t\tdriver.query(`SELECT\n c.table_name,\n column_name,\n data_type,\n udt_name,\n is_nullable,\n character_maximum_length,\n numeric_precision,\n numeric_scale,\n column_default,\n format_type(a.atttypid, a.atttypmod) AS formatted_type\n FROM information_schema.columns c\n JOIN pg_catalog.pg_class cl\n ON cl.relname = c.table_name\n JOIN pg_catalog.pg_namespace ns\n ON ns.nspname = c.table_schema\n AND ns.oid = cl.relnamespace\n JOIN pg_catalog.pg_attribute a\n ON a.attrelid = cl.oid\n AND a.attname = c.column_name\n AND a.attnum > 0\n AND NOT a.attisdropped\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\n ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position,\n ccu.table_schema AS referenced_table_schema,\n ccu.table_name AS referenced_table_name,\n ccu.column_name AS referenced_column_name\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n i.tablename,\n i.indexname,\n ix.indisunique,\n a.attname,\n a.attnum\n FROM pg_indexes i\n JOIN pg_class ic ON ic.relname = i.indexname\n JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1\n JOIN pg_index ix ON ix.indexrelid = ic.oid\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0\n WHERE i.schemaname = $1\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.table_constraints tc\n WHERE tc.table_schema = $1\n AND tc.table_name = i.tablename\n AND tc.constraint_name = i.indexname\n )\n ORDER BY i.tablename, i.indexname, a.attnum`, [schema]),\n\t\t\tdriver.query(`SELECT extname\n FROM pg_extension\n ORDER BY extname`, [])\n\t\t]);\n\t\tconst columnsByTable = groupBy(columnsResult.rows, \"table_name\");\n\t\tconst pksByTable = groupBy(pkResult.rows, \"table_name\");\n\t\tconst fksByTable = groupBy(fkResult.rows, \"table_name\");\n\t\tconst uniquesByTable = groupBy(uniqueResult.rows, \"table_name\");\n\t\tconst indexesByTable = groupBy(indexResult.rows, \"tablename\");\n\t\tconst pkConstraintsByTable = /* @__PURE__ */ new Map();\n\t\tfor (const row of pkResult.rows) {\n\t\t\tlet constraints = pkConstraintsByTable.get(row.table_name);\n\t\t\tif (!constraints) {\n\t\t\t\tconstraints = /* @__PURE__ */ new Set();\n\t\t\t\tpkConstraintsByTable.set(row.table_name, constraints);\n\t\t\t}\n\t\t\tconstraints.add(row.constraint_name);\n\t\t}\n\t\tconst tables = {};\n\t\tfor (const tableRow of tablesResult.rows) {\n\t\t\tconst tableName = tableRow.table_name;\n\t\t\tconst columns = {};\n\t\t\tfor (const colRow of columnsByTable.get(tableName) ?? []) {\n\t\t\t\tlet nativeType = colRow.udt_name;\n\t\t\t\tconst formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;\n\t\t\t\tif (formattedType) nativeType = formattedType;\n\t\t\t\telse if (colRow.data_type === \"character varying\" || colRow.data_type === \"character\") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse 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})`;\n\t\t\t\telse if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse nativeType = colRow.udt_name || colRow.data_type;\n\t\t\t\tcolumns[colRow.column_name] = {\n\t\t\t\t\tname: colRow.column_name,\n\t\t\t\t\tnativeType,\n\t\t\t\t\tnullable: colRow.is_nullable === \"YES\",\n\t\t\t\t\t...ifDefined(\"default\", colRow.column_default ?? void 0)\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pkRows = [...pksByTable.get(tableName) ?? []];\n\t\t\tconst primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);\n\t\t\tconst primaryKey = primaryKeyColumns.length > 0 ? {\n\t\t\t\tcolumns: primaryKeyColumns,\n\t\t\t\t...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}\n\t\t\t} : void 0;\n\t\t\tconst foreignKeysMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const fkRow of fksByTable.get(tableName) ?? []) {\n\t\t\t\tconst existing = foreignKeysMap.get(fkRow.constraint_name);\n\t\t\t\tif (existing) {\n\t\t\t\t\texisting.columns.push(fkRow.column_name);\n\t\t\t\t\texisting.referencedColumns.push(fkRow.referenced_column_name);\n\t\t\t\t} else foreignKeysMap.set(fkRow.constraint_name, {\n\t\t\t\t\tcolumns: [fkRow.column_name],\n\t\t\t\t\treferencedTable: fkRow.referenced_table_name,\n\t\t\t\t\treferencedColumns: [fkRow.referenced_column_name],\n\t\t\t\t\tname: fkRow.constraint_name\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({\n\t\t\t\tcolumns: Object.freeze([...fk.columns]),\n\t\t\t\treferencedTable: fk.referencedTable,\n\t\t\t\treferencedColumns: Object.freeze([...fk.referencedColumns]),\n\t\t\t\tname: fk.name\n\t\t\t}));\n\t\t\tconst pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();\n\t\t\tconst uniquesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const uniqueRow of uniquesByTable.get(tableName) ?? []) {\n\t\t\t\tif (pkConstraints.has(uniqueRow.constraint_name)) continue;\n\t\t\t\tconst existing = uniquesMap.get(uniqueRow.constraint_name);\n\t\t\t\tif (existing) existing.columns.push(uniqueRow.column_name);\n\t\t\t\telse uniquesMap.set(uniqueRow.constraint_name, {\n\t\t\t\t\tcolumns: [uniqueRow.column_name],\n\t\t\t\t\tname: uniqueRow.constraint_name\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst uniques = Array.from(uniquesMap.values()).map((uq) => ({\n\t\t\t\tcolumns: Object.freeze([...uq.columns]),\n\t\t\t\tname: uq.name\n\t\t\t}));\n\t\t\tconst indexesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const idxRow of indexesByTable.get(tableName) ?? []) {\n\t\t\t\tif (!idxRow.attname) continue;\n\t\t\t\tconst existing = indexesMap.get(idxRow.indexname);\n\t\t\t\tif (existing) existing.columns.push(idxRow.attname);\n\t\t\t\telse indexesMap.set(idxRow.indexname, {\n\t\t\t\t\tcolumns: [idxRow.attname],\n\t\t\t\t\tname: idxRow.indexname,\n\t\t\t\t\tunique: idxRow.indisunique\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst indexes = Array.from(indexesMap.values()).map((idx) => ({\n\t\t\t\tcolumns: Object.freeze([...idx.columns]),\n\t\t\t\tname: idx.name,\n\t\t\t\tunique: idx.unique\n\t\t\t}));\n\t\t\ttables[tableName] = {\n\t\t\t\tname: tableName,\n\t\t\t\tcolumns,\n\t\t\t\t...ifDefined(\"primaryKey\", primaryKey),\n\t\t\t\tforeignKeys,\n\t\t\t\tuniques,\n\t\t\t\tindexes\n\t\t\t};\n\t\t}\n\t\tconst extensions = extensionsResult.rows.map((row) => row.extname);\n\t\tconst storageTypes = await pgEnumControlHooks.introspectTypes?.({\n\t\t\tdriver,\n\t\t\tschemaName: schema\n\t\t}) ?? {};\n\t\treturn {\n\t\t\ttables,\n\t\t\textensions,\n\t\t\tannotations: { pg: {\n\t\t\t\tschema,\n\t\t\t\tversion: await this.getPostgresVersion(driver),\n\t\t\t\t...ifDefined(\"storageTypes\", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)\n\t\t\t} }\n\t\t};\n\t}\n\t/**\n\t* Gets the Postgres version from the database.\n\t*/\n\tasync getPostgresVersion(driver) {\n\t\treturn ((await driver.query(\"SELECT version() AS version\", [])).rows[0]?.version ?? \"\").match(/PostgreSQL (\\d+\\.\\d+)/)?.[1] ?? \"unknown\";\n\t}\n};\n/**\n* Pre-computed lookup map for simple prefix-based type normalization.\n* Maps short Postgres type names to their canonical SQL names.\n* Using a Map for O(1) lookup instead of multiple startsWith checks.\n*/\nconst TYPE_PREFIX_MAP = new Map([\n\t[\"varchar\", \"character varying\"],\n\t[\"bpchar\", \"character\"],\n\t[\"varbit\", \"bit varying\"]\n]);\n/**\n* Normalizes a Postgres schema native type to its canonical form for comparison.\n*\n* Uses a pre-computed lookup map for simple prefix replacements (O(1))\n* and handles complex temporal type normalization separately.\n*/\nfunction normalizeSchemaNativeType(nativeType) {\n\tconst trimmed = nativeType.trim();\n\tfor (const [prefix, replacement] of TYPE_PREFIX_MAP) if (trimmed.startsWith(prefix)) return replacement + trimmed.slice(prefix.length);\n\tif (trimmed.includes(\" with time zone\")) {\n\t\tif (trimmed.startsWith(\"timestamp\")) return `timestamptz${trimmed.slice(9).replace(\" with time zone\", \"\")}`;\n\t\tif (trimmed.startsWith(\"time\")) return `timetz${trimmed.slice(4).replace(\" with time zone\", \"\")}`;\n\t}\n\tif (trimmed.includes(\" without time zone\")) return trimmed.replace(\" without time zone\", \"\");\n\treturn trimmed;\n}\nfunction normalizeFormattedType(formattedType, dataType, udtName) {\n\tif (formattedType === \"integer\") return \"int4\";\n\tif (formattedType === \"smallint\") return \"int2\";\n\tif (formattedType === \"bigint\") return \"int8\";\n\tif (formattedType === \"real\") return \"float4\";\n\tif (formattedType === \"double precision\") return \"float8\";\n\tif (formattedType === \"boolean\") return \"bool\";\n\tif (formattedType.startsWith(\"varchar\")) return formattedType.replace(\"varchar\", \"character varying\");\n\tif (formattedType.startsWith(\"bpchar\")) return formattedType.replace(\"bpchar\", \"character\");\n\tif (formattedType.startsWith(\"varbit\")) return formattedType.replace(\"varbit\", \"bit varying\");\n\tif (dataType === \"timestamp with time zone\" || udtName === \"timestamptz\") return formattedType.replace(\"timestamp\", \"timestamptz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"timestamp without time zone\" || udtName === \"timestamp\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (dataType === \"time with time zone\" || udtName === \"timetz\") return formattedType.replace(\"time\", \"timetz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"time without time zone\" || udtName === \"time\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (formattedType.startsWith(\"\\\"\") && formattedType.endsWith(\"\\\"\")) return formattedType.slice(1, -1);\n\treturn formattedType;\n}\n/**\n* Groups an array of objects by a specified key.\n* Returns a Map for O(1) lookup by group key.\n*/\nfunction groupBy(items, key) {\n\tconst map = /* @__PURE__ */ new Map();\n\tfor (const item of items) {\n\t\tconst groupKey = item[key];\n\t\tlet group = map.get(groupKey);\n\t\tif (!group) {\n\t\t\tgroup = [];\n\t\t\tmap.set(groupKey, group);\n\t\t}\n\t\tgroup.push(item);\n\t}\n\treturn map;\n}\n\n//#endregion\n//#region src/exports/control.ts\nconst postgresAdapterDescriptor = {\n\t...postgresAdapterDescriptorMeta,\n\toperationSignatures: () => [],\n\tcreate() {\n\t\treturn new PostgresControlAdapter();\n\t}\n};\nvar control_default = postgresAdapterDescriptor;\n\n//#endregion\nexport { SqlEscapeError, control_default as default, escapeLiteral, expandParameterizedNativeType, normalizeSchemaNativeType, parsePostgresDefault, qualifyName, quoteIdentifier };\n//# sourceMappingURL=control.mjs.map","import {\n escapeLiteral,\n expandParameterizedNativeType,\n normalizeSchemaNativeType,\n parsePostgresDefault,\n quoteIdentifier,\n} from '@prisma-next/adapter-postgres/control';\nimport { isTaggedBigInt } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport {\n createMigrationPlan,\n extractCodecControlHooks,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport {\n arraysEqual,\n isIndexSatisfied,\n isUniqueConstraintSatisfied,\n verifySqlSchema,\n} from '@prisma-next/family-sql/schema-verify';\nimport type {\n ForeignKey,\n SqlContract,\n SqlStorage,\n StorageColumn,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresColumnDefault } from '../types';\n\ntype OperationClass = 'extension' | 'type' | 'table' | 'unique' | 'index' | 'foreignKey';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype PlannerDatabaseDependency = {\n readonly id: string;\n readonly label: string;\n readonly install: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly verifyDatabaseDependencyInstalled: (schema: SqlSchemaIR) => readonly SchemaIssue[];\n};\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): SqlMigrationPlanner<PostgresPlanTargetDetails> {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\nclass PostgresMigrationPlanner implements SqlMigrationPlanner<PostgresPlanTargetDetails> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: SqlMigrationPlannerPlanOptions) {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const classification = this.classifySchema(options);\n if (classification.kind === 'conflict') {\n return plannerFailure(classification.conflicts);\n }\n\n // Extract codec control hooks once at entry point for reuse across all operations.\n // This avoids repeated iteration over frameworkComponents for each method that needs hooks.\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n\n const storageTypePlan = this.buildStorageTypeOperations(options, schemaName, codecHooks);\n if (storageTypePlan.conflicts.length > 0) {\n return plannerFailure(storageTypePlan.conflicts);\n }\n\n // Build extension operations from component-owned database dependencies\n operations.push(\n ...this.buildDatabaseDependencyOperations(options),\n ...storageTypePlan.operations,\n ...this.buildTableOperations(options.contract.storage.tables, options.schema, schemaName),\n ...this.buildColumnOperations(options.contract.storage.tables, options.schema, schemaName),\n ...this.buildPrimaryKeyOperations(\n options.contract.storage.tables,\n options.schema,\n schemaName,\n ),\n ...this.buildUniqueOperations(options.contract.storage.tables, options.schema, schemaName),\n ...this.buildIndexOperations(options.contract.storage.tables, options.schema, schemaName),\n ...this.buildFkBackingIndexOperations(\n options.contract.storage.tables,\n options.schema,\n schemaName,\n ),\n ...this.buildForeignKeyOperations(\n options.contract.storage.tables,\n options.schema,\n schemaName,\n ),\n );\n\n const plan = createMigrationPlan<PostgresPlanTargetDetails>({\n targetId: 'postgres',\n origin: null,\n destination: {\n storageHash: options.contract.storageHash,\n ...ifDefined('profileHash', options.contract.profileHash),\n },\n operations,\n });\n\n return plannerSuccess(plan);\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Init planner requires additive operations be allowed',\n why: 'The init planner only emits additive operations. Update the policy to include \"additive\".',\n },\n ]);\n }\n return null;\n }\n\n /**\n * Builds migration operations from component-owned database dependencies.\n * These operations install database-side persistence structures declared by components.\n */\n private buildDatabaseDependencyOperations(\n options: PlannerOptionsWithComponents,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const dependencies = this.collectDependencies(options);\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const seenDependencyIds = new Set<string>();\n const seenOperationIds = new Set<string>();\n\n for (const dependency of dependencies) {\n if (seenDependencyIds.has(dependency.id)) {\n continue;\n }\n seenDependencyIds.add(dependency.id);\n\n const issues = dependency.verifyDatabaseDependencyInstalled(options.schema);\n if (issues.length === 0) {\n continue;\n }\n\n for (const installOp of dependency.install) {\n if (seenOperationIds.has(installOp.id)) {\n continue;\n }\n seenOperationIds.add(installOp.id);\n // SQL family components are expected to provide compatible target details. This would be better if\n // the type system could enforce it but it's not likely to occur in practice.\n operations.push(installOp as SqlMigrationPlanOperation<PostgresPlanTargetDetails>);\n }\n }\n\n return operations;\n }\n\n private buildStorageTypeOperations(\n options: PlannerOptionsWithComponents,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): {\n readonly operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly conflicts: readonly SqlPlannerConflict[];\n } {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n const storageTypes = options.contract.storage.types ?? {};\n\n for (const [typeName, typeInstance] of sortedEntries(storageTypes)) {\n const hook = codecHooks.get(typeInstance.codecId);\n const planResult = hook?.planTypeOperations?.({\n typeName,\n typeInstance,\n contract: options.contract,\n schema: options.schema,\n schemaName,\n policy: options.policy,\n });\n if (!planResult) {\n continue;\n }\n for (const operation of planResult.operations) {\n if (!options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n conflicts.push({\n kind: 'missingButNonAdditive',\n summary: `Storage type \"${typeName}\" requires \"${operation.operationClass}\" operation \"${operation.id}\"`,\n location: {\n type: typeName,\n },\n });\n continue;\n }\n operations.push({\n ...operation,\n target: {\n id: operation.target.id,\n details: this.buildTargetDetails('type', typeName, schemaName),\n },\n });\n }\n }\n\n return { operations, conflicts };\n }\n private collectDependencies(\n options: PlannerOptionsWithComponents,\n ): ReadonlyArray<PlannerDatabaseDependency> {\n const components = options.frameworkComponents;\n if (components.length === 0) {\n return [];\n }\n const deps: PlannerDatabaseDependency[] = [];\n for (const component of components) {\n if (!isSqlDependencyProvider(component)) {\n continue;\n }\n const initDeps = component.databaseDependencies?.init;\n if (initDeps && initDeps.length > 0) {\n deps.push(...initDeps);\n }\n }\n return sortDependencies(deps);\n }\n\n private buildTableOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n if (schema.tables[tableName]) {\n continue;\n }\n const qualified = qualifyTableName(schemaName, tableName);\n operations.push({\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" does not exist`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: buildCreateTableSql(qualified, table),\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n });\n }\n return operations;\n }\n\n private buildColumnOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n if (!schemaTable) {\n continue;\n }\n for (const [columnName, column] of sortedEntries(table.columns)) {\n if (schemaTable.columns[columnName]) {\n continue;\n }\n operations.push(this.buildAddColumnOperation(schemaName, tableName, columnName, column));\n }\n }\n return operations;\n }\n\n private buildAddColumnOperation(\n schema: string,\n tableName: string,\n columnName: string,\n column: StorageColumn,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schema, tableName);\n const notNull = column.nullable === false;\n const hasDefault = column.default !== undefined;\n // Only require empty table for NOT NULL columns WITHOUT defaults.\n // PostgreSQL allows adding NOT NULL columns with defaults to non-empty tables\n // because the default value is applied to existing rows.\n const requiresEmptyTable = notNull && !hasDefault;\n const precheck = [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ...(requiresEmptyTable\n ? [\n {\n description: `ensure table \"${tableName}\" is empty before adding NOT NULL column without default`,\n sql: tableIsEmptyCheck(qualified),\n },\n ]\n : []),\n ];\n const execute = [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(qualified, columnName, column),\n },\n ];\n const postcheck = [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n ...(notNull\n ? [\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnIsNotNullCheck({ schema, table: tableName, column: columnName }),\n },\n ]\n : []),\n ];\n\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schema),\n },\n precheck,\n execute,\n postcheck,\n };\n }\n\n private buildPrimaryKeyOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n if (!table.primaryKey) {\n continue;\n }\n const schemaTable = schema.tables[tableName];\n if (!schemaTable || schemaTable.primaryKey) {\n continue;\n }\n const constraintName = table.primaryKey.name ?? `${tableName}_pkey`;\n operations.push({\n id: `primaryKey.${tableName}.${constraintName}`,\n label: `Add primary key ${constraintName} on ${tableName}`,\n summary: `Adds primary key ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure primary key does not exist on \"${tableName}\"`,\n sql: tableHasPrimaryKeyCheck(schemaName, tableName, false),\n },\n ],\n execute: [\n {\n description: `add primary key \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nPRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify primary key \"${constraintName}\" exists`,\n sql: tableHasPrimaryKeyCheck(schemaName, tableName, true, constraintName),\n },\n ],\n });\n }\n return operations;\n }\n\n private buildUniqueOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n for (const unique of table.uniques) {\n if (schemaTable && hasUniqueConstraint(schemaTable, unique.columns)) {\n continue;\n }\n const constraintName = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n operations.push({\n id: `unique.${tableName}.${constraintName}`,\n label: `Add unique constraint ${constraintName} on ${tableName}`,\n summary: `Adds unique constraint ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('unique', constraintName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure unique constraint \"${constraintName}\" is missing`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName, exists: false }),\n },\n ],\n execute: [\n {\n description: `add unique constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nUNIQUE (${unique.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify unique constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildIndexOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n for (const index of table.indexes) {\n if (schemaTable && hasIndex(schemaTable, index.columns)) {\n continue;\n }\n const indexName = index.name ?? `${tableName}_${index.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${index.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n /**\n * Generates FK-backing index operations for FKs with `index: true`,\n * but only when no matching user-declared index exists in `contractTable.indexes`.\n */\n private buildFkBackingIndexOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n // Collect column sets of user-declared indexes to avoid duplicates\n const declaredIndexColumns = new Set(table.indexes.map((idx) => idx.columns.join(',')));\n\n for (const fk of table.foreignKeys) {\n if (fk.index === false) continue;\n // Skip if user already declared an index with these columns\n if (declaredIndexColumns.has(fk.columns.join(','))) continue;\n // Skip if the index already exists in the database\n if (schemaTable && hasIndex(schemaTable, fk.columns)) continue;\n\n const indexName = `${tableName}_${fk.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create FK-backing index ${indexName} on ${tableName}`,\n summary: `Creates FK-backing index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create FK-backing index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${fk.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildForeignKeyOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false) continue;\n if (schemaTable && hasForeignKey(schemaTable, foreignKey)) {\n continue;\n }\n const fkName = foreignKey.name ?? `${tableName}_${foreignKey.columns.join('_')}_fkey`;\n operations.push({\n id: `foreignKey.${tableName}.${fkName}`,\n label: `Add foreign key ${fkName} on ${tableName}`,\n summary: `Adds foreign key ${fkName} referencing ${foreignKey.references.table}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('foreignKey', fkName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure foreign key \"${fkName}\" is missing`,\n sql: constraintExistsCheck({\n constraintName: fkName,\n schema: schemaName,\n exists: false,\n }),\n },\n ],\n execute: [\n {\n description: `add foreign key \"${fkName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify foreign key \"${fkName}\" exists`,\n sql: constraintExistsCheck({ constraintName: fkName, schema: schemaName }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n ): PostgresPlanTargetDetails {\n return {\n schema,\n objectType,\n name,\n ...ifDefined('table', table),\n };\n }\n\n private classifySchema(options: PlannerOptionsWithComponents):\n | { kind: 'ok' }\n | {\n kind: 'conflict';\n conflicts: SqlPlannerConflict[];\n } {\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict: false,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n\n const conflicts = this.extractConflicts(verifyResult.schema.issues);\n if (conflicts.length > 0) {\n return { kind: 'conflict', conflicts };\n }\n return { kind: 'ok' };\n }\n\n private extractConflicts(issues: readonly SchemaIssue[]): SqlPlannerConflict[] {\n const conflicts: SqlPlannerConflict[] = [];\n for (const issue of issues) {\n if (isAdditiveIssue(issue)) {\n continue;\n }\n const conflict = this.convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n return conflicts.sort(conflictComparator);\n }\n\n private convertIssueToConflict(issue: SchemaIssue): SqlPlannerConflict | null {\n switch (issue.kind) {\n case 'type_mismatch':\n return this.buildConflict('typeMismatch', issue);\n case 'nullability_mismatch':\n return this.buildConflict('nullabilityConflict', issue);\n case 'primary_key_mismatch':\n return this.buildConflict('indexIncompatible', issue);\n case 'unique_constraint_mismatch':\n return this.buildConflict('indexIncompatible', issue);\n case 'index_mismatch':\n return this.buildConflict('indexIncompatible', issue);\n case 'foreign_key_mismatch':\n return this.buildConflict('foreignKeyConflict', issue);\n default:\n return null;\n }\n }\n\n private buildConflict(kind: SqlPlannerConflict['kind'], issue: SchemaIssue): SqlPlannerConflict {\n const location = buildConflictLocation(issue);\n const meta =\n issue.expected || issue.actual\n ? Object.freeze({\n ...ifDefined('expected', issue.expected),\n ...ifDefined('actual', issue.actual),\n })\n : undefined;\n\n return {\n kind,\n summary: issue.message,\n ...ifDefined('location', location),\n ...ifDefined('meta', meta),\n };\n }\n}\n\nfunction isSqlDependencyProvider(component: unknown): component is {\n readonly databaseDependencies?: {\n readonly init?: readonly PlannerDatabaseDependency[];\n };\n} {\n if (typeof component !== 'object' || component === null) {\n return false;\n }\n const record = component as Record<string, unknown>;\n\n // If present, enforce familyId match to avoid mixing families at runtime.\n if (Object.hasOwn(record, 'familyId') && record['familyId'] !== 'sql') {\n return false;\n }\n\n if (!Object.hasOwn(record, 'databaseDependencies')) {\n return false;\n }\n const deps = record['databaseDependencies'];\n return deps === undefined || (typeof deps === 'object' && deps !== null);\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n if (dependencies.length <= 1) {\n return dependencies;\n }\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction buildCreateTableSql(qualifiedTableName: string, table: StorageTable): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column),\n buildColumnDefaultSql(column.default, column),\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n },\n );\n\n const constraintDefinitions: string[] = [];\n if (table.primaryKey) {\n constraintDefinitions.push(\n `PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n );\n }\n\n const allDefinitions = [...columnDefinitions, ...constraintDefinitions];\n return `CREATE TABLE ${qualifiedTableName} (\\n ${allDefinitions.join(',\\n ')}\\n)`;\n}\n\n/**\n * Builds the column type SQL, handling autoincrement as a special case.\n * For autoincrement on int4/int8, we use SERIAL/BIGSERIAL types.\n */\nfunction buildColumnTypeSql(column: StorageColumn): string {\n const columnDefault = column.default;\n\n // For autoincrement, use SERIAL/BIGSERIAL types instead of int4/int8\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (column.nativeType === 'int4' || column.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (column.nativeType === 'int8' || column.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (column.nativeType === 'int2' || column.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n\n if (column.typeRef) {\n return quoteIdentifier(column.nativeType);\n }\n\n return renderParameterizedTypeSql(column) ?? column.nativeType;\n}\n\n/**\n * Renders parameterized type SQL for a column, returning null if no expansion is needed.\n *\n * Uses the shared expandParameterizedNativeType utility from the postgres adapter.\n * Returns null when the column has no typeParams, allowing the caller to fall back\n * to the base nativeType.\n */\nfunction renderParameterizedTypeSql(column: StorageColumn): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n const expanded = expandParameterizedNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n // If no expansion happened (returned the same base type), return null\n // so caller can decide whether to use nativeType directly\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/**\n * Builds the DEFAULT clause for a column definition.\n * Returns empty string if no default is defined.\n *\n * Note: autoincrement is handled specially via SERIAL types, so we skip it here.\n */\nfunction buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n // autoincrement is handled by SERIAL type, no explicit DEFAULT needed\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n return `DEFAULT ${columnDefault.expression}`;\n }\n case 'sequence':\n // Sequence names use quoteIdentifier for safe identifier handling\n return `DEFAULT nextval(${quoteIdentifier(columnDefault.name)}::regclass)`;\n }\n}\n\nfunction renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (!isJsonColumn && isTaggedBigInt(value)) {\n if (!/^-?\\d+$/.test(value.value)) {\n throw new Error(`Invalid tagged bigint value: \"${value.value}\" is not a valid integer`);\n }\n return value.value;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'NULL';\n }\n const json = JSON.stringify(value);\n if (isJsonColumn) {\n return `'${escapeLiteral(json)}'::${column.nativeType}`;\n }\n return `'${escapeLiteral(json)}'`;\n}\n\nfunction qualifyTableName(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\nfunction toRegclassLiteral(schema: string, name: string): string {\n const regclass = `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`;\n return `'${escapeLiteral(regclass)}'`;\n}\n\nfunction sortedEntries<V>(record: Readonly<Record<string, V>>): Array<[string, V]> {\n return Object.entries(record).sort(([a], [b]) => a.localeCompare(b)) as Array<[string, V]>;\n}\n\nfunction constraintExistsCheck({\n constraintName,\n schema,\n exists = true,\n}: {\n constraintName: string;\n schema: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n return `SELECT ${existsClause} (\n SELECT 1 FROM pg_constraint c\n JOIN pg_namespace n ON c.connamespace = n.oid\n WHERE c.conname = '${escapeLiteral(constraintName)}'\n AND n.nspname = '${escapeLiteral(schema)}'\n)`;\n}\n\nfunction columnExistsCheck({\n schema,\n table,\n column,\n exists = true,\n}: {\n schema: string;\n table: string;\n column: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? '' : 'NOT ';\n return `SELECT ${existsClause}EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n)`;\n}\n\nfunction columnIsNotNullCheck({\n schema,\n table,\n column,\n}: {\n schema: string;\n table: string;\n column: string;\n}): string {\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n AND is_nullable = 'NO'\n)`;\n}\n\nfunction tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nfunction buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n): string {\n const typeSql = buildColumnTypeSql(column);\n const defaultSql = buildColumnDefaultSql(column.default, column);\n const parts = [\n `ALTER TABLE ${qualifiedTableName}`,\n `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,\n defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n}\n\nfunction tableHasPrimaryKeyCheck(\n schema: string,\n table: string,\n exists: boolean,\n constraintName?: string,\n): string {\n const comparison = exists ? '' : 'NOT ';\n const constraintFilter = constraintName\n ? `AND c2.relname = '${escapeLiteral(constraintName)}'`\n : '';\n return `SELECT ${comparison}EXISTS (\n SELECT 1\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid\n WHERE n.nspname = '${escapeLiteral(schema)}'\n AND c.relname = '${escapeLiteral(table)}'\n AND i.indisprimary\n ${constraintFilter}\n)`;\n}\n\n/**\n * Checks if table has a unique constraint satisfied by the given columns.\n * Uses shared semantic satisfaction predicate from verify-helpers.\n */\nfunction hasUniqueConstraint(\n table: SqlSchemaIR['tables'][string],\n columns: readonly string[],\n): boolean {\n return isUniqueConstraintSatisfied(table.uniques, table.indexes, columns);\n}\n\n/**\n * Checks if table has an index satisfied by the given columns.\n * Uses shared semantic satisfaction predicate from verify-helpers.\n */\nfunction hasIndex(table: SqlSchemaIR['tables'][string], columns: readonly string[]): boolean {\n return isIndexSatisfied(table.indexes, table.uniques, columns);\n}\n\nfunction hasForeignKey(table: SqlSchemaIR['tables'][string], fk: ForeignKey): boolean {\n return table.foreignKeys.some(\n (candidate) =>\n arraysEqual(candidate.columns, fk.columns) &&\n candidate.referencedTable === fk.references.table &&\n arraysEqual(candidate.referencedColumns, fk.references.columns),\n );\n}\n\nfunction isAdditiveIssue(issue: SchemaIssue): boolean {\n switch (issue.kind) {\n case 'type_missing':\n case 'type_values_mismatch':\n case 'missing_table':\n case 'missing_column':\n case 'extension_missing':\n return true;\n case 'primary_key_mismatch':\n return issue.actual === undefined;\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'foreign_key_mismatch':\n return issue.indexOrConstraint === undefined;\n default:\n return false;\n }\n}\n\nfunction buildConflictLocation(issue: SchemaIssue) {\n const location: {\n table?: string;\n column?: string;\n constraint?: string;\n } = {};\n if (issue.table) {\n location.table = issue.table;\n }\n if (issue.column) {\n location.column = issue.column;\n }\n if (issue.indexOrConstraint) {\n location.constraint = issue.indexOrConstraint;\n }\n return Object.keys(location).length > 0 ? location : undefined;\n}\n\nfunction conflictComparator(a: SqlPlannerConflict, b: SqlPlannerConflict): number {\n if (a.kind !== b.kind) {\n return a.kind < b.kind ? -1 : 1;\n }\n const aLocation = a.location ?? {};\n const bLocation = b.location ?? {};\n const tableCompare = compareStrings(aLocation.table, bLocation.table);\n if (tableCompare !== 0) {\n return tableCompare;\n }\n const columnCompare = compareStrings(aLocation.column, bLocation.column);\n if (columnCompare !== 0) {\n return columnCompare;\n }\n const constraintCompare = compareStrings(aLocation.constraint, bLocation.constraint);\n if (constraintCompare !== 0) {\n return constraintCompare;\n }\n return compareStrings(a.summary, b.summary);\n}\n\nfunction compareStrings(a?: string, b?: string): number {\n if (a === b) {\n return 0;\n }\n if (a === undefined) {\n return -1;\n }\n if (b === undefined) {\n return 1;\n }\n return a < b ? -1 : 1;\n}\n","import { bigintJsonReplacer } from '@prisma-next/contract/types';\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport const ensurePrismaContractSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}'\n )`,\n params: [],\n};\n\nexport const ensureLedgerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.ledger (\n id bigserial primary key,\n created_at timestamptz not null default now(),\n origin_core_hash text,\n origin_profile_hash text,\n destination_core_hash text not null,\n destination_profile_hash text,\n contract_json_before jsonb,\n contract_json_after jsonb,\n operations jsonb not null\n )`,\n params: [],\n};\n\nexport interface WriteMarkerInput {\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number | null;\n readonly appTag?: string | null;\n readonly meta?: Record<string, unknown>;\n}\n\nexport function buildWriteMarkerStatements(input: WriteMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n 1,\n input.storageHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n id,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb\n )`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set\n core_hash = $2,\n profile_hash = $3,\n contract_json = $4::jsonb,\n canonical_version = $5,\n updated_at = now(),\n app_tag = $6,\n meta = $7::jsonb\n where id = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originStorageHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationStorageHash: string;\n readonly destinationProfileHash?: string | null;\n readonly contractJsonBefore?: unknown;\n readonly contractJsonAfter?: unknown;\n readonly operations: unknown;\n}\n\nexport function buildLedgerInsertStatement(input: LedgerInsertInput): SqlStatement {\n return {\n sql: `insert into prisma_contract.ledger (\n origin_core_hash,\n origin_profile_hash,\n destination_core_hash,\n destination_profile_hash,\n contract_json_before,\n contract_json_after,\n operations\n ) values (\n $1,\n $2,\n $3,\n $4,\n $5::jsonb,\n $6::jsonb,\n $7::jsonb\n )`,\n params: [\n input.originStorageHash ?? null,\n input.originProfileHash ?? null,\n input.destinationStorageHash,\n input.destinationProfileHash ?? null,\n jsonParam(input.contractJsonBefore),\n jsonParam(input.contractJsonAfter),\n jsonParam(input.operations),\n ],\n };\n}\n\nfunction jsonParam(value: unknown): string {\n return JSON.stringify(value ?? null, bigintJsonReplacer);\n}\n","import {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n} from '@prisma-next/adapter-postgres/control';\nimport type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport { readMarker } from '@prisma-next/family-sql/verify';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport type { PostgresPlanTargetDetails } from './planner';\nimport {\n buildLedgerInsertStatement,\n buildWriteMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await readMarker(driver);\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // Apply plan operations or skip if marker already at destination\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n let applyValue: ApplyPlanSuccessValue;\n\n if (markerAtDestination) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contractIR: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Record marker and ledger entries\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n if (!marker) {\n return okVoid();\n }\n if (this.markerMatchesDestination(marker, plan)) {\n return okVoid();\n }\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (no marker expected).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOrigin: null,\n },\n },\n );\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n ): Promise<void> {\n const writeStatements = buildWriteMarkerStatements({\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","import type {\n ControlTargetInstance,\n MigrationPlanner,\n MigrationRunner,\n} from '@prisma-next/core-control-plane/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n operationSignatures: () => [],\n /**\n * Migrations capability for CLI to access planner/runner via core types.\n * The SQL-specific planner/runner types are compatible with the generic\n * MigrationPlanner/MigrationRunner interfaces at runtime.\n */\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner() as MigrationPlanner<'sql', 'postgres'>;\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;AAGA,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,mB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ACA,SACA,gBACA,oBACe;EACf,MAAM,kBAAkB,2BAA2B;GACjD,mBAAmB,gBAAgB,eAAe;GAClD,mBAAmB,gBAAgB,eAAe;GAClD,wBAAwB,QAAQ,KAAK,YAAY;GACjD,wBACE,QAAQ,KAAK,YAAY,eACzB,QAAQ,oBAAoB,eAC5B,QAAQ,KAAK,YAAY;GAC3B,oBAAoB,gBAAgB,gBAAgB;GACpD,mBAAmB,QAAQ;GAC3B,YAAY;GACb,CAAC;AACF,QAAM,KAAK,iBAAiB,QAAQ,gBAAgB;;CAGtD,MAAc,YACZ,QACA,KACe;AACf,QAAM,OAAO,MAAM,8CAA8C,CAAC,IAAI,CAAC;;CAGzE,MAAc,iBACZ,QACe;AACf,QAAM,OAAO,MAAM,QAAQ;;CAG7B,MAAc,kBACZ,QACe;AACf,QAAM,OAAO,MAAM,SAAS;;CAG9B,MAAc,oBACZ,QACe;AACf,QAAM,OAAO,MAAM,WAAW;;CAGhC,MAAc,iBACZ,QACA,WACe;AACf,MAAI,UAAU,OAAO,SAAS,GAAG;AAC/B,SAAM,OAAO,MAAM,UAAU,KAAK,UAAU,OAAO;AACnD;;AAEF,QAAM,OAAO,MAAM,UAAU,IAAI;;;;;;AC1kBrC,MAAMC,2BACJ;CACE,GAAG;CACH,2BAA2B,EAAE;CAM7B,YAAY;EACV,cAAc,SAAmC;AAC/C,UAAO,gCAAgC;;EAEzC,aAAa,QAAQ;AACnB,UAAO,8BAA8B,OAAO;;EAE/C;CACD,SAAmD;AACjD,SAAO;GACL,UAAU;GACV,UAAU;GACX;;CAMH,cAAc,SAAmC;AAC/C,SAAO,gCAAgC;;CAMzC,aAAa,QAAQ;AACnB,SAAO,8BAA8B,OAAO;;CAE/C;AAEH,sBAAe"}
1
+ {"version":3,"file":"control.mjs","names":["MAX_IDENTIFIER_LENGTH","control_default","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","deps: PlannerDatabaseDependency[]","constraintDefinitions: string[]","location: {\n table?: string;\n column?: string;\n constraint?: string;\n }","REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string>","ensurePrismaContractSchemaStatement: SqlStatement","ensureMarkerTableStatement: SqlStatement","ensureLedgerTableStatement: SqlStatement","params: readonly unknown[]","DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../../../6-adapters/postgres/dist/sql-utils-CSfAGEwF.mjs","../../../6-adapters/postgres/dist/codec-ids-Bsm9c7ns.mjs","../../../6-adapters/postgres/dist/descriptor-meta-ilnFI7bx.mjs","../../../6-adapters/postgres/dist/control.mjs","../src/core/migrations/planner.ts","../src/core/migrations/statement-builders.ts","../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["//#region src/core/sql-utils.ts\n/**\n* Shared SQL utility functions for the Postgres adapter.\n*\n* These functions handle safe SQL identifier and literal escaping\n* with security validations to prevent injection and encoding issues.\n*/\n/**\n* Error thrown when an invalid SQL identifier or literal is detected.\n* Boundary layers map this to structured envelopes.\n*/\nvar SqlEscapeError = class extends Error {\n\tconstructor(message, value, kind) {\n\t\tsuper(message);\n\t\tthis.value = value;\n\t\tthis.kind = kind;\n\t\tthis.name = \"SqlEscapeError\";\n\t}\n};\n/**\n* Maximum length for PostgreSQL identifiers (NAMEDATALEN - 1).\n*/\nconst MAX_IDENTIFIER_LENGTH = 63;\n/**\n* Validates and quotes a PostgreSQL identifier (table, column, type, schema names).\n*\n* Security validations:\n* - Rejects null bytes which could cause truncation or unexpected behavior\n* - Rejects empty identifiers\n* - Warns on identifiers exceeding PostgreSQL's 63-character limit\n*\n* @throws {SqlEscapeError} If the identifier contains null bytes or is empty\n*/\nfunction quoteIdentifier(identifier) {\n\tif (identifier.length === 0) throw new SqlEscapeError(\"Identifier cannot be empty\", identifier, \"identifier\");\n\tif (identifier.includes(\"\\0\")) throw new SqlEscapeError(\"Identifier cannot contain null bytes\", identifier.replace(/\\0/g, \"\\\\0\"), \"identifier\");\n\tif (identifier.length > MAX_IDENTIFIER_LENGTH) console.warn(`Identifier \"${identifier.slice(0, 20)}...\" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character limit and will be truncated`);\n\treturn `\"${identifier.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n/**\n* Escapes a string literal for safe use in SQL statements.\n*\n* Security validations:\n* - Rejects null bytes which could cause truncation or unexpected behavior\n*\n* Note: This assumes PostgreSQL's `standard_conforming_strings` is ON (default since PG 9.1).\n* Backslashes are treated as literal characters, not escape sequences.\n*\n* @throws {SqlEscapeError} If the value contains null bytes\n*/\nfunction escapeLiteral(value) {\n\tif (value.includes(\"\\0\")) throw new SqlEscapeError(\"Literal value cannot contain null bytes\", value.replace(/\\0/g, \"\\\\0\"), \"literal\");\n\treturn value.replace(/'/g, \"''\");\n}\n/**\n* Builds a qualified name (schema.object) with proper quoting.\n*/\nfunction qualifyName(schemaName, objectName) {\n\treturn `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n/**\n* Validates that an enum value doesn't exceed PostgreSQL's label length limit.\n*\n* PostgreSQL enum labels have a maximum length of NAMEDATALEN-1 (63 bytes by default).\n* Unlike identifiers, enum labels that exceed this limit cause an error rather than\n* silent truncation.\n*\n* @param value - The enum value to validate\n* @param enumTypeName - Name of the enum type (for error messages)\n* @throws {SqlEscapeError} If the value exceeds the maximum length\n*/\nfunction validateEnumValueLength(value, enumTypeName) {\n\tif (value.length > MAX_IDENTIFIER_LENGTH) throw new SqlEscapeError(`Enum value \"${value.slice(0, 20)}...\" for type \"${enumTypeName}\" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character label limit`, value, \"literal\");\n}\n\n//#endregion\nexport { validateEnumValueLength as a, quoteIdentifier as i, escapeLiteral as n, qualifyName as r, SqlEscapeError as t };\n//# sourceMappingURL=sql-utils-CSfAGEwF.mjs.map","import { SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_VARCHAR_CODEC_ID } from \"@prisma-next/sql-relational-core/ast\";\n\n//#region src/core/codec-ids.ts\nconst PG_TEXT_CODEC_ID = \"pg/text@1\";\nconst PG_ENUM_CODEC_ID = \"pg/enum@1\";\nconst PG_CHAR_CODEC_ID = \"pg/char@1\";\nconst PG_VARCHAR_CODEC_ID = \"pg/varchar@1\";\nconst PG_INT_CODEC_ID = \"pg/int@1\";\nconst PG_INT2_CODEC_ID = \"pg/int2@1\";\nconst PG_INT4_CODEC_ID = \"pg/int4@1\";\nconst PG_INT8_CODEC_ID = \"pg/int8@1\";\nconst PG_FLOAT_CODEC_ID = \"pg/float@1\";\nconst PG_FLOAT4_CODEC_ID = \"pg/float4@1\";\nconst PG_FLOAT8_CODEC_ID = \"pg/float8@1\";\nconst PG_NUMERIC_CODEC_ID = \"pg/numeric@1\";\nconst PG_BOOL_CODEC_ID = \"pg/bool@1\";\nconst PG_BIT_CODEC_ID = \"pg/bit@1\";\nconst PG_VARBIT_CODEC_ID = \"pg/varbit@1\";\nconst PG_TIMESTAMP_CODEC_ID = \"pg/timestamp@1\";\nconst PG_TIMESTAMPTZ_CODEC_ID = \"pg/timestamptz@1\";\nconst PG_TIME_CODEC_ID = \"pg/time@1\";\nconst PG_TIMETZ_CODEC_ID = \"pg/timetz@1\";\nconst PG_INTERVAL_CODEC_ID = \"pg/interval@1\";\nconst PG_JSON_CODEC_ID = \"pg/json@1\";\nconst PG_JSONB_CODEC_ID = \"pg/jsonb@1\";\n\n//#endregion\nexport { SQL_CHAR_CODEC_ID as C, SQL_VARCHAR_CODEC_ID as E, PG_VARCHAR_CODEC_ID as S, SQL_INT_CODEC_ID as T, PG_TIMESTAMPTZ_CODEC_ID as _, PG_FLOAT4_CODEC_ID as a, PG_TIME_CODEC_ID as b, PG_INT2_CODEC_ID as c, PG_INTERVAL_CODEC_ID as d, PG_INT_CODEC_ID as f, PG_TEXT_CODEC_ID as g, PG_NUMERIC_CODEC_ID as h, PG_ENUM_CODEC_ID as i, PG_INT4_CODEC_ID as l, PG_JSON_CODEC_ID as m, PG_BOOL_CODEC_ID as n, PG_FLOAT8_CODEC_ID as o, PG_JSONB_CODEC_ID as p, PG_CHAR_CODEC_ID as r, PG_FLOAT_CODEC_ID as s, PG_BIT_CODEC_ID as t, PG_INT8_CODEC_ID as u, PG_TIMESTAMP_CODEC_ID as v, SQL_FLOAT_CODEC_ID as w, PG_VARBIT_CODEC_ID as x, PG_TIMETZ_CODEC_ID as y };\n//# sourceMappingURL=codec-ids-Bsm9c7ns.mjs.map","import { C as SQL_CHAR_CODEC_ID, E as SQL_VARCHAR_CODEC_ID, S as PG_VARCHAR_CODEC_ID, T as SQL_INT_CODEC_ID, _ as PG_TIMESTAMPTZ_CODEC_ID, a as PG_FLOAT4_CODEC_ID, b as PG_TIME_CODEC_ID, c as PG_INT2_CODEC_ID, d as PG_INTERVAL_CODEC_ID, f as PG_INT_CODEC_ID, g as PG_TEXT_CODEC_ID, h as PG_NUMERIC_CODEC_ID, i as PG_ENUM_CODEC_ID, l as PG_INT4_CODEC_ID, m as PG_JSON_CODEC_ID, n as PG_BOOL_CODEC_ID, o as PG_FLOAT8_CODEC_ID, p as PG_JSONB_CODEC_ID, r as PG_CHAR_CODEC_ID, s as PG_FLOAT_CODEC_ID, t as PG_BIT_CODEC_ID, u as PG_INT8_CODEC_ID, v as PG_TIMESTAMP_CODEC_ID, w as SQL_FLOAT_CODEC_ID, x as PG_VARBIT_CODEC_ID, y as PG_TIMETZ_CODEC_ID } from \"./codec-ids-Bsm9c7ns.mjs\";\nimport { a as validateEnumValueLength, i as quoteIdentifier, n as escapeLiteral, r as qualifyName } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { arraysEqual } from \"@prisma-next/family-sql/schema-verify\";\n\n//#region src/core/enum-control-hooks.ts\nconst ENUM_INTROSPECT_QUERY = `\n SELECT\n n.nspname AS schema_name,\n t.typname AS type_name,\n array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n JOIN pg_enum e ON t.oid = e.enumtypid\n WHERE n.nspname = $1\n GROUP BY n.nspname, t.typname\n ORDER BY n.nspname, t.typname\n`;\n/**\n* Type guard for string arrays. Used for runtime validation of introspected data.\n*/\nfunction isStringArray(value) {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n/**\n* Parses a PostgreSQL array value into a JavaScript string array.\n*\n* PostgreSQL's `pg` library may return `array_agg` results either as:\n* - A JavaScript array (when type parsers are configured)\n* - A string in PostgreSQL array literal format: `{value1,value2,...}`\n*\n* Handles PostgreSQL's quoting rules for array elements:\n* - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted\n* - Inside quoted elements, `\\\"` represents `\"` and `\\\\` represents `\\`\n*\n* @param value - The value to parse (array or PostgreSQL array string)\n* @returns A string array, or null if the value cannot be parsed\n*/\nfunction parsePostgresArray(value) {\n\tif (isStringArray(value)) return value;\n\tif (typeof value === \"string\" && value.startsWith(\"{\") && value.endsWith(\"}\")) {\n\t\tconst inner = value.slice(1, -1);\n\t\tif (inner === \"\") return [];\n\t\treturn parseArrayElements(inner);\n\t}\n\treturn null;\n}\nfunction parseArrayElements(input) {\n\tconst result = [];\n\tlet i = 0;\n\twhile (i < input.length) {\n\t\tif (input[i] === \",\") {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (input[i] === \"\\\"\") {\n\t\t\ti++;\n\t\t\tlet element = \"\";\n\t\t\twhile (i < input.length && input[i] !== \"\\\"\") {\n\t\t\t\tif (input[i] === \"\\\\\" && i + 1 < input.length) {\n\t\t\t\t\ti++;\n\t\t\t\t\telement += input[i];\n\t\t\t\t} else element += input[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tresult.push(element);\n\t\t} else {\n\t\t\tconst nextComma = input.indexOf(\",\", i);\n\t\t\tif (nextComma === -1) {\n\t\t\t\tresult.push(input.slice(i).trim());\n\t\t\t\ti = input.length;\n\t\t\t} else {\n\t\t\t\tresult.push(input.slice(i, nextComma).trim());\n\t\t\t\ti = nextComma;\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n/**\n* Extracts enum values from a StorageTypeInstance.\n* Returns null if values are missing or invalid.\n*/\nfunction getEnumValues(typeInstance) {\n\tconst values = typeInstance.typeParams?.[\"values\"];\n\treturn isStringArray(values) ? values : null;\n}\n/**\n* Reads existing enum values from the schema IR for a given native type.\n* Uses optional chaining to simplify navigation through the annotations structure.\n*/\nfunction readExistingEnumValues(schema, nativeType) {\n\tconst existing = ((schema.annotations?.[\"pg\"])?.[\"storageTypes\"])?.[nativeType];\n\tif (!existing || existing.codecId !== PG_ENUM_CODEC_ID) return null;\n\treturn getEnumValues(existing);\n}\n/**\n* Determines what changes are needed to transform existing enum values to desired values.\n*\n* Returns one of:\n* - `unchanged`: No changes needed, values match exactly\n* - `add_values`: New values can be safely appended (PostgreSQL supports this)\n* - `rebuild`: Full enum rebuild required (value removal, reordering, or both)\n*\n* Note: PostgreSQL enums can only have values added (not removed or reordered) without\n* a full type rebuild involving temp type creation and column migration.\n*\n* @param existing - Current enum values in the database\n* @param desired - Target enum values from the contract\n* @returns The type of change required\n*/\nfunction determineEnumDiff(existing, desired) {\n\tif (arraysEqual(existing, desired)) return { kind: \"unchanged\" };\n\tconst existingSet = new Set(existing);\n\tconst desiredSet = new Set(desired);\n\tconst missingValues = desired.filter((value) => !existingSet.has(value));\n\tconst removedValues = existing.filter((value) => !desiredSet.has(value));\n\tconst orderMismatch = missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);\n\tif (removedValues.length > 0 || orderMismatch) return {\n\t\tkind: \"rebuild\",\n\t\tremovedValues\n\t};\n\treturn {\n\t\tkind: \"add_values\",\n\t\tvalues: missingValues\n\t};\n}\nfunction enumTypeExistsCheck(schemaName, typeName, exists = true) {\n\treturn `SELECT ${exists ? \"EXISTS\" : \"NOT EXISTS\"} (\n SELECT 1\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = '${escapeLiteral(schemaName)}'\n AND t.typname = '${escapeLiteral(typeName)}'\n)`;\n}\nfunction buildCreateEnumOperation(typeName, nativeType, schemaName, values) {\n\tfor (const value of values) validateEnumValueLength(value, typeName);\n\tconst literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst qualifiedType = qualifyName(schemaName, nativeType);\n\treturn {\n\t\tid: `type.${typeName}`,\n\t\tlabel: `Create type ${typeName}`,\n\t\tsummary: `Creates enum type ${typeName}`,\n\t\toperationClass: \"additive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${nativeType}\" does not exist`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType, false)\n\t\t}],\n\t\texecute: [{\n\t\t\tdescription: `create type \"${nativeType}\"`,\n\t\t\tsql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`\n\t\t}],\n\t\tpostcheck: [{\n\t\t\tdescription: `verify type \"${nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType)\n\t\t}]\n\t};\n}\n/**\n* Computes the optimal position for inserting a new enum value to maintain\n* the desired order relative to existing values.\n*\n* PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.\n* This function finds the best reference value by:\n* 1. Looking for the nearest preceding value that already exists\n* 2. Falling back to the nearest following value if no preceding exists\n* 3. Defaulting to end-of-list if no reference is found\n*\n* @param options.desired - The target ordered list of all enum values\n* @param options.desiredIndex - Index of the value being inserted in the desired list\n* @param options.current - Current list of enum values (being built up incrementally)\n* @returns SQL clause (e.g., \" AFTER 'x'\") and insert position for tracking\n*/\nfunction computeInsertPosition(options) {\n\tconst { desired, desiredIndex, current } = options;\n\tconst currentSet = new Set(current);\n\tconst previous = desired.slice(0, desiredIndex).reverse().find((candidate) => currentSet.has(candidate));\n\tconst next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));\n\treturn {\n\t\tclause: previous ? ` AFTER '${escapeLiteral(previous)}'` : next ? ` BEFORE '${escapeLiteral(next)}'` : \"\",\n\t\tinsertAt: previous ? current.indexOf(previous) + 1 : next ? current.indexOf(next) : current.length\n\t};\n}\n/**\n* Builds operations to add new enum values to an existing PostgreSQL enum type.\n*\n* Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.\n* Values are inserted in the correct order using BEFORE/AFTER positioning to match\n* the desired final order.\n*\n* This is a safe, non-destructive operation - existing data is not affected.\n*\n* @param options.typeName - Contract-level type name (e.g., 'Role')\n* @param options.nativeType - PostgreSQL type name (e.g., 'role')\n* @param options.schemaName - PostgreSQL schema (e.g., 'public')\n* @param options.desired - Target ordered list of all enum values\n* @param options.existing - Current enum values in the database\n* @returns Array of migration operations to add each missing value\n*/\nfunction buildAddValueOperations(options) {\n\tconst { typeName, nativeType, schemaName } = options;\n\tconst current = [...options.existing];\n\tconst currentSet = new Set(current);\n\tconst operations = [];\n\tfor (let index = 0; index < options.desired.length; index += 1) {\n\t\tconst value = options.desired[index];\n\t\tif (value === void 0) continue;\n\t\tif (currentSet.has(value)) continue;\n\t\tvalidateEnumValueLength(value, typeName);\n\t\tconst { clause, insertAt } = computeInsertPosition({\n\t\t\tdesired: options.desired,\n\t\t\tdesiredIndex: index,\n\t\t\tcurrent\n\t\t});\n\t\toperations.push({\n\t\t\tid: `type.${typeName}.value.${value}`,\n\t\t\tlabel: `Add value ${value} to ${typeName}`,\n\t\t\tsummary: `Adds enum value ${value} to ${typeName}`,\n\t\t\toperationClass: \"widening\",\n\t\t\ttarget: { id: \"postgres\" },\n\t\t\tprecheck: [],\n\t\t\texecute: [{\n\t\t\t\tdescription: `add value \"${value}\" if not exists`,\n\t\t\t\tsql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(value)}'${clause}`\n\t\t\t}],\n\t\t\tpostcheck: []\n\t\t});\n\t\tcurrent.splice(insertAt, 0, value);\n\t\tcurrentSet.add(value);\n\t}\n\treturn operations;\n}\n/**\n* Collects columns using the enum type from the contract (desired state).\n* Used for type-safe reference tracking.\n*/\nfunction collectEnumColumnsFromContract(contract, typeName, nativeType) {\n\tconst columns = [];\n\tfor (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({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects columns using the enum type from the schema IR (live database state).\n* This ensures we find ALL dependent columns, including those added outside the contract\n* (e.g., manual DDL), which is critical for safe enum rebuild operations.\n*/\nfunction collectEnumColumnsFromSchema(schema, nativeType) {\n\tconst columns = [];\n\tfor (const [tableName, table] of Object.entries(schema.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.nativeType === nativeType) columns.push({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects all columns using the enum type from both contract AND live database.\n* Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.\n*\n* This is critical for data integrity: if a column exists in the database using\n* this enum but is not in the contract (e.g., added via manual DDL), we must\n* still migrate it to avoid DROP TYPE failures.\n*/\nfunction collectAllEnumColumns(contract, schema, typeName, nativeType) {\n\tconst contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);\n\tconst schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst result = [];\n\tfor (const col of [...contractColumns, ...schemaColumns]) {\n\t\tconst key = `${col.table}.${col.column}`;\n\t\tif (!seen.has(key)) {\n\t\t\tseen.add(key);\n\t\t\tresult.push(col);\n\t\t}\n\t}\n\treturn result.sort((a, b) => {\n\t\tconst tableCompare = a.table.localeCompare(b.table);\n\t\treturn tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);\n\t});\n}\n/**\n* Builds a SQL check to verify a column's type matches an expected type.\n*/\nfunction columnTypeCheck(options) {\n\treturn `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(options.schemaName)}'\n AND table_name = '${escapeLiteral(options.tableName)}'\n AND column_name = '${escapeLiteral(options.columnName)}'\n AND udt_name = '${escapeLiteral(options.expectedType)}'\n)`;\n}\n/** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */\nconst MAX_IDENTIFIER_LENGTH = 63;\n/** Suffix added to enum type names during rebuild operations */\nconst REBUILD_SUFFIX = \"__pn_rebuild\";\n/**\n* Builds an SQL check to verify no rows contain any of the removed enum values.\n* This prevents data loss during enum rebuild operations.\n*\n* @param schemaName - PostgreSQL schema name\n* @param tableName - Table containing the enum column\n* @param columnName - Column using the enum type\n* @param removedValues - Array of enum values being removed\n* @returns SQL query that returns true if no rows contain removed values\n*/\nfunction noRemovedValuesExistCheck(schemaName, tableName, columnName, removedValues) {\n\tif (removedValues.length === 0) return \"SELECT true\";\n\tconst valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(\", \");\n\treturn `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualifyName(schemaName, tableName)}\n WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})\n LIMIT 1\n)`;\n}\n/**\n* Builds a migration operation to recreate a PostgreSQL enum type with updated values.\n*\n* This is required when:\n* - Enum values are removed (PostgreSQL doesn't support direct removal)\n* - Enum values are reordered (PostgreSQL doesn't support reordering)\n*\n* The operation:\n* 1. Creates a new enum type with the desired values (temp name)\n* 2. Migrates all columns to use the new type via text cast\n* 3. Drops the original type\n* 4. Renames the temp type to the original name\n*\n* IMPORTANT: If values are being removed and data exists using those values,\n* the operation will fail at the precheck stage with a clear error message.\n* This prevents silent data loss.\n*\n* @param options.typeName - Contract-level type name\n* @param options.nativeType - PostgreSQL type name\n* @param options.schemaName - PostgreSQL schema\n* @param options.values - Desired final enum values\n* @param options.removedValues - Values being removed (for data loss checks)\n* @param options.contract - Full contract for column discovery\n* @param options.schema - Current schema IR for column discovery\n* @returns Migration operation for full enum rebuild\n*/\nfunction buildRecreateEnumOperation(options) {\n\tconst tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;\n\tif (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {\n\t\tconst maxBaseLength = MAX_IDENTIFIER_LENGTH - 12;\n\t\tthrow 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).`);\n\t}\n\tconst qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);\n\tconst qualifiedTemp = qualifyName(options.schemaName, tempTypeName);\n\tconst literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst columnRefs = collectAllEnumColumns(options.contract, options.schema, options.typeName, options.nativeType);\n\tconst alterColumns = columnRefs.map((ref) => ({\n\t\tdescription: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,\n\t\tsql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}\nALTER COLUMN ${quoteIdentifier(ref.column)}\nTYPE ${qualifiedTemp}\nUSING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`\n\t}));\n\tconst postchecks = [\n\t\t{\n\t\t\tdescription: `verify type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t},\n\t\t{\n\t\t\tdescription: `verify temp type \"${tempTypeName}\" was removed`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, tempTypeName, false)\n\t\t},\n\t\t...columnRefs.map((ref) => ({\n\t\t\tdescription: `verify ${ref.table}.${ref.column} uses type \"${options.nativeType}\"`,\n\t\t\tsql: columnTypeCheck({\n\t\t\t\tschemaName: options.schemaName,\n\t\t\t\ttableName: ref.table,\n\t\t\t\tcolumnName: ref.column,\n\t\t\t\texpectedType: options.nativeType\n\t\t\t})\n\t\t}))\n\t];\n\treturn {\n\t\tid: `type.${options.typeName}.rebuild`,\n\t\tlabel: `Rebuild type ${options.typeName}`,\n\t\tsummary: `Recreates enum type ${options.typeName} with updated values`,\n\t\toperationClass: \"destructive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t}, ...options.removedValues.length > 0 ? columnRefs.map((ref) => ({\n\t\t\tdescription: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(\", \")})`,\n\t\t\tsql: noRemovedValuesExistCheck(options.schemaName, ref.table, ref.column, options.removedValues)\n\t\t})) : []],\n\t\texecute: [\n\t\t\t{\n\t\t\t\tdescription: `drop orphaned temp type \"${tempTypeName}\" if exists`,\n\t\t\t\tsql: `DROP TYPE IF EXISTS ${qualifiedTemp}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `create temp type \"${tempTypeName}\"`,\n\t\t\t\tsql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`\n\t\t\t},\n\t\t\t...alterColumns,\n\t\t\t{\n\t\t\t\tdescription: `drop type \"${options.nativeType}\"`,\n\t\t\t\tsql: `DROP TYPE ${qualifiedOriginal}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `rename type \"${tempTypeName}\" to \"${options.nativeType}\"`,\n\t\t\t\tsql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`\n\t\t\t}\n\t\t],\n\t\tpostcheck: postchecks\n\t};\n}\n/**\n* Postgres enum hooks for planning, verifying, and introspecting `storage.types`.\n*/\nconst pgEnumControlHooks = {\n\tplanTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired || desired.length === 0) return { operations: [] };\n\t\tconst schemaNamespace = schemaName ?? \"public\";\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return { operations: [buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired)] };\n\t\tconst diff = determineEnumDiff(existing, desired);\n\t\tif (diff.kind === \"unchanged\") return { operations: [] };\n\t\tif (diff.kind === \"rebuild\") return { operations: [buildRecreateEnumOperation({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tvalues: desired,\n\t\t\tremovedValues: diff.removedValues,\n\t\t\tcontract,\n\t\t\tschema\n\t\t})] };\n\t\treturn { operations: buildAddValueOperations({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tdesired,\n\t\t\texisting\n\t\t}) };\n\t},\n\tverifyType: ({ typeName, typeInstance, schema }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired) return [];\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return [{\n\t\t\tkind: \"type_missing\",\n\t\t\ttable: \"\",\n\t\t\ttypeName,\n\t\t\tmessage: `Type \"${typeName}\" is missing from database`\n\t\t}];\n\t\tif (!arraysEqual(existing, desired)) return [{\n\t\t\tkind: \"type_values_mismatch\",\n\t\t\ttable: \"\",\n\t\t\ttypeName,\n\t\t\texpected: desired.join(\", \"),\n\t\t\tactual: existing.join(\", \"),\n\t\t\tmessage: `Type \"${typeName}\" values do not match contract`\n\t\t}];\n\t\treturn [];\n\t},\n\tintrospectTypes: async ({ driver, schemaName }) => {\n\t\tconst namespace = schemaName ?? \"public\";\n\t\tconst result = await driver.query(ENUM_INTROSPECT_QUERY, [namespace]);\n\t\tconst types = {};\n\t\tfor (const row of result.rows) {\n\t\t\tconst values = parsePostgresArray(row.values);\n\t\t\tif (!values) throw new Error(`Failed to parse enum values for type \"${row.type_name}\": unexpected format: ${JSON.stringify(row.values)}`);\n\t\t\ttypes[row.type_name] = {\n\t\t\t\tcodecId: PG_ENUM_CODEC_ID,\n\t\t\t\tnativeType: row.type_name,\n\t\t\t\ttypeParams: { values }\n\t\t\t};\n\t\t}\n\t\treturn types;\n\t}\n};\n\n//#endregion\n//#region src/core/json-schema-type-expression.ts\nconst MAX_DEPTH = 32;\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction escapeStringLiteral(str) {\n\treturn str.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\\\\r\");\n}\nfunction quotePropertyKey(key) {\n\treturn /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;\n}\nfunction renderLiteral(value) {\n\tif (typeof value === \"string\") return `'${escapeStringLiteral(value)}'`;\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (value === null) return \"null\";\n\treturn \"unknown\";\n}\nfunction renderUnion(items, depth) {\n\treturn items.map((item) => render(item, depth)).join(\" | \");\n}\nfunction renderObjectType(schema, depth) {\n\tconst properties = isRecord(schema[\"properties\"]) ? schema[\"properties\"] : {};\n\tconst required = Array.isArray(schema[\"required\"]) ? new Set(schema[\"required\"].filter((key) => typeof key === \"string\")) : /* @__PURE__ */ new Set();\n\tconst keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));\n\tif (keys.length === 0) {\n\t\tconst additionalProperties = schema[\"additionalProperties\"];\n\t\tif (additionalProperties === true || additionalProperties === void 0) return \"Record<string, unknown>\";\n\t\treturn `Record<string, ${render(additionalProperties, depth)}>`;\n\t}\n\treturn `{ ${keys.map((key) => {\n\t\tconst valueSchema = properties[key];\n\t\tconst optionalMarker = required.has(key) ? \"\" : \"?\";\n\t\treturn `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;\n\t}).join(\"; \")} }`;\n}\nfunction renderArrayType(schema, depth) {\n\tif (Array.isArray(schema[\"items\"])) return `readonly [${schema[\"items\"].map((item) => render(item, depth)).join(\", \")}]`;\n\tif (schema[\"items\"] !== void 0) {\n\t\tconst itemType = render(schema[\"items\"], depth);\n\t\treturn itemType.includes(\" | \") || itemType.includes(\" & \") ? `(${itemType})[]` : `${itemType}[]`;\n\t}\n\treturn \"unknown[]\";\n}\nfunction render(schema, depth) {\n\tif (depth > MAX_DEPTH || !isRecord(schema)) return \"JsonValue\";\n\tconst nextDepth = depth + 1;\n\tif (\"const\" in schema) return renderLiteral(schema[\"const\"]);\n\tif (Array.isArray(schema[\"enum\"])) return schema[\"enum\"].map((value) => renderLiteral(value)).join(\" | \");\n\tif (Array.isArray(schema[\"oneOf\"])) return renderUnion(schema[\"oneOf\"], nextDepth);\n\tif (Array.isArray(schema[\"anyOf\"])) return renderUnion(schema[\"anyOf\"], nextDepth);\n\tif (Array.isArray(schema[\"allOf\"])) return schema[\"allOf\"].map((item) => render(item, nextDepth)).join(\" & \");\n\tif (Array.isArray(schema[\"type\"])) return schema[\"type\"].map((item) => render({\n\t\t...schema,\n\t\ttype: item\n\t}, nextDepth)).join(\" | \");\n\tswitch (schema[\"type\"]) {\n\t\tcase \"string\": return \"string\";\n\t\tcase \"number\":\n\t\tcase \"integer\": return \"number\";\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"null\": return \"null\";\n\t\tcase \"array\": return renderArrayType(schema, nextDepth);\n\t\tcase \"object\": return renderObjectType(schema, nextDepth);\n\t\tdefault: break;\n\t}\n\treturn \"JsonValue\";\n}\nfunction renderTypeScriptTypeFromJsonSchema(schema) {\n\treturn render(schema, 0);\n}\n\n//#endregion\n//#region src/core/parameterized-types.ts\n/**\n* Shared utility for expanding parameterized Postgres types to their full SQL representation.\n*\n* This module provides a single source of truth for type expansion logic, used by:\n* - Schema verification (verify-sql-schema.ts) via the expandNativeType codec control hook\n* - Migration planner (planner.ts) via direct import\n*\n* @module\n*/\n/** Set of codec IDs that use the 'length' parameter */\nconst LENGTH_CODEC_IDS = new Set([\n\tSQL_CHAR_CODEC_ID,\n\tSQL_VARCHAR_CODEC_ID,\n\tPG_CHAR_CODEC_ID,\n\tPG_VARCHAR_CODEC_ID,\n\tPG_BIT_CODEC_ID,\n\tPG_VARBIT_CODEC_ID\n]);\n/** Set of codec IDs that use the 'precision' parameter for temporal types */\nconst TEMPORAL_PRECISION_CODEC_IDS = new Set([\n\tPG_TIMESTAMP_CODEC_ID,\n\tPG_TIMESTAMPTZ_CODEC_ID,\n\tPG_TIME_CODEC_ID,\n\tPG_TIMETZ_CODEC_ID,\n\tPG_INTERVAL_CODEC_ID\n]);\n/**\n* Validates that a value is a valid type parameter number.\n* Type parameters must be finite, non-negative integers.\n*/\nfunction isValidTypeParamNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\n/**\n* Expands a parameterized native type to its full SQL representation.\n*\n* For example:\n* - { nativeType: 'character varying', typeParams: { length: 255 } } -> 'character varying(255)'\n* - { nativeType: 'numeric', typeParams: { precision: 10, scale: 2 } } -> 'numeric(10,2)'\n* - { nativeType: 'timestamp without time zone', typeParams: { precision: 3 } } -> 'timestamp without time zone(3)'\n*\n* Returns the original nativeType if:\n* - No typeParams are provided\n* - No codecId is provided\n* - The codecId is not a known parameterized type\n* - The typeParams values are invalid\n*/\nfunction expandParameterizedNativeType(input) {\n\tconst { nativeType, codecId, typeParams } = input;\n\tif (!typeParams || !codecId) return nativeType;\n\tif (LENGTH_CODEC_IDS.has(codecId)) {\n\t\tconst length = typeParams[\"length\"];\n\t\tif (isValidTypeParamNumber(length)) return `${nativeType}(${length})`;\n\t\treturn nativeType;\n\t}\n\tif (codecId === PG_NUMERIC_CODEC_ID) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tconst scale = typeParams[\"scale\"];\n\t\tif (isValidTypeParamNumber(precision)) {\n\t\t\tif (isValidTypeParamNumber(scale)) return `${nativeType}(${precision},${scale})`;\n\t\t\treturn `${nativeType}(${precision})`;\n\t\t}\n\t\treturn nativeType;\n\t}\n\tif (TEMPORAL_PRECISION_CODEC_IDS.has(codecId)) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (isValidTypeParamNumber(precision)) return `${nativeType}(${precision})`;\n\t\treturn nativeType;\n\t}\n\treturn nativeType;\n}\n\n//#endregion\n//#region src/core/descriptor-meta.ts\n/** Creates a type import spec for codec types */\nconst codecTypeImport = (named) => ({\n\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\tnamed,\n\talias: named\n});\n/** Creates a precision-based TypeScript type renderer for temporal types */\nconst precisionRenderer = (typeName) => ({\n\tkind: \"function\",\n\trender: (params) => {\n\t\tconst precision = params[\"precision\"];\n\t\treturn typeof precision === \"number\" ? `${typeName}<${precision}>` : typeName;\n\t}\n});\n/** Creates control hooks with just expandNativeType for parameterized types */\nconst parameterizedTypeHooks = { expandNativeType: expandParameterizedNativeType };\n/**\n* Validates that a type expression string is safe to embed in generated .d.ts files.\n* Rejects expressions containing patterns that could inject executable code.\n*/\nfunction isSafeTypeExpression(expr) {\n\treturn !/import\\s*\\(|require\\s*\\(|declare\\s|export\\s|eval\\s*\\(/.test(expr);\n}\nfunction renderJsonTypeExpression(params) {\n\tconst typeName = params[\"type\"];\n\tif (typeof typeName === \"string\" && typeName.trim().length > 0) {\n\t\tconst trimmed = typeName.trim();\n\t\tif (!isSafeTypeExpression(trimmed)) return \"JsonValue\";\n\t\treturn trimmed;\n\t}\n\tconst schema = params[\"schemaJson\"];\n\tif (schema && typeof schema === \"object\") {\n\t\tconst rendered = renderTypeScriptTypeFromJsonSchema(schema);\n\t\tif (!isSafeTypeExpression(rendered)) return \"JsonValue\";\n\t\treturn rendered;\n\t}\n\treturn \"JsonValue\";\n}\nconst postgresAdapterDescriptorMeta = {\n\tkind: \"adapter\",\n\tfamilyId: \"sql\",\n\ttargetId: \"postgres\",\n\tid: \"postgres\",\n\tversion: \"0.0.1\",\n\tcapabilities: {\n\t\tpostgres: {\n\t\t\torderBy: true,\n\t\t\tlimit: true,\n\t\t\tlateral: true,\n\t\t\tjsonAgg: true,\n\t\t\treturning: true\n\t\t},\n\t\tsql: { enums: true }\n\t},\n\ttypes: {\n\t\tcodecTypes: {\n\t\t\timport: {\n\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\tnamed: \"CodecTypes\",\n\t\t\t\talias: \"PgTypes\"\n\t\t\t},\n\t\t\tparameterized: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: \"Char<{{length}}>\",\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: \"Varchar<{{length}}>\",\n\t\t\t\t[PG_CHAR_CODEC_ID]: \"Char<{{length}}>\",\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: \"Varchar<{{length}}>\",\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: (params) => {\n\t\t\t\t\t\tconst precision = params[\"precision\"];\n\t\t\t\t\t\tif (typeof precision !== \"number\") throw new Error(\"pg/numeric@1 renderer expects precision\");\n\t\t\t\t\t\tconst scale = params[\"scale\"];\n\t\t\t\t\t\treturn typeof scale === \"number\" ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t[PG_BIT_CODEC_ID]: \"Bit<{{length}}>\",\n\t\t\t\t[PG_VARBIT_CODEC_ID]: \"VarBit<{{length}}>\",\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: precisionRenderer(\"Timestamp\"),\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: precisionRenderer(\"Timestamptz\"),\n\t\t\t\t[PG_TIME_CODEC_ID]: precisionRenderer(\"Time\"),\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: precisionRenderer(\"Timetz\"),\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: precisionRenderer(\"Interval\"),\n\t\t\t\t[PG_ENUM_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: (params) => {\n\t\t\t\t\t\tconst values = params[\"values\"];\n\t\t\t\t\t\tif (!Array.isArray(values)) throw new Error(\"pg/enum@1 renderer expects values array\");\n\t\t\t\t\t\treturn values.map((value) => `'${String(value).replace(/'/g, \"\\\\'\")}'`).join(\" | \");\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t[PG_JSON_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: renderJsonTypeExpression\n\t\t\t\t},\n\t\t\t\t[PG_JSONB_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: renderJsonTypeExpression\n\t\t\t\t}\n\t\t\t},\n\t\t\ttypeImports: [\n\t\t\t\t{\n\t\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\t\tnamed: \"JsonValue\",\n\t\t\t\t\talias: \"JsonValue\"\n\t\t\t\t},\n\t\t\t\tcodecTypeImport(\"Char\"),\n\t\t\t\tcodecTypeImport(\"Varchar\"),\n\t\t\t\tcodecTypeImport(\"Numeric\"),\n\t\t\t\tcodecTypeImport(\"Bit\"),\n\t\t\t\tcodecTypeImport(\"VarBit\"),\n\t\t\t\tcodecTypeImport(\"Timestamp\"),\n\t\t\t\tcodecTypeImport(\"Timestamptz\"),\n\t\t\t\tcodecTypeImport(\"Time\"),\n\t\t\t\tcodecTypeImport(\"Timetz\"),\n\t\t\t\tcodecTypeImport(\"Interval\")\n\t\t\t],\n\t\t\tcontrolPlaneHooks: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_CHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_BIT_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_VARBIT_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIME_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_ENUM_CODEC_ID]: pgEnumControlHooks\n\t\t\t}\n\t\t},\n\t\tstorage: [\n\t\t\t{\n\t\t\t\ttypeId: PG_TEXT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"text\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT2_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int2\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_NUMERIC_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"numeric\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMP_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamp\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMPTZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamptz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIME_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"time\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMETZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timetz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BOOL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bool\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARBIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INTERVAL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"interval\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSON_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"json\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSONB_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"jsonb\"\n\t\t\t}\n\t\t]\n\t}\n};\n\n//#endregion\nexport { expandParameterizedNativeType as n, pgEnumControlHooks as r, postgresAdapterDescriptorMeta as t };\n//# sourceMappingURL=descriptor-meta-ilnFI7bx.mjs.map","import { i as quoteIdentifier, n as escapeLiteral, r as qualifyName, t as SqlEscapeError } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { n as expandParameterizedNativeType, r as pgEnumControlHooks, t as postgresAdapterDescriptorMeta } from \"./descriptor-meta-ilnFI7bx.mjs\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/core/default-normalizer.ts\n/**\n* Pre-compiled regex patterns for performance.\n* These are compiled once at module load time rather than on each function call.\n*/\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst TIMESTAMP_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP|clock_timestamp\\s*\\(\\s*\\))$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n/**\n* Parses a raw Postgres column default expression into a normalized ColumnDefault.\n* This enables semantic comparison between contract defaults and introspected schema defaults.\n*\n* Used by the migration diff layer to normalize raw database defaults during comparison,\n* keeping the introspection layer focused on faithful data capture.\n*\n* @param rawDefault - Raw default expression from information_schema.columns.column_default\n* @param _nativeType - Native column type (currently unused, reserved for future type-aware parsing)\n* @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n*/\nfunction parsePostgresDefault(rawDefault, _nativeType) {\n\tconst trimmed = rawDefault.trim();\n\tconst normalizedType = _nativeType?.toLowerCase();\n\tconst isBigInt = normalizedType === \"bigint\" || normalizedType === \"int8\";\n\tif (NEXTVAL_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"autoincrement()\"\n\t};\n\tif (TIMESTAMP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"now()\"\n\t};\n\tif (UUID_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (UUID_OSSP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (TRUE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: true\n\t};\n\tif (FALSE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: false\n\t};\n\tif (NUMERIC_PATTERN.test(trimmed)) {\n\t\tif (isBigInt) return {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: {\n\t\t\t\t$type: \"bigint\",\n\t\t\t\tvalue: trimmed\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: Number(trimmed)\n\t\t};\n\t}\n\tconst stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n\tif (stringMatch?.[1] !== void 0) {\n\t\tconst unescaped = stringMatch[1].replace(/''/g, \"'\");\n\t\tif (normalizedType === \"json\" || normalizedType === \"jsonb\") try {\n\t\t\treturn {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: JSON.parse(unescaped)\n\t\t\t};\n\t\t} catch {}\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: unescaped\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"function\",\n\t\texpression: trimmed\n\t};\n}\n\n//#endregion\n//#region src/core/control-adapter.ts\n/**\n* Postgres control plane adapter for control-plane operations like introspection.\n* Provides target-specific implementations for control-plane domain actions.\n*/\nvar PostgresControlAdapter = class {\n\tfamilyId = \"sql\";\n\ttargetId = \"postgres\";\n\t/**\n\t* @deprecated Use targetId instead\n\t*/\n\ttarget = \"postgres\";\n\t/**\n\t* Target-specific normalizer for raw Postgres default expressions.\n\t* Used by schema verification to normalize raw defaults before comparison.\n\t*/\n\tnormalizeDefault = parsePostgresDefault;\n\t/**\n\t* Target-specific normalizer for Postgres schema native type names.\n\t* Used by schema verification to normalize introspected type names\n\t* before comparison with contract native types.\n\t*/\n\tnormalizeNativeType = normalizeSchemaNativeType;\n\t/**\n\t* Introspects a Postgres database schema and returns a raw SqlSchemaIR.\n\t*\n\t* This is a pure schema discovery operation that queries the Postgres catalog\n\t* and returns the schema structure without type mapping or contract enrichment.\n\t* Type mapping and enrichment are handled separately by enrichment helpers.\n\t*\n\t* Uses batched queries to minimize database round trips (7 queries instead of 5T+3).\n\t*\n\t* @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries\n\t* @param contractIR - Optional contract IR for contract-guided introspection (filtering, optimization)\n\t* @param schema - Schema name to introspect (defaults to 'public')\n\t* @returns Promise resolving to SqlSchemaIR representing the live database schema\n\t*/\n\tasync introspect(driver, _contractIR, schema = \"public\") {\n\t\tconst [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult, extensionsResult] = await Promise.all([\n\t\t\tdriver.query(`SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`, [schema]),\n\t\t\tdriver.query(`SELECT\n c.table_name,\n column_name,\n data_type,\n udt_name,\n is_nullable,\n character_maximum_length,\n numeric_precision,\n numeric_scale,\n column_default,\n format_type(a.atttypid, a.atttypmod) AS formatted_type\n FROM information_schema.columns c\n JOIN pg_catalog.pg_class cl\n ON cl.relname = c.table_name\n JOIN pg_catalog.pg_namespace ns\n ON ns.nspname = c.table_schema\n AND ns.oid = cl.relnamespace\n JOIN pg_catalog.pg_attribute a\n ON a.attrelid = cl.oid\n AND a.attname = c.column_name\n AND a.attnum > 0\n AND NOT a.attisdropped\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\n ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position,\n ref_ns.nspname AS referenced_table_schema,\n ref_cl.relname AS referenced_table_name,\n ref_att.attname AS referenced_column_name,\n rc.delete_rule,\n rc.update_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n JOIN pg_catalog.pg_constraint pgc\n ON pgc.conname = tc.constraint_name\n AND pgc.connamespace = (\n SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema\n )\n JOIN pg_catalog.pg_class ref_cl\n ON ref_cl.oid = pgc.confrelid\n JOIN pg_catalog.pg_namespace ref_ns\n ON ref_ns.oid = ref_cl.relnamespace\n JOIN pg_catalog.pg_attribute ref_att\n ON ref_att.attrelid = pgc.confrelid\n AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]\n JOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n i.tablename,\n i.indexname,\n ix.indisunique,\n a.attname,\n a.attnum\n FROM pg_indexes i\n JOIN pg_class ic ON ic.relname = i.indexname\n JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1\n JOIN pg_index ix ON ix.indexrelid = ic.oid\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0\n WHERE i.schemaname = $1\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.table_constraints tc\n WHERE tc.table_schema = $1\n AND tc.table_name = i.tablename\n AND tc.constraint_name = i.indexname\n )\n ORDER BY i.tablename, i.indexname, a.attnum`, [schema]),\n\t\t\tdriver.query(`SELECT extname\n FROM pg_extension\n ORDER BY extname`, [])\n\t\t]);\n\t\tconst columnsByTable = groupBy(columnsResult.rows, \"table_name\");\n\t\tconst pksByTable = groupBy(pkResult.rows, \"table_name\");\n\t\tconst fksByTable = groupBy(fkResult.rows, \"table_name\");\n\t\tconst uniquesByTable = groupBy(uniqueResult.rows, \"table_name\");\n\t\tconst indexesByTable = groupBy(indexResult.rows, \"tablename\");\n\t\tconst pkConstraintsByTable = /* @__PURE__ */ new Map();\n\t\tfor (const row of pkResult.rows) {\n\t\t\tlet constraints = pkConstraintsByTable.get(row.table_name);\n\t\t\tif (!constraints) {\n\t\t\t\tconstraints = /* @__PURE__ */ new Set();\n\t\t\t\tpkConstraintsByTable.set(row.table_name, constraints);\n\t\t\t}\n\t\t\tconstraints.add(row.constraint_name);\n\t\t}\n\t\tconst tables = {};\n\t\tfor (const tableRow of tablesResult.rows) {\n\t\t\tconst tableName = tableRow.table_name;\n\t\t\tconst columns = {};\n\t\t\tfor (const colRow of columnsByTable.get(tableName) ?? []) {\n\t\t\t\tlet nativeType = colRow.udt_name;\n\t\t\t\tconst formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;\n\t\t\t\tif (formattedType) nativeType = formattedType;\n\t\t\t\telse if (colRow.data_type === \"character varying\" || colRow.data_type === \"character\") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse 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})`;\n\t\t\t\telse if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse nativeType = colRow.udt_name || colRow.data_type;\n\t\t\t\tcolumns[colRow.column_name] = {\n\t\t\t\t\tname: colRow.column_name,\n\t\t\t\t\tnativeType,\n\t\t\t\t\tnullable: colRow.is_nullable === \"YES\",\n\t\t\t\t\t...ifDefined(\"default\", colRow.column_default ?? void 0)\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pkRows = [...pksByTable.get(tableName) ?? []];\n\t\t\tconst primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);\n\t\t\tconst primaryKey = primaryKeyColumns.length > 0 ? {\n\t\t\t\tcolumns: primaryKeyColumns,\n\t\t\t\t...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}\n\t\t\t} : void 0;\n\t\t\tconst foreignKeysMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const fkRow of fksByTable.get(tableName) ?? []) {\n\t\t\t\tconst existing = foreignKeysMap.get(fkRow.constraint_name);\n\t\t\t\tif (existing) {\n\t\t\t\t\texisting.columns.push(fkRow.column_name);\n\t\t\t\t\texisting.referencedColumns.push(fkRow.referenced_column_name);\n\t\t\t\t} else foreignKeysMap.set(fkRow.constraint_name, {\n\t\t\t\t\tcolumns: [fkRow.column_name],\n\t\t\t\t\treferencedTable: fkRow.referenced_table_name,\n\t\t\t\t\treferencedColumns: [fkRow.referenced_column_name],\n\t\t\t\t\tname: fkRow.constraint_name,\n\t\t\t\t\tdeleteRule: fkRow.delete_rule,\n\t\t\t\t\tupdateRule: fkRow.update_rule\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({\n\t\t\t\tcolumns: Object.freeze([...fk.columns]),\n\t\t\t\treferencedTable: fk.referencedTable,\n\t\t\t\treferencedColumns: Object.freeze([...fk.referencedColumns]),\n\t\t\t\tname: fk.name,\n\t\t\t\t...ifDefined(\"onDelete\", mapReferentialAction(fk.deleteRule)),\n\t\t\t\t...ifDefined(\"onUpdate\", mapReferentialAction(fk.updateRule))\n\t\t\t}));\n\t\t\tconst pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();\n\t\t\tconst uniquesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const uniqueRow of uniquesByTable.get(tableName) ?? []) {\n\t\t\t\tif (pkConstraints.has(uniqueRow.constraint_name)) continue;\n\t\t\t\tconst existing = uniquesMap.get(uniqueRow.constraint_name);\n\t\t\t\tif (existing) existing.columns.push(uniqueRow.column_name);\n\t\t\t\telse uniquesMap.set(uniqueRow.constraint_name, {\n\t\t\t\t\tcolumns: [uniqueRow.column_name],\n\t\t\t\t\tname: uniqueRow.constraint_name\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst uniques = Array.from(uniquesMap.values()).map((uq) => ({\n\t\t\t\tcolumns: Object.freeze([...uq.columns]),\n\t\t\t\tname: uq.name\n\t\t\t}));\n\t\t\tconst indexesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const idxRow of indexesByTable.get(tableName) ?? []) {\n\t\t\t\tif (!idxRow.attname) continue;\n\t\t\t\tconst existing = indexesMap.get(idxRow.indexname);\n\t\t\t\tif (existing) existing.columns.push(idxRow.attname);\n\t\t\t\telse indexesMap.set(idxRow.indexname, {\n\t\t\t\t\tcolumns: [idxRow.attname],\n\t\t\t\t\tname: idxRow.indexname,\n\t\t\t\t\tunique: idxRow.indisunique\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst indexes = Array.from(indexesMap.values()).map((idx) => ({\n\t\t\t\tcolumns: Object.freeze([...idx.columns]),\n\t\t\t\tname: idx.name,\n\t\t\t\tunique: idx.unique\n\t\t\t}));\n\t\t\ttables[tableName] = {\n\t\t\t\tname: tableName,\n\t\t\t\tcolumns,\n\t\t\t\t...ifDefined(\"primaryKey\", primaryKey),\n\t\t\t\tforeignKeys,\n\t\t\t\tuniques,\n\t\t\t\tindexes\n\t\t\t};\n\t\t}\n\t\tconst extensions = extensionsResult.rows.map((row) => row.extname);\n\t\tconst storageTypes = await pgEnumControlHooks.introspectTypes?.({\n\t\t\tdriver,\n\t\t\tschemaName: schema\n\t\t}) ?? {};\n\t\treturn {\n\t\t\ttables,\n\t\t\textensions,\n\t\t\tannotations: { pg: {\n\t\t\t\tschema,\n\t\t\t\tversion: await this.getPostgresVersion(driver),\n\t\t\t\t...ifDefined(\"storageTypes\", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)\n\t\t\t} }\n\t\t};\n\t}\n\t/**\n\t* Gets the Postgres version from the database.\n\t*/\n\tasync getPostgresVersion(driver) {\n\t\treturn ((await driver.query(\"SELECT version() AS version\", [])).rows[0]?.version ?? \"\").match(/PostgreSQL (\\d+\\.\\d+)/)?.[1] ?? \"unknown\";\n\t}\n};\n/**\n* Pre-computed lookup map for simple prefix-based type normalization.\n* Maps short Postgres type names to their canonical SQL names.\n* Using a Map for O(1) lookup instead of multiple startsWith checks.\n*/\nconst TYPE_PREFIX_MAP = new Map([\n\t[\"varchar\", \"character varying\"],\n\t[\"bpchar\", \"character\"],\n\t[\"varbit\", \"bit varying\"]\n]);\n/**\n* Normalizes a Postgres schema native type to its canonical form for comparison.\n*\n* Uses a pre-computed lookup map for simple prefix replacements (O(1))\n* and handles complex temporal type normalization separately.\n*/\nfunction normalizeSchemaNativeType(nativeType) {\n\tconst trimmed = nativeType.trim();\n\tfor (const [prefix, replacement] of TYPE_PREFIX_MAP) if (trimmed.startsWith(prefix)) return replacement + trimmed.slice(prefix.length);\n\tif (trimmed.includes(\" with time zone\")) {\n\t\tif (trimmed.startsWith(\"timestamp\")) return `timestamptz${trimmed.slice(9).replace(\" with time zone\", \"\")}`;\n\t\tif (trimmed.startsWith(\"time\")) return `timetz${trimmed.slice(4).replace(\" with time zone\", \"\")}`;\n\t}\n\tif (trimmed.includes(\" without time zone\")) return trimmed.replace(\" without time zone\", \"\");\n\treturn trimmed;\n}\nfunction normalizeFormattedType(formattedType, dataType, udtName) {\n\tif (formattedType === \"integer\") return \"int4\";\n\tif (formattedType === \"smallint\") return \"int2\";\n\tif (formattedType === \"bigint\") return \"int8\";\n\tif (formattedType === \"real\") return \"float4\";\n\tif (formattedType === \"double precision\") return \"float8\";\n\tif (formattedType === \"boolean\") return \"bool\";\n\tif (formattedType.startsWith(\"varchar\")) return formattedType.replace(\"varchar\", \"character varying\");\n\tif (formattedType.startsWith(\"bpchar\")) return formattedType.replace(\"bpchar\", \"character\");\n\tif (formattedType.startsWith(\"varbit\")) return formattedType.replace(\"varbit\", \"bit varying\");\n\tif (dataType === \"timestamp with time zone\" || udtName === \"timestamptz\") return formattedType.replace(\"timestamp\", \"timestamptz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"timestamp without time zone\" || udtName === \"timestamp\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (dataType === \"time with time zone\" || udtName === \"timetz\") return formattedType.replace(\"time\", \"timetz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"time without time zone\" || udtName === \"time\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (formattedType.startsWith(\"\\\"\") && formattedType.endsWith(\"\\\"\")) return formattedType.slice(1, -1);\n\treturn formattedType;\n}\nconst PG_REFERENTIAL_ACTION_MAP = {\n\t\"NO ACTION\": \"noAction\",\n\tRESTRICT: \"restrict\",\n\tCASCADE: \"cascade\",\n\t\"SET NULL\": \"setNull\",\n\t\"SET DEFAULT\": \"setDefault\"\n};\n/**\n* Maps a Postgres referential action rule to the canonical SqlReferentialAction.\n* Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.\n* Throws for unrecognized rules to prevent silent data loss.\n*/\nfunction mapReferentialAction(rule) {\n\tconst mapped = PG_REFERENTIAL_ACTION_MAP[rule];\n\tif (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: \"${rule}\". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);\n\tif (mapped === \"noAction\") return void 0;\n\treturn mapped;\n}\n/**\n* Groups an array of objects by a specified key.\n* Returns a Map for O(1) lookup by group key.\n*/\nfunction groupBy(items, key) {\n\tconst map = /* @__PURE__ */ new Map();\n\tfor (const item of items) {\n\t\tconst groupKey = item[key];\n\t\tlet group = map.get(groupKey);\n\t\tif (!group) {\n\t\t\tgroup = [];\n\t\t\tmap.set(groupKey, group);\n\t\t}\n\t\tgroup.push(item);\n\t}\n\treturn map;\n}\n\n//#endregion\n//#region src/exports/control.ts\nconst postgresAdapterDescriptor = {\n\t...postgresAdapterDescriptorMeta,\n\toperationSignatures: () => [],\n\tcreate() {\n\t\treturn new PostgresControlAdapter();\n\t}\n};\nvar control_default = postgresAdapterDescriptor;\n\n//#endregion\nexport { SqlEscapeError, control_default as default, escapeLiteral, expandParameterizedNativeType, normalizeSchemaNativeType, parsePostgresDefault, qualifyName, quoteIdentifier };\n//# sourceMappingURL=control.mjs.map","import {\n escapeLiteral,\n expandParameterizedNativeType,\n normalizeSchemaNativeType,\n parsePostgresDefault,\n quoteIdentifier,\n} from '@prisma-next/adapter-postgres/control';\nimport { isTaggedBigInt } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport {\n createMigrationPlan,\n extractCodecControlHooks,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport {\n arraysEqual,\n isIndexSatisfied,\n isUniqueConstraintSatisfied,\n verifySqlSchema,\n} from '@prisma-next/family-sql/schema-verify';\nimport type {\n ForeignKey,\n ReferentialAction,\n SqlContract,\n SqlStorage,\n StorageColumn,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresColumnDefault } from '../types';\n\ntype OperationClass = 'extension' | 'type' | 'table' | 'unique' | 'index' | 'foreignKey';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype PlannerDatabaseDependency = {\n readonly id: string;\n readonly label: string;\n readonly install: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly verifyDatabaseDependencyInstalled: (schema: SqlSchemaIR) => readonly SchemaIssue[];\n};\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): SqlMigrationPlanner<PostgresPlanTargetDetails> {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\nclass PostgresMigrationPlanner implements SqlMigrationPlanner<PostgresPlanTargetDetails> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: SqlMigrationPlannerPlanOptions) {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const classification = this.classifySchema(options);\n if (classification.kind === 'conflict') {\n return plannerFailure(classification.conflicts);\n }\n\n // Extract codec control hooks once at entry point for reuse across all operations.\n // This avoids repeated iteration over frameworkComponents for each method that needs hooks.\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n\n const storageTypePlan = this.buildStorageTypeOperations(options, schemaName, codecHooks);\n if (storageTypePlan.conflicts.length > 0) {\n return plannerFailure(storageTypePlan.conflicts);\n }\n\n // Build extension operations from component-owned database dependencies\n operations.push(\n ...this.buildDatabaseDependencyOperations(options),\n ...storageTypePlan.operations,\n ...this.buildTableOperations(options.contract.storage.tables, options.schema, schemaName),\n ...this.buildColumnOperations(options.contract.storage.tables, options.schema, schemaName),\n ...this.buildPrimaryKeyOperations(\n options.contract.storage.tables,\n options.schema,\n schemaName,\n ),\n ...this.buildUniqueOperations(options.contract.storage.tables, options.schema, schemaName),\n ...this.buildIndexOperations(options.contract.storage.tables, options.schema, schemaName),\n ...this.buildFkBackingIndexOperations(\n options.contract.storage.tables,\n options.schema,\n schemaName,\n ),\n ...this.buildForeignKeyOperations(\n options.contract.storage.tables,\n options.schema,\n schemaName,\n ),\n );\n\n const plan = createMigrationPlan<PostgresPlanTargetDetails>({\n targetId: 'postgres',\n origin: null,\n destination: {\n storageHash: options.contract.storageHash,\n ...ifDefined('profileHash', options.contract.profileHash),\n },\n operations,\n });\n\n return plannerSuccess(plan);\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Init planner requires additive operations be allowed',\n why: 'The init planner only emits additive operations. Update the policy to include \"additive\".',\n },\n ]);\n }\n return null;\n }\n\n /**\n * Builds migration operations from component-owned database dependencies.\n * These operations install database-side persistence structures declared by components.\n */\n private buildDatabaseDependencyOperations(\n options: PlannerOptionsWithComponents,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const dependencies = this.collectDependencies(options);\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const seenDependencyIds = new Set<string>();\n const seenOperationIds = new Set<string>();\n\n for (const dependency of dependencies) {\n if (seenDependencyIds.has(dependency.id)) {\n continue;\n }\n seenDependencyIds.add(dependency.id);\n\n const issues = dependency.verifyDatabaseDependencyInstalled(options.schema);\n if (issues.length === 0) {\n continue;\n }\n\n for (const installOp of dependency.install) {\n if (seenOperationIds.has(installOp.id)) {\n continue;\n }\n seenOperationIds.add(installOp.id);\n // SQL family components are expected to provide compatible target details. This would be better if\n // the type system could enforce it but it's not likely to occur in practice.\n operations.push(installOp as SqlMigrationPlanOperation<PostgresPlanTargetDetails>);\n }\n }\n\n return operations;\n }\n\n private buildStorageTypeOperations(\n options: PlannerOptionsWithComponents,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): {\n readonly operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly conflicts: readonly SqlPlannerConflict[];\n } {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n const storageTypes = options.contract.storage.types ?? {};\n\n for (const [typeName, typeInstance] of sortedEntries(storageTypes)) {\n const hook = codecHooks.get(typeInstance.codecId);\n const planResult = hook?.planTypeOperations?.({\n typeName,\n typeInstance,\n contract: options.contract,\n schema: options.schema,\n schemaName,\n policy: options.policy,\n });\n if (!planResult) {\n continue;\n }\n for (const operation of planResult.operations) {\n if (!options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n conflicts.push({\n kind: 'missingButNonAdditive',\n summary: `Storage type \"${typeName}\" requires \"${operation.operationClass}\" operation \"${operation.id}\"`,\n location: {\n type: typeName,\n },\n });\n continue;\n }\n operations.push({\n ...operation,\n target: {\n id: operation.target.id,\n details: this.buildTargetDetails('type', typeName, schemaName),\n },\n });\n }\n }\n\n return { operations, conflicts };\n }\n private collectDependencies(\n options: PlannerOptionsWithComponents,\n ): ReadonlyArray<PlannerDatabaseDependency> {\n const components = options.frameworkComponents;\n if (components.length === 0) {\n return [];\n }\n const deps: PlannerDatabaseDependency[] = [];\n for (const component of components) {\n if (!isSqlDependencyProvider(component)) {\n continue;\n }\n const initDeps = component.databaseDependencies?.init;\n if (initDeps && initDeps.length > 0) {\n deps.push(...initDeps);\n }\n }\n return sortDependencies(deps);\n }\n\n private buildTableOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n if (schema.tables[tableName]) {\n continue;\n }\n const qualified = qualifyTableName(schemaName, tableName);\n operations.push({\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" does not exist`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: buildCreateTableSql(qualified, table),\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n });\n }\n return operations;\n }\n\n private buildColumnOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n if (!schemaTable) {\n continue;\n }\n for (const [columnName, column] of sortedEntries(table.columns)) {\n if (schemaTable.columns[columnName]) {\n continue;\n }\n operations.push(this.buildAddColumnOperation(schemaName, tableName, columnName, column));\n }\n }\n return operations;\n }\n\n private buildAddColumnOperation(\n schema: string,\n tableName: string,\n columnName: string,\n column: StorageColumn,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schema, tableName);\n const notNull = column.nullable === false;\n const hasDefault = column.default !== undefined;\n // Only require empty table for NOT NULL columns WITHOUT defaults.\n // PostgreSQL allows adding NOT NULL columns with defaults to non-empty tables\n // because the default value is applied to existing rows.\n const requiresEmptyTable = notNull && !hasDefault;\n const precheck = [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ...(requiresEmptyTable\n ? [\n {\n description: `ensure table \"${tableName}\" is empty before adding NOT NULL column without default`,\n sql: tableIsEmptyCheck(qualified),\n },\n ]\n : []),\n ];\n const execute = [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(qualified, columnName, column),\n },\n ];\n const postcheck = [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n ...(notNull\n ? [\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnIsNotNullCheck({ schema, table: tableName, column: columnName }),\n },\n ]\n : []),\n ];\n\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schema),\n },\n precheck,\n execute,\n postcheck,\n };\n }\n\n private buildPrimaryKeyOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n if (!table.primaryKey) {\n continue;\n }\n const schemaTable = schema.tables[tableName];\n if (!schemaTable || schemaTable.primaryKey) {\n continue;\n }\n const constraintName = table.primaryKey.name ?? `${tableName}_pkey`;\n operations.push({\n id: `primaryKey.${tableName}.${constraintName}`,\n label: `Add primary key ${constraintName} on ${tableName}`,\n summary: `Adds primary key ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure primary key does not exist on \"${tableName}\"`,\n sql: tableHasPrimaryKeyCheck(schemaName, tableName, false),\n },\n ],\n execute: [\n {\n description: `add primary key \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nPRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify primary key \"${constraintName}\" exists`,\n sql: tableHasPrimaryKeyCheck(schemaName, tableName, true, constraintName),\n },\n ],\n });\n }\n return operations;\n }\n\n private buildUniqueOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n for (const unique of table.uniques) {\n if (schemaTable && hasUniqueConstraint(schemaTable, unique.columns)) {\n continue;\n }\n const constraintName = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n operations.push({\n id: `unique.${tableName}.${constraintName}`,\n label: `Add unique constraint ${constraintName} on ${tableName}`,\n summary: `Adds unique constraint ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('unique', constraintName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure unique constraint \"${constraintName}\" is missing`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName, exists: false }),\n },\n ],\n execute: [\n {\n description: `add unique constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nUNIQUE (${unique.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify unique constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildIndexOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n for (const index of table.indexes) {\n if (schemaTable && hasIndex(schemaTable, index.columns)) {\n continue;\n }\n const indexName = index.name ?? `${tableName}_${index.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${index.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n /**\n * Generates FK-backing index operations for FKs with `index: true`,\n * but only when no matching user-declared index exists in `contractTable.indexes`.\n */\n private buildFkBackingIndexOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n // Collect column sets of user-declared indexes to avoid duplicates\n const declaredIndexColumns = new Set(table.indexes.map((idx) => idx.columns.join(',')));\n\n for (const fk of table.foreignKeys) {\n if (fk.index === false) continue;\n // Skip if user already declared an index with these columns\n if (declaredIndexColumns.has(fk.columns.join(','))) continue;\n // Skip if the index already exists in the database\n if (schemaTable && hasIndex(schemaTable, fk.columns)) continue;\n\n const indexName = `${tableName}_${fk.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create FK-backing index ${indexName} on ${tableName}`,\n summary: `Creates FK-backing index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create FK-backing index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${fk.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildForeignKeyOperations(\n tables: SqlContract<SqlStorage>['storage']['tables'],\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of sortedEntries(tables)) {\n const schemaTable = schema.tables[tableName];\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false) continue;\n if (schemaTable && hasForeignKey(schemaTable, foreignKey)) {\n continue;\n }\n const fkName = foreignKey.name ?? `${tableName}_${foreignKey.columns.join('_')}_fkey`;\n operations.push({\n id: `foreignKey.${tableName}.${fkName}`,\n label: `Add foreign key ${fkName} on ${tableName}`,\n summary: `Adds foreign key ${fkName} referencing ${foreignKey.references.table}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('foreignKey', fkName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure foreign key \"${fkName}\" is missing`,\n sql: constraintExistsCheck({\n constraintName: fkName,\n schema: schemaName,\n exists: false,\n }),\n },\n ],\n execute: [\n {\n description: `add foreign key \"${fkName}\"`,\n sql: buildForeignKeySql(schemaName, tableName, fkName, foreignKey),\n },\n ],\n postcheck: [\n {\n description: `verify foreign key \"${fkName}\" exists`,\n sql: constraintExistsCheck({ constraintName: fkName, schema: schemaName }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n ): PostgresPlanTargetDetails {\n return {\n schema,\n objectType,\n name,\n ...ifDefined('table', table),\n };\n }\n\n private classifySchema(options: PlannerOptionsWithComponents):\n | { kind: 'ok' }\n | {\n kind: 'conflict';\n conflicts: SqlPlannerConflict[];\n } {\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict: false,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n\n const conflicts = this.extractConflicts(verifyResult.schema.issues);\n if (conflicts.length > 0) {\n return { kind: 'conflict', conflicts };\n }\n return { kind: 'ok' };\n }\n\n private extractConflicts(issues: readonly SchemaIssue[]): SqlPlannerConflict[] {\n const conflicts: SqlPlannerConflict[] = [];\n for (const issue of issues) {\n if (isAdditiveIssue(issue)) {\n continue;\n }\n const conflict = this.convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n return conflicts.sort(conflictComparator);\n }\n\n private convertIssueToConflict(issue: SchemaIssue): SqlPlannerConflict | null {\n switch (issue.kind) {\n case 'type_mismatch':\n return this.buildConflict('typeMismatch', issue);\n case 'nullability_mismatch':\n return this.buildConflict('nullabilityConflict', issue);\n case 'primary_key_mismatch':\n return this.buildConflict('indexIncompatible', issue);\n case 'unique_constraint_mismatch':\n return this.buildConflict('indexIncompatible', issue);\n case 'index_mismatch':\n return this.buildConflict('indexIncompatible', issue);\n case 'foreign_key_mismatch':\n return this.buildConflict('foreignKeyConflict', issue);\n default:\n return null;\n }\n }\n\n private buildConflict(kind: SqlPlannerConflict['kind'], issue: SchemaIssue): SqlPlannerConflict {\n const location = buildConflictLocation(issue);\n const meta =\n issue.expected || issue.actual\n ? Object.freeze({\n ...ifDefined('expected', issue.expected),\n ...ifDefined('actual', issue.actual),\n })\n : undefined;\n\n return {\n kind,\n summary: issue.message,\n ...ifDefined('location', location),\n ...ifDefined('meta', meta),\n };\n }\n}\n\nfunction isSqlDependencyProvider(component: unknown): component is {\n readonly databaseDependencies?: {\n readonly init?: readonly PlannerDatabaseDependency[];\n };\n} {\n if (typeof component !== 'object' || component === null) {\n return false;\n }\n const record = component as Record<string, unknown>;\n\n // If present, enforce familyId match to avoid mixing families at runtime.\n if (Object.hasOwn(record, 'familyId') && record['familyId'] !== 'sql') {\n return false;\n }\n\n if (!Object.hasOwn(record, 'databaseDependencies')) {\n return false;\n }\n const deps = record['databaseDependencies'];\n return deps === undefined || (typeof deps === 'object' && deps !== null);\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n if (dependencies.length <= 1) {\n return dependencies;\n }\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction buildCreateTableSql(qualifiedTableName: string, table: StorageTable): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column),\n buildColumnDefaultSql(column.default, column),\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n },\n );\n\n const constraintDefinitions: string[] = [];\n if (table.primaryKey) {\n constraintDefinitions.push(\n `PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n );\n }\n\n const allDefinitions = [...columnDefinitions, ...constraintDefinitions];\n return `CREATE TABLE ${qualifiedTableName} (\\n ${allDefinitions.join(',\\n ')}\\n)`;\n}\n\n/**\n * Builds the column type SQL, handling autoincrement as a special case.\n * For autoincrement on int4/int8, we use SERIAL/BIGSERIAL types.\n */\nfunction buildColumnTypeSql(column: StorageColumn): string {\n const columnDefault = column.default;\n\n // For autoincrement, use SERIAL/BIGSERIAL types instead of int4/int8\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (column.nativeType === 'int4' || column.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (column.nativeType === 'int8' || column.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (column.nativeType === 'int2' || column.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n\n if (column.typeRef) {\n return quoteIdentifier(column.nativeType);\n }\n\n return renderParameterizedTypeSql(column) ?? column.nativeType;\n}\n\n/**\n * Renders parameterized type SQL for a column, returning null if no expansion is needed.\n *\n * Uses the shared expandParameterizedNativeType utility from the postgres adapter.\n * Returns null when the column has no typeParams, allowing the caller to fall back\n * to the base nativeType.\n */\nfunction renderParameterizedTypeSql(column: StorageColumn): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n const expanded = expandParameterizedNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n // If no expansion happened (returned the same base type), return null\n // so caller can decide whether to use nativeType directly\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/**\n * Builds the DEFAULT clause for a column definition.\n * Returns empty string if no default is defined.\n *\n * Note: autoincrement is handled specially via SERIAL types, so we skip it here.\n */\nfunction buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n // autoincrement is handled by SERIAL type, no explicit DEFAULT needed\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n return `DEFAULT ${columnDefault.expression}`;\n }\n case 'sequence':\n // Sequence names use quoteIdentifier for safe identifier handling\n return `DEFAULT nextval(${quoteIdentifier(columnDefault.name)}::regclass)`;\n }\n}\n\nfunction renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (!isJsonColumn && isTaggedBigInt(value)) {\n if (!/^-?\\d+$/.test(value.value)) {\n throw new Error(`Invalid tagged bigint value: \"${value.value}\" is not a valid integer`);\n }\n return value.value;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'NULL';\n }\n const json = JSON.stringify(value);\n if (isJsonColumn) {\n return `'${escapeLiteral(json)}'::${column.nativeType}`;\n }\n return `'${escapeLiteral(json)}'`;\n}\n\nfunction qualifyTableName(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\nfunction toRegclassLiteral(schema: string, name: string): string {\n const regclass = `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`;\n return `'${escapeLiteral(regclass)}'`;\n}\n\nfunction sortedEntries<V>(record: Readonly<Record<string, V>>): Array<[string, V]> {\n return Object.entries(record).sort(([a], [b]) => a.localeCompare(b)) as Array<[string, V]>;\n}\n\nfunction constraintExistsCheck({\n constraintName,\n schema,\n exists = true,\n}: {\n constraintName: string;\n schema: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n return `SELECT ${existsClause} (\n SELECT 1 FROM pg_constraint c\n JOIN pg_namespace n ON c.connamespace = n.oid\n WHERE c.conname = '${escapeLiteral(constraintName)}'\n AND n.nspname = '${escapeLiteral(schema)}'\n)`;\n}\n\nfunction columnExistsCheck({\n schema,\n table,\n column,\n exists = true,\n}: {\n schema: string;\n table: string;\n column: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? '' : 'NOT ';\n return `SELECT ${existsClause}EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n)`;\n}\n\nfunction columnIsNotNullCheck({\n schema,\n table,\n column,\n}: {\n schema: string;\n table: string;\n column: string;\n}): string {\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n AND is_nullable = 'NO'\n)`;\n}\n\nfunction tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nfunction buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n): string {\n const typeSql = buildColumnTypeSql(column);\n const defaultSql = buildColumnDefaultSql(column.default, column);\n const parts = [\n `ALTER TABLE ${qualifiedTableName}`,\n `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,\n defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n}\n\nfunction tableHasPrimaryKeyCheck(\n schema: string,\n table: string,\n exists: boolean,\n constraintName?: string,\n): string {\n const comparison = exists ? '' : 'NOT ';\n const constraintFilter = constraintName\n ? `AND c2.relname = '${escapeLiteral(constraintName)}'`\n : '';\n return `SELECT ${comparison}EXISTS (\n SELECT 1\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid\n WHERE n.nspname = '${escapeLiteral(schema)}'\n AND c.relname = '${escapeLiteral(table)}'\n AND i.indisprimary\n ${constraintFilter}\n)`;\n}\n\n/**\n * Checks if table has a unique constraint satisfied by the given columns.\n * Uses shared semantic satisfaction predicate from verify-helpers.\n */\nfunction hasUniqueConstraint(\n table: SqlSchemaIR['tables'][string],\n columns: readonly string[],\n): boolean {\n return isUniqueConstraintSatisfied(table.uniques, table.indexes, columns);\n}\n\n/**\n * Checks if table has an index satisfied by the given columns.\n * Uses shared semantic satisfaction predicate from verify-helpers.\n */\nfunction hasIndex(table: SqlSchemaIR['tables'][string], columns: readonly string[]): boolean {\n return isIndexSatisfied(table.indexes, table.uniques, columns);\n}\n\nfunction hasForeignKey(table: SqlSchemaIR['tables'][string], fk: ForeignKey): boolean {\n return table.foreignKeys.some(\n (candidate) =>\n arraysEqual(candidate.columns, fk.columns) &&\n candidate.referencedTable === fk.references.table &&\n arraysEqual(candidate.referencedColumns, fk.references.columns),\n );\n}\n\nfunction isAdditiveIssue(issue: SchemaIssue): boolean {\n switch (issue.kind) {\n case 'type_missing':\n case 'type_values_mismatch':\n case 'missing_table':\n case 'missing_column':\n case 'extension_missing':\n return true;\n case 'primary_key_mismatch':\n return issue.actual === undefined;\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'foreign_key_mismatch':\n return issue.indexOrConstraint === undefined;\n default:\n return false;\n }\n}\n\nfunction buildConflictLocation(issue: SchemaIssue) {\n const location: {\n table?: string;\n column?: string;\n constraint?: string;\n } = {};\n if (issue.table) {\n location.table = issue.table;\n }\n if (issue.column) {\n location.column = issue.column;\n }\n if (issue.indexOrConstraint) {\n location.constraint = issue.indexOrConstraint;\n }\n return Object.keys(location).length > 0 ? location : undefined;\n}\n\nfunction conflictComparator(a: SqlPlannerConflict, b: SqlPlannerConflict): number {\n if (a.kind !== b.kind) {\n return a.kind < b.kind ? -1 : 1;\n }\n const aLocation = a.location ?? {};\n const bLocation = b.location ?? {};\n const tableCompare = compareStrings(aLocation.table, bLocation.table);\n if (tableCompare !== 0) {\n return tableCompare;\n }\n const columnCompare = compareStrings(aLocation.column, bLocation.column);\n if (columnCompare !== 0) {\n return columnCompare;\n }\n const constraintCompare = compareStrings(aLocation.constraint, bLocation.constraint);\n if (constraintCompare !== 0) {\n return constraintCompare;\n }\n return compareStrings(a.summary, b.summary);\n}\n\nfunction compareStrings(a?: string, b?: string): number {\n if (a === b) {\n return 0;\n }\n if (a === undefined) {\n return -1;\n }\n if (b === undefined) {\n return 1;\n }\n return a < b ? -1 : 1;\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\nfunction buildForeignKeySql(\n schemaName: string,\n tableName: string,\n fkName: string,\n foreignKey: ForeignKey,\n): string {\n let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`;\n\n if (foreignKey.onDelete !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];\n if (!action) {\n throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);\n }\n sql += `\\nON DELETE ${action}`;\n }\n if (foreignKey.onUpdate !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];\n if (!action) {\n throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);\n }\n sql += `\\nON UPDATE ${action}`;\n }\n\n return sql;\n}\n","import { bigintJsonReplacer } from '@prisma-next/contract/types';\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport const ensurePrismaContractSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}'\n )`,\n params: [],\n};\n\nexport const ensureLedgerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.ledger (\n id bigserial primary key,\n created_at timestamptz not null default now(),\n origin_core_hash text,\n origin_profile_hash text,\n destination_core_hash text not null,\n destination_profile_hash text,\n contract_json_before jsonb,\n contract_json_after jsonb,\n operations jsonb not null\n )`,\n params: [],\n};\n\nexport interface WriteMarkerInput {\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number | null;\n readonly appTag?: string | null;\n readonly meta?: Record<string, unknown>;\n}\n\nexport function buildWriteMarkerStatements(input: WriteMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n 1,\n input.storageHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n id,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb\n )`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set\n core_hash = $2,\n profile_hash = $3,\n contract_json = $4::jsonb,\n canonical_version = $5,\n updated_at = now(),\n app_tag = $6,\n meta = $7::jsonb\n where id = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originStorageHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationStorageHash: string;\n readonly destinationProfileHash?: string | null;\n readonly contractJsonBefore?: unknown;\n readonly contractJsonAfter?: unknown;\n readonly operations: unknown;\n}\n\nexport function buildLedgerInsertStatement(input: LedgerInsertInput): SqlStatement {\n return {\n sql: `insert into prisma_contract.ledger (\n origin_core_hash,\n origin_profile_hash,\n destination_core_hash,\n destination_profile_hash,\n contract_json_before,\n contract_json_after,\n operations\n ) values (\n $1,\n $2,\n $3,\n $4,\n $5::jsonb,\n $6::jsonb,\n $7::jsonb\n )`,\n params: [\n input.originStorageHash ?? null,\n input.originProfileHash ?? null,\n input.destinationStorageHash,\n input.destinationProfileHash ?? null,\n jsonParam(input.contractJsonBefore),\n jsonParam(input.contractJsonAfter),\n jsonParam(input.operations),\n ],\n };\n}\n\nfunction jsonParam(value: unknown): string {\n return JSON.stringify(value ?? null, bigintJsonReplacer);\n}\n","import {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n} from '@prisma-next/adapter-postgres/control';\nimport type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport { readMarker } from '@prisma-next/family-sql/verify';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport type { PostgresPlanTargetDetails } from './planner';\nimport {\n buildLedgerInsertStatement,\n buildWriteMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await readMarker(driver);\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // Apply plan operations or skip if marker already at destination\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n let applyValue: ApplyPlanSuccessValue;\n\n if (markerAtDestination) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contractIR: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Record marker and ledger entries\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n if (!marker) {\n return okVoid();\n }\n if (this.markerMatchesDestination(marker, plan)) {\n return okVoid();\n }\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (no marker expected).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOrigin: null,\n },\n },\n );\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n ): Promise<void> {\n const writeStatements = buildWriteMarkerStatements({\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","import type {\n ControlTargetInstance,\n MigrationPlanner,\n MigrationRunner,\n} from '@prisma-next/core-control-plane/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n operationSignatures: () => [],\n /**\n * Migrations capability for CLI to access planner/runner via core types.\n * The SQL-specific planner/runner types are compatible with the generic\n * MigrationPlanner/MigrationRunner interfaces at runtime.\n */\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner() as MigrationPlanner<'sql', 'postgres'>;\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAWA,IAAI,iBAAiB,cAAc,MAAM;CACxC,YAAY,SAAS,OAAO,MAAM;AACjC,QAAM,QAAQ;AACd,OAAK,QAAQ;AACb,OAAK,OAAO;AACZ,OAAK,OAAO;;;;;;AAMd,MAAMA,0BAAwB;;;;;;;;;;;AAW9B,SAAS,gBAAgB,YAAY;AACpC,KAAI,WAAW,WAAW,EAAG,OAAM,IAAI,eAAe,8BAA8B,YAAY,aAAa;AAC7G,KAAI,WAAW,SAAS,KAAK,CAAE,OAAM,IAAI,eAAe,wCAAwC,WAAW,QAAQ,OAAO,MAAM,EAAE,aAAa;AAC/I,KAAI,WAAW,SAASA,wBAAuB,SAAQ,KAAK,eAAe,WAAW,MAAM,GAAG,GAAG,CAAC,4BAA4BA,wBAAsB,wCAAwC;AAC7L,QAAO,IAAI,WAAW,QAAQ,MAAM,OAAO,CAAC;;;;;;;;;;;;;AAa7C,SAAS,cAAc,OAAO;AAC7B,KAAI,MAAM,SAAS,KAAK,CAAE,OAAM,IAAI,eAAe,2CAA2C,MAAM,QAAQ,OAAO,MAAM,EAAE,UAAU;AACrI,QAAO,MAAM,QAAQ,MAAM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c,SAAmC;AAC/C,SAAO,gCAAgC;;CAMzC,aAAa,QAAQ;AACnB,SAAO,8BAA8B,OAAO;;CAE/C;AAEH,sBAAe"}
package/package.json CHANGED
@@ -1,32 +1,32 @@
1
1
  {
2
2
  "name": "@prisma-next/target-postgres",
3
- "version": "0.3.0-dev.41",
3
+ "version": "0.3.0-dev.43",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "Postgres target pack for Prisma Next",
7
7
  "dependencies": {
8
8
  "arktype": "^2.0.0",
9
- "@prisma-next/cli": "0.3.0-dev.41",
10
- "@prisma-next/contract": "0.3.0-dev.41",
11
- "@prisma-next/core-control-plane": "0.3.0-dev.41",
12
- "@prisma-next/sql-contract": "0.3.0-dev.41",
13
- "@prisma-next/family-sql": "0.3.0-dev.41",
14
- "@prisma-next/core-execution-plane": "0.3.0-dev.41",
15
- "@prisma-next/sql-errors": "0.3.0-dev.41",
16
- "@prisma-next/sql-relational-core": "0.3.0-dev.41",
17
- "@prisma-next/sql-schema-ir": "0.3.0-dev.41",
18
- "@prisma-next/sql-runtime": "0.3.0-dev.41",
19
- "@prisma-next/utils": "0.3.0-dev.41"
9
+ "@prisma-next/cli": "0.3.0-dev.43",
10
+ "@prisma-next/contract": "0.3.0-dev.43",
11
+ "@prisma-next/core-control-plane": "0.3.0-dev.43",
12
+ "@prisma-next/core-execution-plane": "0.3.0-dev.43",
13
+ "@prisma-next/family-sql": "0.3.0-dev.43",
14
+ "@prisma-next/sql-errors": "0.3.0-dev.43",
15
+ "@prisma-next/sql-contract": "0.3.0-dev.43",
16
+ "@prisma-next/sql-relational-core": "0.3.0-dev.43",
17
+ "@prisma-next/sql-schema-ir": "0.3.0-dev.43",
18
+ "@prisma-next/utils": "0.3.0-dev.43",
19
+ "@prisma-next/sql-runtime": "0.3.0-dev.43"
20
20
  },
21
21
  "devDependencies": {
22
22
  "tsdown": "0.18.4",
23
23
  "typescript": "5.9.3",
24
24
  "vitest": "4.0.17",
25
- "@prisma-next/adapter-postgres": "0.3.0-dev.41",
25
+ "@prisma-next/adapter-postgres": "0.3.0-dev.43",
26
+ "@prisma-next/driver-postgres": "0.3.0-dev.43",
27
+ "@prisma-next/test-utils": "0.0.1",
26
28
  "@prisma-next/tsconfig": "0.0.0",
27
- "@prisma-next/tsdown": "0.0.0",
28
- "@prisma-next/driver-postgres": "0.3.0-dev.41",
29
- "@prisma-next/test-utils": "0.0.1"
29
+ "@prisma-next/tsdown": "0.0.0"
30
30
  },
31
31
  "files": [
32
32
  "dist",
@@ -29,6 +29,7 @@ import {
29
29
  } from '@prisma-next/family-sql/schema-verify';
30
30
  import type {
31
31
  ForeignKey,
32
+ ReferentialAction,
32
33
  SqlContract,
33
34
  SqlStorage,
34
35
  StorageColumn,
@@ -635,12 +636,7 @@ UNIQUE (${unique.columns.map(quoteIdentifier).join(', ')})`,
635
636
  execute: [
636
637
  {
637
638
  description: `add foreign key "${fkName}"`,
638
- sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
639
- ADD CONSTRAINT ${quoteIdentifier(fkName)}
640
- FOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})
641
- REFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns
642
- .map(quoteIdentifier)
643
- .join(', ')})`,
639
+ sql: buildForeignKeySql(schemaName, tableName, fkName, foreignKey),
644
640
  },
645
641
  ],
646
642
  postcheck: [
@@ -1123,3 +1119,42 @@ function compareStrings(a?: string, b?: string): number {
1123
1119
  }
1124
1120
  return a < b ? -1 : 1;
1125
1121
  }
1122
+
1123
+ const REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {
1124
+ noAction: 'NO ACTION',
1125
+ restrict: 'RESTRICT',
1126
+ cascade: 'CASCADE',
1127
+ setNull: 'SET NULL',
1128
+ setDefault: 'SET DEFAULT',
1129
+ };
1130
+
1131
+ function buildForeignKeySql(
1132
+ schemaName: string,
1133
+ tableName: string,
1134
+ fkName: string,
1135
+ foreignKey: ForeignKey,
1136
+ ): string {
1137
+ let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}
1138
+ ADD CONSTRAINT ${quoteIdentifier(fkName)}
1139
+ FOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})
1140
+ REFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns
1141
+ .map(quoteIdentifier)
1142
+ .join(', ')})`;
1143
+
1144
+ if (foreignKey.onDelete !== undefined) {
1145
+ const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];
1146
+ if (!action) {
1147
+ throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);
1148
+ }
1149
+ sql += `\nON DELETE ${action}`;
1150
+ }
1151
+ if (foreignKey.onUpdate !== undefined) {
1152
+ const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];
1153
+ if (!action) {
1154
+ throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);
1155
+ }
1156
+ sql += `\nON UPDATE ${action}`;
1157
+ }
1158
+
1159
+ return sql;
1160
+ }