@prisma-next/target-postgres 0.3.0-dev.113 → 0.3.0-dev.114
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/dist/control.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"control.mjs","names":["MAX_IDENTIFIER_LENGTH","control_default","constraintDefinitions: string[]","REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string>","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","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-l_dv8Nnn.mjs","../../../../1-framework/2-authoring/ids/dist/index.mjs","../../../6-adapters/postgres/dist/control.mjs","../src/core/migrations/planner-identity-values.ts","../src/core/migrations/planner-sql.ts","../src/core/migrations/planner-target-details.ts","../src/core/migrations/planner-recipes.ts","../src/core/migrations/planner-reconciliation.ts","../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\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\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/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});\nfunction isPositiveInteger(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value > 0;\n}\nfunction isNonNegativeInteger(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\nfunction expandLength({ nativeType, typeParams }) {\n\tif (!typeParams || !(\"length\" in typeParams)) return nativeType;\n\tconst length = typeParams[\"length\"];\n\tif (!isPositiveInteger(length)) throw new Error(`Invalid \"length\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(length)}`);\n\treturn `${nativeType}(${length})`;\n}\nfunction expandPrecision({ nativeType, typeParams }) {\n\tif (!typeParams || !(\"precision\" in typeParams)) return nativeType;\n\tconst precision = typeParams[\"precision\"];\n\tif (!isPositiveInteger(precision)) throw new Error(`Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`);\n\treturn `${nativeType}(${precision})`;\n}\nfunction expandNumeric({ nativeType, typeParams }) {\n\tconst hasPrecision = typeParams && \"precision\" in typeParams;\n\tconst hasScale = typeParams && \"scale\" in typeParams;\n\tif (!hasPrecision && !hasScale) return nativeType;\n\tif (!hasPrecision && hasScale) throw new Error(`Invalid type parameters for \"${nativeType}\": \"scale\" requires \"precision\" to be specified`);\n\tif (hasPrecision) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (!isPositiveInteger(precision)) throw new Error(`Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`);\n\t\tif (hasScale) {\n\t\t\tconst scale = typeParams[\"scale\"];\n\t\t\tif (!isNonNegativeInteger(scale)) throw new Error(`Invalid \"scale\" type parameter for \"${nativeType}\": expected a non-negative integer, got ${JSON.stringify(scale)}`);\n\t\t\treturn `${nativeType}(${precision},${scale})`;\n\t\t}\n\t\treturn `${nativeType}(${precision})`;\n\t}\n\treturn nativeType;\n}\nconst lengthHooks = { expandNativeType: expandLength };\nconst precisionHooks = { expandNativeType: expandPrecision };\nconst numericHooks = { expandNativeType: expandNumeric };\nconst identityHooks = { expandNativeType: ({ nativeType }) => nativeType };\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]: lengthHooks,\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_CHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: numericHooks,\n\t\t\t\t[PG_BIT_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_VARBIT_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIME_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_ENUM_CODEC_ID]: pgEnumControlHooks,\n\t\t\t\t[PG_JSON_CODEC_ID]: identityHooks,\n\t\t\t\t[PG_JSONB_CODEC_ID]: identityHooks\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 { pgEnumControlHooks as n, postgresAdapterDescriptorMeta as t };\n//# sourceMappingURL=descriptor-meta-l_dv8Nnn.mjs.map","import { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/generator-ids.ts\nconst builtinGeneratorIds = [\n\t\"ulid\",\n\t\"nanoid\",\n\t\"uuidv7\",\n\t\"uuidv4\",\n\t\"cuid2\",\n\t\"ksuid\"\n];\n\n//#endregion\n//#region src/index.ts\nfunction resolveNanoidColumnDescriptor(params) {\n\tconst rawSize = params?.[\"size\"];\n\tif (rawSize === void 0) return {\n\t\ttype: {\n\t\t\tcodecId: \"sql/char@1\",\n\t\t\tnativeType: \"character\"\n\t\t},\n\t\ttypeParams: { length: 21 }\n\t};\n\tif (typeof rawSize !== \"number\" || !Number.isInteger(rawSize) || rawSize < 2 || rawSize > 255) throw new Error(\"nanoid size must be an integer between 2 and 255\");\n\treturn {\n\t\ttype: {\n\t\t\tcodecId: \"sql/char@1\",\n\t\t\tnativeType: \"character\"\n\t\t},\n\t\ttypeParams: { length: rawSize }\n\t};\n}\nconst builtinGeneratorMetadataById = {\n\tulid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 26 }\n\t\t}\n\t},\n\tnanoid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 21 }\n\t\t},\n\t\tresolveGeneratedColumnDescriptor: resolveNanoidColumnDescriptor\n\t},\n\tuuidv7: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 36 }\n\t\t}\n\t},\n\tuuidv4: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 36 }\n\t\t}\n\t},\n\tcuid2: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 24 }\n\t\t}\n\t},\n\tksuid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 27 }\n\t\t}\n\t}\n};\nconst builtinGeneratorRegistryMetadata = builtinGeneratorIds.map((id) => ({\n\tid,\n\tapplicableCodecIds: builtinGeneratorMetadataById[id].applicableCodecIds\n}));\nfunction resolveBuiltinGeneratedColumnDescriptor(input) {\n\tconst metadata = builtinGeneratorMetadataById[input.id];\n\tconst resolver = metadata.resolveGeneratedColumnDescriptor;\n\tif (resolver) return resolver(input.params);\n\treturn metadata.generatedColumnDescriptor;\n}\nfunction createGeneratedSpec(id, options) {\n\tconst params = options;\n\tconst resolvedDescriptor = resolveBuiltinGeneratedColumnDescriptor({\n\t\tid,\n\t\t...ifDefined(\"params\", params)\n\t});\n\treturn {\n\t\ttype: resolvedDescriptor.type,\n\t\tnullable: false,\n\t\t...ifDefined(\"typeParams\", resolvedDescriptor.typeParams),\n\t\tgenerated: {\n\t\t\tkind: \"generator\",\n\t\t\tid,\n\t\t\t...ifDefined(\"params\", params)\n\t\t}\n\t};\n}\nconst ulid = (options) => createGeneratedSpec(\"ulid\", options);\nconst nanoid = (options) => createGeneratedSpec(\"nanoid\", options);\nconst uuidv7 = (options) => createGeneratedSpec(\"uuidv7\", options);\nconst uuidv4 = (options) => createGeneratedSpec(\"uuidv4\", options);\nconst cuid2 = (options) => createGeneratedSpec(\"cuid2\", options);\nconst ksuid = (options) => createGeneratedSpec(\"ksuid\", options);\n\n//#endregion\nexport { builtinGeneratorIds, builtinGeneratorRegistryMetadata, cuid2, ksuid, nanoid, resolveBuiltinGeneratedColumnDescriptor, ulid, uuidv4, uuidv7 };\n//# sourceMappingURL=index.mjs.map","import { i as quoteIdentifier, n as escapeLiteral, r as qualifyName, t as SqlEscapeError } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { n as pgEnumControlHooks, t as postgresAdapterDescriptorMeta } from \"./descriptor-meta-l_dv8Nnn.mjs\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\nimport { builtinGeneratorRegistryMetadata, resolveBuiltinGeneratedColumnDescriptor } from \"@prisma-next/ids\";\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 NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/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* Returns the canonical expression for a timestamp default function, or undefined\n* if the expression is not a recognized timestamp default.\n*\n* Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n* - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n* - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n*\n* These are semantically different in Postgres: now() returns the transaction\n* start time (constant within a transaction), while clock_timestamp() returns\n* the actual wall-clock time (can differ across rows in a single INSERT).\n*/\nfunction canonicalizeTimestampDefault(expr) {\n\tif (NOW_FUNCTION_PATTERN.test(expr)) return \"now()\";\n\tif (CLOCK_TIMESTAMP_PATTERN.test(expr)) return \"clock_timestamp()\";\n\tif (!TIMESTAMP_CAST_SUFFIX.test(expr)) return void 0;\n\tlet inner = expr.replace(TIMESTAMP_CAST_SUFFIX, \"\").trim();\n\tif (inner.startsWith(\"(\") && inner.endsWith(\")\")) inner = inner.slice(1, -1).trim();\n\tif (NOW_FUNCTION_PATTERN.test(inner)) return \"now()\";\n\tif (CLOCK_TIMESTAMP_PATTERN.test(inner)) return \"clock_timestamp()\";\n\tinner = inner.replace(TEXT_CAST_SUFFIX, \"\").trim();\n\tif (NOW_LITERAL_PATTERN.test(inner)) return \"now()\";\n}\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, used for type-aware parsing (bigint tagging, JSON detection)\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\tconst canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n\tif (canonicalTimestamp) return {\n\t\tkind: \"function\",\n\t\texpression: canonicalTimestamp\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 (NULL_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: null\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\tconst num = Number(trimmed);\n\t\tif (!Number.isFinite(num)) return void 0;\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: num\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 dependencies = extensionsResult.rows.map((row) => ({ id: `postgres.extension.${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\tdependencies,\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/core/control-mutation-defaults.ts\nfunction invalidArgumentDiagnostic(input) {\n\treturn {\n\t\tok: false,\n\t\tdiagnostic: {\n\t\t\tcode: \"PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT\",\n\t\t\tmessage: input.message,\n\t\t\tsourceId: input.context.sourceId,\n\t\t\tspan: input.span\n\t\t}\n\t};\n}\nfunction executionGenerator(id, params) {\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"execution\",\n\t\t\tgenerated: {\n\t\t\t\tkind: \"generator\",\n\t\t\t\tid,\n\t\t\t\t...params ? { params } : {}\n\t\t\t}\n\t\t}\n\t};\n}\nfunction expectNoArgs(input) {\n\tif (input.call.args.length === 0) return;\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: `Default function \"${input.call.name}\" does not accept arguments. Use ${input.usage}.`\n\t});\n}\nfunction parseIntegerArgument(raw) {\n\tconst trimmed = raw.trim();\n\tif (!/^-?\\d+$/.test(trimmed)) return;\n\tconst value = Number(trimmed);\n\tif (!Number.isInteger(value)) return;\n\treturn value;\n}\nfunction parseStringLiteral(raw) {\n\tconst match = raw.trim().match(/^(['\"])(.*)\\1$/s);\n\tif (!match) return;\n\treturn match[2] ?? \"\";\n}\nfunction lowerAutoincrement(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`autoincrement()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: \"autoincrement()\"\n\t\t\t}\n\t\t}\n\t};\n}\nfunction lowerNow(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`now()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: \"now()\"\n\t\t\t}\n\t\t}\n\t};\n}\nfunction lowerUuid(input) {\n\tif (input.call.args.length === 0) return executionGenerator(\"uuidv4\");\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"uuid\\\" accepts at most one version argument: `uuid()`, `uuid(4)`, or `uuid(7)`.\"\n\t});\n\tconst version = parseIntegerArgument(input.call.args[0]?.raw ?? \"\");\n\tif (version === 4) return executionGenerator(\"uuidv4\");\n\tif (version === 7) return executionGenerator(\"uuidv7\");\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"uuid\\\" supports only `uuid()`, `uuid(4)`, or `uuid(7)` in SQL PSL provider v1.\"\n\t});\n}\nfunction lowerCuid(input) {\n\tif (input.call.args.length === 0) return {\n\t\tok: false,\n\t\tdiagnostic: {\n\t\t\tcode: \"PSL_UNKNOWN_DEFAULT_FUNCTION\",\n\t\t\tmessage: \"Default function \\\"cuid()\\\" is not supported in SQL PSL provider v1. Use `cuid(2)` instead.\",\n\t\t\tsourceId: input.context.sourceId,\n\t\t\tspan: input.call.span\n\t\t}\n\t};\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"cuid\\\" accepts exactly one version argument: `cuid(2)`.\"\n\t});\n\tif (parseIntegerArgument(input.call.args[0]?.raw ?? \"\") === 2) return executionGenerator(\"cuid2\");\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"cuid\\\" supports only `cuid(2)` in SQL PSL provider v1.\"\n\t});\n}\nfunction lowerUlid(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`ulid()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn executionGenerator(\"ulid\");\n}\nfunction lowerNanoid(input) {\n\tif (input.call.args.length === 0) return executionGenerator(\"nanoid\");\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"nanoid\\\" accepts at most one size argument: `nanoid()` or `nanoid(<2-255>)`.\"\n\t});\n\tconst size = parseIntegerArgument(input.call.args[0]?.raw ?? \"\");\n\tif (size !== void 0 && size >= 2 && size <= 255) return executionGenerator(\"nanoid\", { size });\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"nanoid\\\" size argument must be an integer between 2 and 255.\"\n\t});\n}\nfunction lowerDbgenerated(input) {\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" requires exactly one string argument: `dbgenerated(\\\"...\\\")`.\"\n\t});\n\tconst rawExpression = parseStringLiteral(input.call.args[0]?.raw ?? \"\");\n\tif (rawExpression === void 0) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" argument must be a string literal.\"\n\t});\n\tif (rawExpression.trim().length === 0) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" argument cannot be empty.\"\n\t});\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: rawExpression\n\t\t\t}\n\t\t}\n\t};\n}\nconst postgresDefaultFunctionRegistryEntries = [\n\t[\"autoincrement\", {\n\t\tlower: lowerAutoincrement,\n\t\tusageSignatures: [\"autoincrement()\"]\n\t}],\n\t[\"now\", {\n\t\tlower: lowerNow,\n\t\tusageSignatures: [\"now()\"]\n\t}],\n\t[\"uuid\", {\n\t\tlower: lowerUuid,\n\t\tusageSignatures: [\n\t\t\t\"uuid()\",\n\t\t\t\"uuid(4)\",\n\t\t\t\"uuid(7)\"\n\t\t]\n\t}],\n\t[\"cuid\", {\n\t\tlower: lowerCuid,\n\t\tusageSignatures: [\"cuid(2)\"]\n\t}],\n\t[\"ulid\", {\n\t\tlower: lowerUlid,\n\t\tusageSignatures: [\"ulid()\"]\n\t}],\n\t[\"nanoid\", {\n\t\tlower: lowerNanoid,\n\t\tusageSignatures: [\"nanoid()\", \"nanoid(<2-255>)\"]\n\t}],\n\t[\"dbgenerated\", {\n\t\tlower: lowerDbgenerated,\n\t\tusageSignatures: [\"dbgenerated(\\\"...\\\")\"]\n\t}]\n];\nconst postgresPslScalarTypeDescriptors = new Map([\n\t[\"String\", {\n\t\tcodecId: \"pg/text@1\",\n\t\tnativeType: \"text\"\n\t}],\n\t[\"Boolean\", {\n\t\tcodecId: \"pg/bool@1\",\n\t\tnativeType: \"bool\"\n\t}],\n\t[\"Int\", {\n\t\tcodecId: \"pg/int4@1\",\n\t\tnativeType: \"int4\"\n\t}],\n\t[\"BigInt\", {\n\t\tcodecId: \"pg/int8@1\",\n\t\tnativeType: \"int8\"\n\t}],\n\t[\"Float\", {\n\t\tcodecId: \"pg/float8@1\",\n\t\tnativeType: \"float8\"\n\t}],\n\t[\"Decimal\", {\n\t\tcodecId: \"pg/numeric@1\",\n\t\tnativeType: \"numeric\"\n\t}],\n\t[\"DateTime\", {\n\t\tcodecId: \"pg/timestamptz@1\",\n\t\tnativeType: \"timestamptz\"\n\t}],\n\t[\"Json\", {\n\t\tcodecId: \"pg/jsonb@1\",\n\t\tnativeType: \"jsonb\"\n\t}],\n\t[\"Bytes\", {\n\t\tcodecId: \"pg/bytea@1\",\n\t\tnativeType: \"bytea\"\n\t}]\n]);\nfunction createPostgresDefaultFunctionRegistry() {\n\treturn new Map(postgresDefaultFunctionRegistryEntries);\n}\nfunction createPostgresMutationDefaultGeneratorDescriptors() {\n\treturn builtinGeneratorRegistryMetadata.map(({ id, applicableCodecIds }) => ({\n\t\tid,\n\t\tapplicableCodecIds,\n\t\tresolveGeneratedColumnDescriptor: ({ generated }) => {\n\t\t\tif (generated.kind !== \"generator\" || generated.id !== id) return;\n\t\t\tconst descriptor = resolveBuiltinGeneratedColumnDescriptor({\n\t\t\t\tid,\n\t\t\t\t...generated.params ? { params: generated.params } : {}\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tcodecId: descriptor.type.codecId,\n\t\t\t\tnativeType: descriptor.type.nativeType,\n\t\t\t\t...descriptor.type.typeRef ? { typeRef: descriptor.type.typeRef } : {},\n\t\t\t\t...descriptor.typeParams ? { typeParams: descriptor.typeParams } : {}\n\t\t\t};\n\t\t}\n\t}));\n}\nfunction createPostgresPslScalarTypeDescriptors() {\n\treturn new Map(postgresPslScalarTypeDescriptors);\n}\n\n//#endregion\n//#region src/exports/control.ts\nconst postgresAdapterDescriptor = {\n\t...postgresAdapterDescriptorMeta,\n\toperationSignatures: () => [],\n\tpslTypeDescriptors: () => ({ scalarTypeDescriptors: createPostgresPslScalarTypeDescriptors() }),\n\tcontrolMutationDefaults: () => ({\n\t\tdefaultFunctionRegistry: createPostgresDefaultFunctionRegistry(),\n\t\tgeneratorDescriptors: createPostgresMutationDefaultGeneratorDescriptors()\n\t}),\n\tcreate() {\n\t\treturn new PostgresControlAdapter();\n\t}\n};\nvar control_default = postgresAdapterDescriptor;\n\n//#endregion\nexport { SqlEscapeError, control_default as default, escapeLiteral, normalizeSchemaNativeType, parsePostgresDefault, qualifyName, quoteIdentifier };\n//# sourceMappingURL=control.mjs.map","import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\n/**\n * Resolves the identity value (monoid neutral element) as a SQL literal for a column's type.\n * Checks codec hooks first (extensions can provide type-specific identity values),\n * then falls back to the built-in map.\n */\nexport function resolveIdentityValue(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): string | null {\n if (column.codecId) {\n const hookDefault = codecHooks.get(column.codecId)?.resolveIdentityValue?.({\n nativeType: column.nativeType,\n codecId: column.codecId,\n ...ifDefined('typeParams', column.typeParams),\n });\n if (hookDefault !== undefined) {\n return hookDefault;\n }\n }\n\n return buildBuiltinIdentityValue(column.nativeType, column.typeParams);\n}\n\n/**\n * Returns the built-in identity value (monoid neutral element) as a SQL literal for the given\n * PostgreSQL native type — e.g. 0 for integers, '' for text, false for booleans.\n *\n * This is the planner's fallback when no codec hook provides a type-specific identity value.\n *\n * Returns null for unrecognized types (for example enums and extension-owned types without a\n * hook), which causes the planner to fall back to the empty-table precheck.\n *\n * @internal Exported for testing only.\n */\nexport function buildBuiltinIdentityValue(\n nativeType: string,\n typeParams?: Record<string, unknown>,\n): string | null {\n const normalizedNativeType = normalizeIdentityValueNativeType(nativeType);\n\n if (normalizedNativeType.endsWith('[]')) {\n return \"'{}'\";\n }\n\n switch (normalizedNativeType) {\n case 'text':\n case 'character':\n case 'bpchar':\n case 'character varying':\n case 'varchar':\n return \"''\";\n\n case 'int2':\n case 'int4':\n case 'int8':\n case 'integer':\n case 'bigint':\n case 'smallint':\n case 'float4':\n case 'float8':\n case 'real':\n case 'double precision':\n case 'numeric':\n case 'decimal':\n return '0';\n\n case 'bool':\n case 'boolean':\n return 'false';\n\n case 'uuid':\n return \"'00000000-0000-0000-0000-000000000000'\";\n\n case 'json':\n return \"'{}'::json\";\n case 'jsonb':\n return \"'{}'::jsonb\";\n\n case 'date':\n case 'timestamp':\n case 'timestamptz':\n case 'timestamp with time zone':\n case 'timestamp without time zone':\n return \"'epoch'\";\n\n case 'time':\n case 'time without time zone':\n return \"'00:00:00'\";\n case 'timetz':\n case 'time with time zone':\n return \"'00:00:00+00'\";\n\n case 'interval':\n return \"'0'\";\n\n case 'bytea':\n return \"''::bytea\";\n case 'tsvector':\n return \"''::tsvector\";\n\n case 'bit':\n return buildBitIdentityValue(typeParams);\n case 'bit varying':\n case 'varbit':\n return \"B''\";\n\n default:\n return null;\n }\n}\n\nfunction normalizeIdentityValueNativeType(nativeType: string): string {\n return nativeType.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nfunction buildBitIdentityValue(typeParams?: Record<string, unknown>): string | null {\n const length = typeParams?.['length'];\n if (length === undefined) {\n return \"B'0'\";\n }\n if (typeof length !== 'number' || !Number.isInteger(length) || length <= 0) {\n return null;\n }\n return `B'${'0'.repeat(length)}'`;\n}\n","import { escapeLiteral, quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport { isTaggedBigInt } from '@prisma-next/contract/types';\nimport type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type {\n ForeignKey,\n ReferentialAction,\n StorageColumn,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\nimport type { PostgresColumnDefault } from '../types';\n\nexport function buildCreateTableSql(\n qualifiedTableName: string,\n table: StorageTable,\n codecHooks: Map<string, CodecControlHooks>,\n): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column, codecHooks),\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 * Pattern for safe PostgreSQL type names.\n * Allows letters, digits, underscores, spaces (for \"double precision\", \"character varying\"),\n * and trailing [] for array types.\n */\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*(\\[\\])?$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*(\\\\[\\\\])?$/',\n );\n }\n}\n\n/**\n * Sanity check against accidental SQL injection from malformed contract files.\n * Rejects semicolons, SQL comment tokens, and dollar-quoting.\n * Not a comprehensive security boundary — the contract is developer-authored.\n */\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\$\\$|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, dollar-quoting, or subqueries.',\n );\n }\n}\n\nexport function buildColumnTypeSql(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): string {\n const columnDefault = column.default;\n\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 assertSafeNativeType(column.nativeType);\n return renderParameterizedTypeSql(column, codecHooks) ?? column.nativeType;\n}\n\nfunction renderParameterizedTypeSql(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n if (!column.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(column.codecId);\n if (!hooks?.expandNativeType) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${column.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n\n const expanded = hooks.expandNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n return expanded !== column.nativeType ? expanded : null;\n}\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 if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n return `DEFAULT nextval(${quoteIdentifier(columnDefault.name)}::regclass)`;\n }\n}\n\nexport function 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\nexport function qualifyTableName(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\nexport function toRegclassLiteral(schema: string, name: string): string {\n const regclass = `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`;\n return `'${escapeLiteral(regclass)}'`;\n}\n\nexport function 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\nexport function 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\nexport function columnNullabilityCheck({\n schema,\n table,\n column,\n nullable,\n}: {\n schema: string;\n table: string;\n column: string;\n nullable: boolean;\n}): string {\n const expected = nullable ? 'YES' : 'NO';\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 = '${expected}'\n)`;\n}\n\nexport function tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nexport function columnHasNoDefaultCheck(opts: {\n schema: string;\n table: string;\n column: string;\n}): string {\n return `SELECT NOT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(opts.schema)}'\n AND table_name = '${escapeLiteral(opts.table)}'\n AND column_name = '${escapeLiteral(opts.column)}'\n AND column_default IS NOT NULL\n)`;\n}\n\nexport function buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n defaultLiteral?: string | null,\n): string {\n const typeSql = buildColumnTypeSql(column, codecHooks);\n const defaultSql =\n buildColumnDefaultSql(column.default, column) ||\n (defaultLiteral != null ? `DEFAULT ${defaultLiteral}` : '');\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\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\nexport function 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 { ifDefined } from '@prisma-next/utils/defined';\nimport type { OperationClass, PostgresPlanTargetDetails } from './planner';\n\nexport function 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","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { StorageColumn } from '@prisma-next/sql-contract/types';\nimport type { PostgresPlanTargetDetails } from './planner';\nimport {\n buildAddColumnSql,\n columnExistsCheck,\n columnHasNoDefaultCheck,\n columnNullabilityCheck,\n qualifyTableName,\n} from './planner-sql';\nimport { buildTargetDetails } from './planner-target-details';\n\nexport function buildAddColumnOperationIdentity(\n schema: string,\n tableName: string,\n columnName: string,\n): Pick<\n SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n 'id' | 'label' | 'summary' | 'target'\n> {\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schema),\n },\n };\n}\n\nexport function buildAddNotNullColumnWithTemporaryDefaultOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly temporaryDefault: string;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const { schema, tableName, columnName, column, codecHooks, temporaryDefault } = options;\n const qualified = qualifyTableName(schema, tableName);\n\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(qualified, columnName, column, codecHooks, temporaryDefault),\n },\n {\n description: `drop temporary default from column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n {\n description: `verify column \"${columnName}\" has no default after temporary default removal`,\n sql: columnHasNoDefaultCheck({ schema, table: tableName, column: columnName }),\n },\n ],\n };\n}\n","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport type { SqlContract, SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PlanningMode, PostgresPlanTargetDetails } from './planner';\nimport {\n buildColumnTypeSql,\n columnExistsCheck,\n columnNullabilityCheck,\n constraintExistsCheck,\n qualifyTableName,\n toRegclassLiteral,\n} from './planner-sql';\nimport { buildTargetDetails } from './planner-target-details';\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nexport function buildReconciliationPlan(options: {\n readonly contract: SqlContract<SqlStorage>;\n readonly issues: readonly SchemaIssue[];\n readonly schemaName: string;\n readonly mode: PlanningMode;\n readonly policy: MigrationOperationPolicy;\n readonly 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 { mode } = options;\n const seenOperationIds = new Set<string>();\n\n for (const issue of sortSchemaIssues(options.issues)) {\n if (isAdditiveIssue(issue)) {\n continue;\n }\n\n const operation = buildReconciliationOperationFromIssue({\n issue,\n contract: options.contract,\n schemaName: options.schemaName,\n mode,\n codecHooks: options.codecHooks,\n });\n\n if (operation) {\n // Skip duplicates: different schema issues may produce the same operation id\n // (e.g., extra_unique_constraint and extra_index on the same object).\n if (!seenOperationIds.has(operation.id)) {\n seenOperationIds.add(operation.id);\n if (options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n operations.push(operation);\n } else {\n const conflict = convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n } else {\n const conflict = convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n\n return {\n operations,\n conflicts: conflicts.sort(conflictComparator),\n };\n}\n\n// ============================================================================\n// Issue Classification\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 'dependency_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\n// ============================================================================\n// Operation Builders\n// ============================================================================\n\nfunction buildReconciliationOperationFromIssue(options: {\n readonly issue: SchemaIssue;\n readonly contract: SqlContract<SqlStorage>;\n readonly schemaName: string;\n readonly mode: PlanningMode;\n readonly codecHooks: Map<string, CodecControlHooks>;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const { issue, contract, schemaName, mode, codecHooks } = options;\n switch (issue.kind) {\n case 'extra_table':\n if (!mode.allowDestructive || !issue.table) {\n return null;\n }\n return buildDropTableOperation(schemaName, issue.table);\n\n case 'extra_column':\n if (!mode.allowDestructive || !issue.table || !issue.column) {\n return null;\n }\n return buildDropColumnOperation(schemaName, issue.table, issue.column);\n\n case 'extra_index':\n if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) {\n return null;\n }\n return buildDropIndexOperation(schemaName, issue.table, issue.indexOrConstraint);\n\n case 'extra_foreign_key':\n case 'extra_unique_constraint': {\n if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) {\n return null;\n }\n const constraintKind = issue.kind === 'extra_foreign_key' ? 'foreignKey' : 'unique';\n return buildDropConstraintOperation(\n schemaName,\n issue.table,\n issue.indexOrConstraint,\n constraintKind,\n );\n }\n\n case 'extra_primary_key': {\n if (!mode.allowDestructive || !issue.table) {\n return null;\n }\n const constraintName = issue.indexOrConstraint ?? `${issue.table}_pkey`;\n return buildDropConstraintOperation(schemaName, issue.table, constraintName, 'primaryKey');\n }\n\n case 'nullability_mismatch': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (issue.expected === 'true') {\n // Contract wants nullable, DB has NOT NULL → widening\n return mode.allowWidening\n ? buildDropNotNullOperation(schemaName, issue.table, issue.column)\n : null;\n }\n // Contract wants NOT NULL, DB has nullable → destructive\n return mode.allowDestructive\n ? buildSetNotNullOperation(schemaName, issue.table, issue.column)\n : null;\n }\n\n case 'type_mismatch': {\n if (!mode.allowDestructive || !issue.table || !issue.column) {\n return null;\n }\n const contractColumn = getContractColumn(contract, issue.table, issue.column);\n if (!contractColumn) {\n return null;\n }\n return buildAlterColumnTypeOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColumn,\n codecHooks,\n );\n }\n\n // Remaining issue kinds (default_missing, default_mismatch, primary_key_mismatch,\n // unique_constraint_mismatch, index_mismatch, foreign_key_mismatch) do not yet have\n // reconciliation operation builders. They fall through to the caller, which converts them to\n // conflicts via convertIssueToConflict. When a new SchemaIssue kind is added, add a\n // case here if the planner can emit an operation for it; otherwise it becomes a conflict.\n default:\n return null;\n }\n}\n\nfunction getContractColumn(\n contract: SqlContract<SqlStorage>,\n tableName: string,\n columnName: string,\n): StorageColumn | null {\n const table = contract.storage.tables[tableName];\n if (!table) {\n return null;\n }\n return table.columns[columnName] ?? null;\n}\n\nfunction buildDropTableOperation(\n schemaName: string,\n tableName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops extra table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n execute: [\n {\n description: `drop table \"${tableName}\"`,\n sql: `DROP TABLE ${qualifyTableName(schemaName, tableName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" is removed`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n };\n}\n\nfunction buildDropColumnOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} from ${tableName}`,\n summary: `Drops extra column ${columnName} from table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" is removed`,\n sql: columnExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: false,\n }),\n },\n ],\n };\n}\n\nfunction buildDropIndexOperation(\n schemaName: string,\n tableName: string,\n indexName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops extra index ${indexName} on table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n execute: [\n {\n description: `drop index \"${indexName}\"`,\n sql: `DROP INDEX ${qualifyTableName(schemaName, indexName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" is removed`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n };\n}\n\nfunction buildDropConstraintOperation(\n schemaName: string,\n tableName: string,\n constraintName: string,\n constraintKind: 'foreignKey' | 'unique' | 'primaryKey',\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropConstraint.${tableName}.${constraintName}`,\n label: `Drop constraint ${constraintName} on ${tableName}`,\n summary: `Drops extra constraint ${constraintName} on table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails(constraintKind, constraintName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName }),\n },\n ],\n execute: [\n {\n description: `drop constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nDROP CONSTRAINT ${quoteIdentifier(constraintName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify constraint \"${constraintName}\" is removed`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName, exists: false }),\n },\n ],\n };\n}\n\nfunction buildDropNotNullOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `alterNullability.${tableName}.${columnName}`,\n label: `Relax nullability for ${columnName} on ${tableName}`,\n summary: `Drops NOT NULL constraint for ${columnName} on table ${tableName}`,\n operationClass: 'widening',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop NOT NULL from \"${columnName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nALTER COLUMN ${quoteIdentifier(columnName)} DROP NOT NULL`,\n },\n ],\n postcheck: [\n {\n description: `verify \"${columnName}\" is nullable`,\n sql: columnNullabilityCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: true,\n }),\n },\n ],\n };\n}\n\nfunction buildSetNotNullOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n return {\n id: `alterNullability.${tableName}.${columnName}`,\n label: `Enforce NOT NULL for ${columnName} on ${tableName}`,\n summary: `Sets NOT NULL on ${columnName} for table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n {\n description: `ensure \"${columnName}\" has no NULL values`,\n sql: `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualified}\n WHERE ${quoteIdentifier(columnName)} IS NULL\n LIMIT 1\n)`,\n },\n ],\n execute: [\n {\n description: `set NOT NULL on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\nALTER COLUMN ${quoteIdentifier(columnName)} SET NOT NULL`,\n },\n ],\n postcheck: [\n {\n description: `verify \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ],\n };\n}\n\nfunction buildAlterColumnTypeOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n const expectedType = buildColumnTypeSql(column, codecHooks);\n return {\n id: `alterType.${tableName}.${columnName}`,\n label: `Alter type for ${columnName} on ${tableName}`,\n summary: `Changes type of ${columnName} to ${expectedType}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n meta: {\n warning: 'TABLE_REWRITE',\n detail:\n 'ALTER COLUMN TYPE requires a full table rewrite and acquires an ACCESS EXCLUSIVE lock. On large tables, this can cause significant downtime.',\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `alter type of \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\nALTER COLUMN ${quoteIdentifier(columnName)}\nTYPE ${expectedType}\nUSING ${quoteIdentifier(columnName)}::${expectedType}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists after type change`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n };\n}\n\n// ============================================================================\n// Conflict Conversion\n// ============================================================================\n\nfunction convertIssueToConflict(issue: SchemaIssue): SqlPlannerConflict | null {\n switch (issue.kind) {\n case 'type_mismatch':\n return buildConflict('typeMismatch', issue);\n case 'nullability_mismatch':\n return buildConflict('nullabilityConflict', issue);\n case 'default_missing':\n case 'default_mismatch':\n case 'extra_table':\n case 'extra_column':\n case 'extra_primary_key':\n case 'extra_foreign_key':\n case 'extra_unique_constraint':\n case 'extra_index':\n return buildConflict('missingButNonAdditive', issue);\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n return buildConflict('indexIncompatible', issue);\n case 'foreign_key_mismatch':\n return buildConflict('foreignKeyConflict', issue);\n // Additive issue kinds (missing_table, missing_column, type_missing, type_values_mismatch,\n // dependency_missing) are filtered by isAdditiveIssue before reaching this method.\n // If a new SchemaIssue kind is introduced, add a mapping here so it becomes a conflict\n // rather than being silently ignored.\n default:\n return null;\n }\n}\n\nfunction 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// ============================================================================\n// Sorting and Comparison Helpers\n// ============================================================================\n\nfunction sortSchemaIssues(issues: readonly SchemaIssue[]): readonly SchemaIssue[] {\n return [...issues].sort((a, b) => {\n const kindCompare = a.kind.localeCompare(b.kind);\n if (kindCompare !== 0) {\n return kindCompare;\n }\n const tableCompare = compareStrings(a.table, b.table);\n if (tableCompare !== 0) {\n return tableCompare;\n }\n const columnCompare = compareStrings(a.column, b.column);\n if (columnCompare !== 0) {\n return columnCompare;\n }\n return compareStrings(a.indexOrConstraint, b.indexOrConstraint);\n });\n}\n\nfunction buildConflictLocation(issue: SchemaIssue) {\n const location = {\n ...ifDefined('table', issue.table),\n ...ifDefined('column', issue.column),\n ...ifDefined('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 {\n escapeLiteral,\n normalizeSchemaNativeType,\n parsePostgresDefault,\n quoteIdentifier,\n} from '@prisma-next/adapter-postgres/control';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\n CodecControlHooks,\n ComponentDatabaseDependency,\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport {\n collectInitDependencies,\n createMigrationPlan,\n extractCodecControlHooks,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { ForeignKey, StorageColumn, StorageTable } from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { resolveIdentityValue } from './planner-identity-values';\nimport {\n buildAddColumnOperationIdentity,\n buildAddNotNullColumnWithTemporaryDefaultOperation,\n} from './planner-recipes';\nimport { buildReconciliationPlan } from './planner-reconciliation';\nimport {\n buildAddColumnSql,\n buildCreateTableSql,\n buildForeignKeySql,\n columnExistsCheck,\n columnNullabilityCheck,\n constraintExistsCheck,\n qualifyTableName,\n tableIsEmptyCheck,\n toRegclassLiteral,\n} from './planner-sql';\nimport { buildTargetDetails } from './planner-target-details';\n\nexport type OperationClass =\n | 'dependency'\n | 'type'\n | 'table'\n | 'column'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | '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};\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\nexport interface PlanningMode {\n readonly includeExtraObjects: boolean;\n readonly allowWidening: boolean;\n readonly allowDestructive: boolean;\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 planningMode = this.resolvePlanningMode(options.policy);\n const schemaIssues = this.collectSchemaIssues(options, planningMode.includeExtraObjects);\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 reconciliationPlan = buildReconciliationPlan({\n contract: options.contract,\n issues: schemaIssues,\n schemaName,\n mode: planningMode,\n policy: options.policy,\n codecHooks,\n });\n if (reconciliationPlan.conflicts.length > 0) {\n return plannerFailure(reconciliationPlan.conflicts);\n }\n\n const storageTypePlan = this.buildStorageTypeOperations(options, schemaName, codecHooks);\n if (storageTypePlan.conflicts.length > 0) {\n return plannerFailure(storageTypePlan.conflicts);\n }\n\n // Sort table entries once for reuse across all additive operation builders.\n const sortedTables = sortedEntries(options.contract.storage.tables);\n\n // Pre-compute constraint lookups once per schema table for O(1) checks across all builders.\n const schemaLookups = buildSchemaLookupMap(options.schema);\n\n // Build extension operations from component-owned database dependencies\n operations.push(\n ...this.buildDatabaseDependencyOperations(options),\n ...storageTypePlan.operations,\n ...reconciliationPlan.operations,\n ...this.buildTableOperations(sortedTables, options.schema, schemaName, codecHooks),\n ...this.buildColumnOperations(\n sortedTables,\n options.schema,\n schemaLookups,\n schemaName,\n codecHooks,\n ),\n ...this.buildPrimaryKeyOperations(sortedTables, options.schema, schemaName),\n ...this.buildUniqueOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildIndexOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildFkBackingIndexOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildForeignKeyOperations(sortedTables, schemaLookups, schemaName),\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: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\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 const installedIds = new Set(options.schema.dependencies.map((d) => d.id));\n\n for (const dependency of dependencies) {\n if (seenDependencyIds.has(dependency.id)) {\n continue;\n }\n seenDependencyIds.add(dependency.id);\n\n if (installedIds.has(dependency.id)) {\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 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 dependencies = collectInitDependencies(options.frameworkComponents);\n return sortDependencies(dependencies.filter(isPostgresPlannerDependency));\n }\n\n private buildTableOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of 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, codecHooks),\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: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const schemaTable = schema.tables[tableName];\n if (!schemaTable) {\n continue;\n }\n const schemaLookup = schemaLookups.get(tableName);\n for (const [columnName, column] of sortedEntries(table.columns)) {\n if (schemaTable.columns[columnName]) {\n continue;\n }\n operations.push(\n this.buildAddColumnOperation({\n schema: schemaName,\n tableName,\n table,\n schemaTable,\n schemaLookup,\n columnName,\n column,\n codecHooks,\n }),\n );\n }\n }\n return operations;\n }\n\n private buildAddColumnOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: SchemaTableLookup | undefined;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n }): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const { schema, tableName, table, schemaTable, schemaLookup, columnName, column, codecHooks } =\n options;\n const notNull = column.nullable === false;\n const hasDefault = column.default !== undefined;\n // Planner logic decides whether this column needs the coordinated multi-step\n // strategy. The strategy recipe itself is built by a dedicated helper.\n const needsTemporaryDefault = notNull && !hasDefault;\n const temporaryDefault = needsTemporaryDefault\n ? resolveIdentityValue(column, codecHooks)\n : null;\n const canUseSharedTemporaryDefault =\n needsTemporaryDefault &&\n temporaryDefault !== null &&\n canUseSharedTemporaryDefaultStrategy({\n table,\n schemaTable,\n schemaLookup,\n columnName,\n });\n\n if (canUseSharedTemporaryDefault) {\n return buildAddNotNullColumnWithTemporaryDefaultOperation({\n schema,\n tableName,\n columnName,\n column,\n codecHooks,\n temporaryDefault,\n });\n }\n\n const qualified = qualifyTableName(schema, tableName);\n const requiresEmptyTableCheck = needsTemporaryDefault && !canUseSharedTemporaryDefault;\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ...(requiresEmptyTableCheck\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 execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(qualified, columnName, column, codecHooks),\n },\n ],\n 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: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ]\n : []),\n ],\n };\n }\n\n private buildPrimaryKeyOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of 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: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const unique of table.uniques) {\n if (lookup && hasUniqueConstraint(lookup, 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: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const index of table.indexes) {\n if (lookup && hasIndex(lookup, index.columns)) {\n continue;\n }\n const indexName = index.name ?? defaultIndexName(tableName, index.columns);\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: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(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 (lookup && hasIndex(lookup, fk.columns)) continue;\n\n const indexName = defaultIndexName(tableName, fk.columns);\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: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false) continue;\n if (lookup && hasForeignKey(lookup, 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 buildTargetDetails(objectType, name, schema, table);\n }\n\n private resolvePlanningMode(policy: MigrationOperationPolicy): PlanningMode {\n const allowWidening = policy.allowedOperationClasses.includes('widening');\n const allowDestructive = policy.allowedOperationClasses.includes('destructive');\n // `db init` uses additive-only policy and intentionally ignores extras.\n // Any reconciliation-capable policy should inspect extras to reconcile strict equality.\n const includeExtraObjects = allowWidening || allowDestructive;\n return { includeExtraObjects, allowWidening, allowDestructive };\n }\n\n private collectSchemaIssues(\n options: PlannerOptionsWithComponents,\n strict: boolean,\n ): readonly SchemaIssue[] {\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n\nfunction canUseSharedTemporaryDefaultStrategy(options: {\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: SchemaTableLookup | undefined;\n readonly columnName: string;\n}): boolean {\n const { table, schemaTable, schemaLookup, columnName } = options;\n\n // Shared placeholders are only safe when later plan steps do not require\n // row-specific values for this newly added column.\n if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) {\n return false;\n }\n\n for (const unique of table.uniques) {\n if (!unique.columns.includes(columnName)) {\n continue;\n }\n if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) {\n return false;\n }\n }\n\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false || !foreignKey.columns.includes(columnName)) {\n continue;\n }\n if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction isPostgresPlannerDependency(\n dependency: ComponentDatabaseDependency<unknown>,\n): dependency is PlannerDatabaseDependency {\n return dependency.install.every((operation) => operation.target.id === 'postgres');\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 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 * Pre-computed lookup sets for a schema table's constraints.\n * Converts O(n*m) linear scans to O(1) Set lookups per constraint check.\n */\ninterface SchemaTableLookup {\n readonly uniqueKeys: Set<string>;\n readonly indexKeys: Set<string>;\n readonly uniqueIndexKeys: Set<string>;\n readonly fkKeys: Set<string>;\n}\n\nfunction buildSchemaLookupMap(schema: SqlSchemaIR): ReadonlyMap<string, SchemaTableLookup> {\n const map = new Map<string, SchemaTableLookup>();\n for (const [tableName, table] of Object.entries(schema.tables)) {\n map.set(tableName, buildSchemaTableLookup(table));\n }\n return map;\n}\n\nfunction buildSchemaTableLookup(table: SqlSchemaIR['tables'][string]): SchemaTableLookup {\n const uniqueKeys = new Set(table.uniques.map((u) => u.columns.join(',')));\n const indexKeys = new Set(table.indexes.map((i) => i.columns.join(',')));\n const uniqueIndexKeys = new Set(\n table.indexes.filter((i) => i.unique).map((i) => i.columns.join(',')),\n );\n const fkKeys = new Set(\n table.foreignKeys.map(\n (fk) => `${fk.columns.join(',')}|${fk.referencedTable}|${fk.referencedColumns.join(',')}`,\n ),\n );\n return { uniqueKeys, indexKeys, uniqueIndexKeys, fkKeys };\n}\n\nfunction hasUniqueConstraint(lookup: SchemaTableLookup, columns: readonly string[]): boolean {\n const key = columns.join(',');\n return lookup.uniqueKeys.has(key) || lookup.uniqueIndexKeys.has(key);\n}\n\nfunction hasIndex(lookup: SchemaTableLookup, columns: readonly string[]): boolean {\n const key = columns.join(',');\n return lookup.indexKeys.has(key) || lookup.uniqueKeys.has(key);\n}\n\nfunction hasForeignKey(lookup: SchemaTableLookup, fk: ForeignKey): boolean {\n return lookup.fkKeys.has(\n `${fk.columns.join(',')}|${fk.references.table}|${fk.references.columns.join(',')}`,\n );\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 // db update (origin: null) always applies; migration-apply (origin set) skips if marker matches.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const skipOperations = markerAtDestination && options.plan.origin != null;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\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 // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\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 { TargetBoundComponentDescriptor } from '@prisma-next/contract/framework-components';\nimport type { ColumnDefault } from '@prisma-next/contract/types';\nimport 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 { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { SqlContract, SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-sql';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n\n if (!input.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${input.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) {\n throw new Error(\n `Column declares typeParams for nativeType \"${input.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${input.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n operationSignatures: () => [],\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 contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as SqlContract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\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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EAGH,MAAM,QAAQ,WAAW,IAAI,MAAM,QAAQ;AAC3C,MAAI,CAAC,OAAO,iBACV,OAAM,IAAI,MACR,8CAA8C,MAAM,WAAW,4DACF,MAAM,QAAQ,6EAE5E;AAEH,SAAO,MAAM,iBAAiB,MAAM;;;AAIxC,SAAgB,sBAAsB,KAAoB,QAA+B;AACvF,KAAI,IAAI,SAAS,WACf,QAAO,IAAI;AAEb,QAAO,qBAAqB,IAAI,OAAO,OAAO;;AAGhD,MAAMC,2BACJ;CACE,GAAG;CACH,2BAA2B,EAAE;CAC7B,YAAY;EACV,cAAc,SAAmC;AAC/C,UAAO,gCAAgC;;EAEzC,aAAa,QAAQ;AACnB,UAAO,8BAA8B,OAAO;;EAE9C,iBAAiB,UAAU,qBAAqB;AAE9C,UAAO,mBAAmB,UAA4C;IACpE,qBAAqB;IACrB,GAAG,UAAU,oBAHE,wBAAwB,oBAAoB,CAGjB;IAC1C,eAAe;IACf,qBAAqB,uBAAuB,EAAE;IAC/C,CAAC;;EAEL;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","columnTypeCheck","control_default","constraintDefinitions: string[]","FORMAT_TYPE_DISPLAY: ReadonlyMap<string, string>","REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string>","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","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-l_dv8Nnn.mjs","../../../../1-framework/2-authoring/ids/dist/index.mjs","../../../6-adapters/postgres/dist/control.mjs","../src/core/migrations/planner-identity-values.ts","../src/core/migrations/planner-sql.ts","../src/core/migrations/planner-target-details.ts","../src/core/migrations/planner-recipes.ts","../src/core/migrations/planner-reconciliation.ts","../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\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\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/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});\nfunction isPositiveInteger(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value > 0;\n}\nfunction isNonNegativeInteger(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\nfunction expandLength({ nativeType, typeParams }) {\n\tif (!typeParams || !(\"length\" in typeParams)) return nativeType;\n\tconst length = typeParams[\"length\"];\n\tif (!isPositiveInteger(length)) throw new Error(`Invalid \"length\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(length)}`);\n\treturn `${nativeType}(${length})`;\n}\nfunction expandPrecision({ nativeType, typeParams }) {\n\tif (!typeParams || !(\"precision\" in typeParams)) return nativeType;\n\tconst precision = typeParams[\"precision\"];\n\tif (!isPositiveInteger(precision)) throw new Error(`Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`);\n\treturn `${nativeType}(${precision})`;\n}\nfunction expandNumeric({ nativeType, typeParams }) {\n\tconst hasPrecision = typeParams && \"precision\" in typeParams;\n\tconst hasScale = typeParams && \"scale\" in typeParams;\n\tif (!hasPrecision && !hasScale) return nativeType;\n\tif (!hasPrecision && hasScale) throw new Error(`Invalid type parameters for \"${nativeType}\": \"scale\" requires \"precision\" to be specified`);\n\tif (hasPrecision) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (!isPositiveInteger(precision)) throw new Error(`Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`);\n\t\tif (hasScale) {\n\t\t\tconst scale = typeParams[\"scale\"];\n\t\t\tif (!isNonNegativeInteger(scale)) throw new Error(`Invalid \"scale\" type parameter for \"${nativeType}\": expected a non-negative integer, got ${JSON.stringify(scale)}`);\n\t\t\treturn `${nativeType}(${precision},${scale})`;\n\t\t}\n\t\treturn `${nativeType}(${precision})`;\n\t}\n\treturn nativeType;\n}\nconst lengthHooks = { expandNativeType: expandLength };\nconst precisionHooks = { expandNativeType: expandPrecision };\nconst numericHooks = { expandNativeType: expandNumeric };\nconst identityHooks = { expandNativeType: ({ nativeType }) => nativeType };\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]: lengthHooks,\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_CHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: numericHooks,\n\t\t\t\t[PG_BIT_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_VARBIT_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIME_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_ENUM_CODEC_ID]: pgEnumControlHooks,\n\t\t\t\t[PG_JSON_CODEC_ID]: identityHooks,\n\t\t\t\t[PG_JSONB_CODEC_ID]: identityHooks\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 { pgEnumControlHooks as n, postgresAdapterDescriptorMeta as t };\n//# sourceMappingURL=descriptor-meta-l_dv8Nnn.mjs.map","import { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/generator-ids.ts\nconst builtinGeneratorIds = [\n\t\"ulid\",\n\t\"nanoid\",\n\t\"uuidv7\",\n\t\"uuidv4\",\n\t\"cuid2\",\n\t\"ksuid\"\n];\n\n//#endregion\n//#region src/index.ts\nfunction resolveNanoidColumnDescriptor(params) {\n\tconst rawSize = params?.[\"size\"];\n\tif (rawSize === void 0) return {\n\t\ttype: {\n\t\t\tcodecId: \"sql/char@1\",\n\t\t\tnativeType: \"character\"\n\t\t},\n\t\ttypeParams: { length: 21 }\n\t};\n\tif (typeof rawSize !== \"number\" || !Number.isInteger(rawSize) || rawSize < 2 || rawSize > 255) throw new Error(\"nanoid size must be an integer between 2 and 255\");\n\treturn {\n\t\ttype: {\n\t\t\tcodecId: \"sql/char@1\",\n\t\t\tnativeType: \"character\"\n\t\t},\n\t\ttypeParams: { length: rawSize }\n\t};\n}\nconst builtinGeneratorMetadataById = {\n\tulid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 26 }\n\t\t}\n\t},\n\tnanoid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 21 }\n\t\t},\n\t\tresolveGeneratedColumnDescriptor: resolveNanoidColumnDescriptor\n\t},\n\tuuidv7: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 36 }\n\t\t}\n\t},\n\tuuidv4: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 36 }\n\t\t}\n\t},\n\tcuid2: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 24 }\n\t\t}\n\t},\n\tksuid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 27 }\n\t\t}\n\t}\n};\nconst builtinGeneratorRegistryMetadata = builtinGeneratorIds.map((id) => ({\n\tid,\n\tapplicableCodecIds: builtinGeneratorMetadataById[id].applicableCodecIds\n}));\nfunction resolveBuiltinGeneratedColumnDescriptor(input) {\n\tconst metadata = builtinGeneratorMetadataById[input.id];\n\tconst resolver = metadata.resolveGeneratedColumnDescriptor;\n\tif (resolver) return resolver(input.params);\n\treturn metadata.generatedColumnDescriptor;\n}\nfunction createGeneratedSpec(id, options) {\n\tconst params = options;\n\tconst resolvedDescriptor = resolveBuiltinGeneratedColumnDescriptor({\n\t\tid,\n\t\t...ifDefined(\"params\", params)\n\t});\n\treturn {\n\t\ttype: resolvedDescriptor.type,\n\t\tnullable: false,\n\t\t...ifDefined(\"typeParams\", resolvedDescriptor.typeParams),\n\t\tgenerated: {\n\t\t\tkind: \"generator\",\n\t\t\tid,\n\t\t\t...ifDefined(\"params\", params)\n\t\t}\n\t};\n}\nconst ulid = (options) => createGeneratedSpec(\"ulid\", options);\nconst nanoid = (options) => createGeneratedSpec(\"nanoid\", options);\nconst uuidv7 = (options) => createGeneratedSpec(\"uuidv7\", options);\nconst uuidv4 = (options) => createGeneratedSpec(\"uuidv4\", options);\nconst cuid2 = (options) => createGeneratedSpec(\"cuid2\", options);\nconst ksuid = (options) => createGeneratedSpec(\"ksuid\", options);\n\n//#endregion\nexport { builtinGeneratorIds, builtinGeneratorRegistryMetadata, cuid2, ksuid, nanoid, resolveBuiltinGeneratedColumnDescriptor, ulid, uuidv4, uuidv7 };\n//# sourceMappingURL=index.mjs.map","import { i as quoteIdentifier, n as escapeLiteral, r as qualifyName, t as SqlEscapeError } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { n as pgEnumControlHooks, t as postgresAdapterDescriptorMeta } from \"./descriptor-meta-l_dv8Nnn.mjs\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\nimport { builtinGeneratorRegistryMetadata, resolveBuiltinGeneratedColumnDescriptor } from \"@prisma-next/ids\";\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 NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/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* Returns the canonical expression for a timestamp default function, or undefined\n* if the expression is not a recognized timestamp default.\n*\n* Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n* - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n* - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n*\n* These are semantically different in Postgres: now() returns the transaction\n* start time (constant within a transaction), while clock_timestamp() returns\n* the actual wall-clock time (can differ across rows in a single INSERT).\n*/\nfunction canonicalizeTimestampDefault(expr) {\n\tif (NOW_FUNCTION_PATTERN.test(expr)) return \"now()\";\n\tif (CLOCK_TIMESTAMP_PATTERN.test(expr)) return \"clock_timestamp()\";\n\tif (!TIMESTAMP_CAST_SUFFIX.test(expr)) return void 0;\n\tlet inner = expr.replace(TIMESTAMP_CAST_SUFFIX, \"\").trim();\n\tif (inner.startsWith(\"(\") && inner.endsWith(\")\")) inner = inner.slice(1, -1).trim();\n\tif (NOW_FUNCTION_PATTERN.test(inner)) return \"now()\";\n\tif (CLOCK_TIMESTAMP_PATTERN.test(inner)) return \"clock_timestamp()\";\n\tinner = inner.replace(TEXT_CAST_SUFFIX, \"\").trim();\n\tif (NOW_LITERAL_PATTERN.test(inner)) return \"now()\";\n}\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, used for type-aware parsing (bigint tagging, JSON detection)\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\tconst canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n\tif (canonicalTimestamp) return {\n\t\tkind: \"function\",\n\t\texpression: canonicalTimestamp\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 (NULL_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: null\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\tconst num = Number(trimmed);\n\t\tif (!Number.isFinite(num)) return void 0;\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: num\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 dependencies = extensionsResult.rows.map((row) => ({ id: `postgres.extension.${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\tdependencies,\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/core/control-mutation-defaults.ts\nfunction invalidArgumentDiagnostic(input) {\n\treturn {\n\t\tok: false,\n\t\tdiagnostic: {\n\t\t\tcode: \"PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT\",\n\t\t\tmessage: input.message,\n\t\t\tsourceId: input.context.sourceId,\n\t\t\tspan: input.span\n\t\t}\n\t};\n}\nfunction executionGenerator(id, params) {\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"execution\",\n\t\t\tgenerated: {\n\t\t\t\tkind: \"generator\",\n\t\t\t\tid,\n\t\t\t\t...params ? { params } : {}\n\t\t\t}\n\t\t}\n\t};\n}\nfunction expectNoArgs(input) {\n\tif (input.call.args.length === 0) return;\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: `Default function \"${input.call.name}\" does not accept arguments. Use ${input.usage}.`\n\t});\n}\nfunction parseIntegerArgument(raw) {\n\tconst trimmed = raw.trim();\n\tif (!/^-?\\d+$/.test(trimmed)) return;\n\tconst value = Number(trimmed);\n\tif (!Number.isInteger(value)) return;\n\treturn value;\n}\nfunction parseStringLiteral(raw) {\n\tconst match = raw.trim().match(/^(['\"])(.*)\\1$/s);\n\tif (!match) return;\n\treturn match[2] ?? \"\";\n}\nfunction lowerAutoincrement(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`autoincrement()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: \"autoincrement()\"\n\t\t\t}\n\t\t}\n\t};\n}\nfunction lowerNow(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`now()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: \"now()\"\n\t\t\t}\n\t\t}\n\t};\n}\nfunction lowerUuid(input) {\n\tif (input.call.args.length === 0) return executionGenerator(\"uuidv4\");\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"uuid\\\" accepts at most one version argument: `uuid()`, `uuid(4)`, or `uuid(7)`.\"\n\t});\n\tconst version = parseIntegerArgument(input.call.args[0]?.raw ?? \"\");\n\tif (version === 4) return executionGenerator(\"uuidv4\");\n\tif (version === 7) return executionGenerator(\"uuidv7\");\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"uuid\\\" supports only `uuid()`, `uuid(4)`, or `uuid(7)` in SQL PSL provider v1.\"\n\t});\n}\nfunction lowerCuid(input) {\n\tif (input.call.args.length === 0) return {\n\t\tok: false,\n\t\tdiagnostic: {\n\t\t\tcode: \"PSL_UNKNOWN_DEFAULT_FUNCTION\",\n\t\t\tmessage: \"Default function \\\"cuid()\\\" is not supported in SQL PSL provider v1. Use `cuid(2)` instead.\",\n\t\t\tsourceId: input.context.sourceId,\n\t\t\tspan: input.call.span\n\t\t}\n\t};\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"cuid\\\" accepts exactly one version argument: `cuid(2)`.\"\n\t});\n\tif (parseIntegerArgument(input.call.args[0]?.raw ?? \"\") === 2) return executionGenerator(\"cuid2\");\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"cuid\\\" supports only `cuid(2)` in SQL PSL provider v1.\"\n\t});\n}\nfunction lowerUlid(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`ulid()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn executionGenerator(\"ulid\");\n}\nfunction lowerNanoid(input) {\n\tif (input.call.args.length === 0) return executionGenerator(\"nanoid\");\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"nanoid\\\" accepts at most one size argument: `nanoid()` or `nanoid(<2-255>)`.\"\n\t});\n\tconst size = parseIntegerArgument(input.call.args[0]?.raw ?? \"\");\n\tif (size !== void 0 && size >= 2 && size <= 255) return executionGenerator(\"nanoid\", { size });\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"nanoid\\\" size argument must be an integer between 2 and 255.\"\n\t});\n}\nfunction lowerDbgenerated(input) {\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" requires exactly one string argument: `dbgenerated(\\\"...\\\")`.\"\n\t});\n\tconst rawExpression = parseStringLiteral(input.call.args[0]?.raw ?? \"\");\n\tif (rawExpression === void 0) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" argument must be a string literal.\"\n\t});\n\tif (rawExpression.trim().length === 0) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" argument cannot be empty.\"\n\t});\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: rawExpression\n\t\t\t}\n\t\t}\n\t};\n}\nconst postgresDefaultFunctionRegistryEntries = [\n\t[\"autoincrement\", {\n\t\tlower: lowerAutoincrement,\n\t\tusageSignatures: [\"autoincrement()\"]\n\t}],\n\t[\"now\", {\n\t\tlower: lowerNow,\n\t\tusageSignatures: [\"now()\"]\n\t}],\n\t[\"uuid\", {\n\t\tlower: lowerUuid,\n\t\tusageSignatures: [\n\t\t\t\"uuid()\",\n\t\t\t\"uuid(4)\",\n\t\t\t\"uuid(7)\"\n\t\t]\n\t}],\n\t[\"cuid\", {\n\t\tlower: lowerCuid,\n\t\tusageSignatures: [\"cuid(2)\"]\n\t}],\n\t[\"ulid\", {\n\t\tlower: lowerUlid,\n\t\tusageSignatures: [\"ulid()\"]\n\t}],\n\t[\"nanoid\", {\n\t\tlower: lowerNanoid,\n\t\tusageSignatures: [\"nanoid()\", \"nanoid(<2-255>)\"]\n\t}],\n\t[\"dbgenerated\", {\n\t\tlower: lowerDbgenerated,\n\t\tusageSignatures: [\"dbgenerated(\\\"...\\\")\"]\n\t}]\n];\nconst postgresPslScalarTypeDescriptors = new Map([\n\t[\"String\", {\n\t\tcodecId: \"pg/text@1\",\n\t\tnativeType: \"text\"\n\t}],\n\t[\"Boolean\", {\n\t\tcodecId: \"pg/bool@1\",\n\t\tnativeType: \"bool\"\n\t}],\n\t[\"Int\", {\n\t\tcodecId: \"pg/int4@1\",\n\t\tnativeType: \"int4\"\n\t}],\n\t[\"BigInt\", {\n\t\tcodecId: \"pg/int8@1\",\n\t\tnativeType: \"int8\"\n\t}],\n\t[\"Float\", {\n\t\tcodecId: \"pg/float8@1\",\n\t\tnativeType: \"float8\"\n\t}],\n\t[\"Decimal\", {\n\t\tcodecId: \"pg/numeric@1\",\n\t\tnativeType: \"numeric\"\n\t}],\n\t[\"DateTime\", {\n\t\tcodecId: \"pg/timestamptz@1\",\n\t\tnativeType: \"timestamptz\"\n\t}],\n\t[\"Json\", {\n\t\tcodecId: \"pg/jsonb@1\",\n\t\tnativeType: \"jsonb\"\n\t}],\n\t[\"Bytes\", {\n\t\tcodecId: \"pg/bytea@1\",\n\t\tnativeType: \"bytea\"\n\t}]\n]);\nfunction createPostgresDefaultFunctionRegistry() {\n\treturn new Map(postgresDefaultFunctionRegistryEntries);\n}\nfunction createPostgresMutationDefaultGeneratorDescriptors() {\n\treturn builtinGeneratorRegistryMetadata.map(({ id, applicableCodecIds }) => ({\n\t\tid,\n\t\tapplicableCodecIds,\n\t\tresolveGeneratedColumnDescriptor: ({ generated }) => {\n\t\t\tif (generated.kind !== \"generator\" || generated.id !== id) return;\n\t\t\tconst descriptor = resolveBuiltinGeneratedColumnDescriptor({\n\t\t\t\tid,\n\t\t\t\t...generated.params ? { params: generated.params } : {}\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tcodecId: descriptor.type.codecId,\n\t\t\t\tnativeType: descriptor.type.nativeType,\n\t\t\t\t...descriptor.type.typeRef ? { typeRef: descriptor.type.typeRef } : {},\n\t\t\t\t...descriptor.typeParams ? { typeParams: descriptor.typeParams } : {}\n\t\t\t};\n\t\t}\n\t}));\n}\nfunction createPostgresPslScalarTypeDescriptors() {\n\treturn new Map(postgresPslScalarTypeDescriptors);\n}\n\n//#endregion\n//#region src/exports/control.ts\nconst postgresAdapterDescriptor = {\n\t...postgresAdapterDescriptorMeta,\n\toperationSignatures: () => [],\n\tpslTypeDescriptors: () => ({ scalarTypeDescriptors: createPostgresPslScalarTypeDescriptors() }),\n\tcontrolMutationDefaults: () => ({\n\t\tdefaultFunctionRegistry: createPostgresDefaultFunctionRegistry(),\n\t\tgeneratorDescriptors: createPostgresMutationDefaultGeneratorDescriptors()\n\t}),\n\tcreate() {\n\t\treturn new PostgresControlAdapter();\n\t}\n};\nvar control_default = postgresAdapterDescriptor;\n\n//#endregion\nexport { SqlEscapeError, control_default as default, escapeLiteral, normalizeSchemaNativeType, parsePostgresDefault, qualifyName, quoteIdentifier };\n//# sourceMappingURL=control.mjs.map","import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\n/**\n * Resolves the identity value (monoid neutral element) as a SQL literal for a column's type.\n * Checks codec hooks first (extensions can provide type-specific identity values),\n * then falls back to the built-in map.\n */\nexport function resolveIdentityValue(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): string | null {\n if (column.codecId) {\n const hookDefault = codecHooks.get(column.codecId)?.resolveIdentityValue?.({\n nativeType: column.nativeType,\n codecId: column.codecId,\n ...ifDefined('typeParams', column.typeParams),\n });\n if (hookDefault !== undefined) {\n return hookDefault;\n }\n }\n\n return buildBuiltinIdentityValue(column.nativeType, column.typeParams);\n}\n\n/**\n * Returns the built-in identity value (monoid neutral element) as a SQL literal for the given\n * PostgreSQL native type — e.g. 0 for integers, '' for text, false for booleans.\n *\n * This is the planner's fallback when no codec hook provides a type-specific identity value.\n *\n * Returns null for unrecognized types (for example enums and extension-owned types without a\n * hook), which causes the planner to fall back to the empty-table precheck.\n *\n * @internal Exported for testing only.\n */\nexport function buildBuiltinIdentityValue(\n nativeType: string,\n typeParams?: Record<string, unknown>,\n): string | null {\n const normalizedNativeType = normalizeIdentityValueNativeType(nativeType);\n\n if (normalizedNativeType.endsWith('[]')) {\n return \"'{}'\";\n }\n\n switch (normalizedNativeType) {\n case 'text':\n case 'character':\n case 'bpchar':\n case 'character varying':\n case 'varchar':\n return \"''\";\n\n case 'int2':\n case 'int4':\n case 'int8':\n case 'integer':\n case 'bigint':\n case 'smallint':\n case 'float4':\n case 'float8':\n case 'real':\n case 'double precision':\n case 'numeric':\n case 'decimal':\n return '0';\n\n case 'bool':\n case 'boolean':\n return 'false';\n\n case 'uuid':\n return \"'00000000-0000-0000-0000-000000000000'\";\n\n case 'json':\n return \"'{}'::json\";\n case 'jsonb':\n return \"'{}'::jsonb\";\n\n case 'date':\n case 'timestamp':\n case 'timestamptz':\n case 'timestamp with time zone':\n case 'timestamp without time zone':\n return \"'epoch'\";\n\n case 'time':\n case 'time without time zone':\n return \"'00:00:00'\";\n case 'timetz':\n case 'time with time zone':\n return \"'00:00:00+00'\";\n\n case 'interval':\n return \"'0'\";\n\n case 'bytea':\n return \"''::bytea\";\n case 'tsvector':\n return \"''::tsvector\";\n\n case 'bit':\n return buildBitIdentityValue(typeParams);\n case 'bit varying':\n case 'varbit':\n return \"B''\";\n\n default:\n return null;\n }\n}\n\nfunction normalizeIdentityValueNativeType(nativeType: string): string {\n return nativeType.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nfunction buildBitIdentityValue(typeParams?: Record<string, unknown>): string | null {\n const length = typeParams?.['length'];\n if (length === undefined) {\n return \"B'0'\";\n }\n if (typeof length !== 'number' || !Number.isInteger(length) || length <= 0) {\n return null;\n }\n return `B'${'0'.repeat(length)}'`;\n}\n","import { escapeLiteral, quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport { isTaggedBigInt } from '@prisma-next/contract/types';\nimport type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type {\n ForeignKey,\n ReferentialAction,\n StorageColumn,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\nimport type { PostgresColumnDefault } from '../types';\n\nexport function buildCreateTableSql(\n qualifiedTableName: string,\n table: StorageTable,\n codecHooks: Map<string, CodecControlHooks>,\n): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column, codecHooks),\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 * Pattern for safe PostgreSQL type names.\n * Allows letters, digits, underscores, spaces (for \"double precision\", \"character varying\"),\n * and trailing [] for array types.\n */\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*(\\[\\])?$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*(\\\\[\\\\])?$/',\n );\n }\n}\n\n/**\n * Sanity check against accidental SQL injection from malformed contract files.\n * Rejects semicolons, SQL comment tokens, and dollar-quoting.\n * Not a comprehensive security boundary — the contract is developer-authored.\n */\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\$\\$|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, dollar-quoting, or subqueries.',\n );\n }\n}\n\nexport function buildColumnTypeSql(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): string {\n const columnDefault = column.default;\n\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 assertSafeNativeType(column.nativeType);\n return renderParameterizedTypeSql(column, codecHooks) ?? column.nativeType;\n}\n\nfunction renderParameterizedTypeSql(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n if (!column.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(column.codecId);\n if (!hooks?.expandNativeType) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${column.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n\n const expanded = hooks.expandNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n return expanded !== column.nativeType ? expanded : null;\n}\n\nexport function 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 if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n return `DEFAULT nextval(${quoteIdentifier(columnDefault.name)}::regclass)`;\n }\n}\n\nexport function 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\nexport function qualifyTableName(schema: string, table: string): string {\n return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;\n}\n\nexport function toRegclassLiteral(schema: string, name: string): string {\n const regclass = `${quoteIdentifier(schema)}.${quoteIdentifier(name)}`;\n return `'${escapeLiteral(regclass)}'`;\n}\n\nexport function constraintExistsCheck({\n constraintName,\n schema,\n table,\n exists = true,\n}: {\n constraintName: string;\n schema: string;\n table: 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 AND c.conrelid = to_regclass(${toRegclassLiteral(schema, table)})\n)`;\n}\n\nexport function 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\nexport function columnNullabilityCheck({\n schema,\n table,\n column,\n nullable,\n}: {\n schema: string;\n table: string;\n column: string;\n nullable: boolean;\n}): string {\n const expected = nullable ? 'YES' : 'NO';\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 = '${expected}'\n)`;\n}\n\n/**\n * Maps contract native type names to the display form returned by PostgreSQL's\n * `format_type()`. Base types use short names in the contract (e.g., `int4`)\n * but `format_type()` returns SQL-standard names (e.g., `integer`).\n *\n * NOTE: The inverse mapping lives in `normalizeFormattedType` in control-adapter.ts.\n * These two maps must stay in sync. A shared bidirectional map in\n * @prisma-next/adapter-postgres would eliminate the drift risk.\n */\nconst FORMAT_TYPE_DISPLAY: ReadonlyMap<string, string> = new Map([\n ['int2', 'smallint'],\n ['int4', 'integer'],\n ['int8', 'bigint'],\n ['float4', 'real'],\n ['float8', 'double precision'],\n ['bool', 'boolean'],\n ['timestamp', 'timestamp without time zone'],\n ['timestamptz', 'timestamp with time zone'],\n ['time', 'time without time zone'],\n ['timetz', 'time with time zone'],\n]);\n\n/**\n * Builds the string that `format_type(atttypid, atttypmod)` would return for a\n * contract column. Used for postchecks — separate from `buildColumnTypeSql` which\n * produces DDL-safe strings (e.g., quoted identifiers, SERIAL).\n */\nexport function buildExpectedFormatType(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): string {\n // Parameterized types: expand with typeParams.\n // format_type() returns the same form (e.g., 'character varying(255)').\n if (column.typeParams && column.codecId) {\n const hooks = codecHooks.get(column.codecId);\n if (hooks?.expandNativeType) {\n return hooks.expandNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n }\n }\n\n // User-defined types (enums, composites): format_type() double-quotes names\n // that contain uppercase characters (e.g., \"StatusType\") but returns lowercase\n // names bare (e.g., status_type). We can't use quoteIdentifier() here because\n // it always quotes, which would break the lowercase case.\n if (column.typeRef) {\n const needsQuoting = column.nativeType !== column.nativeType.toLowerCase();\n return needsQuoting ? `\"${column.nativeType}\"` : column.nativeType;\n }\n\n // Base types: map contract short names to format_type() display names.\n return FORMAT_TYPE_DISPLAY.get(column.nativeType) ?? column.nativeType;\n}\n\n/** Checks that the column's full type (including typmods) matches the expected type via `format_type()`. */\nexport function columnTypeCheck({\n schema,\n table,\n column,\n expectedType,\n}: {\n schema: string;\n table: string;\n column: string;\n expectedType: string;\n}): string {\n return `SELECT EXISTS (\n SELECT 1\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = '${escapeLiteral(schema)}'\n AND c.relname = '${escapeLiteral(table)}'\n AND a.attname = '${escapeLiteral(column)}'\n AND format_type(a.atttypid, a.atttypmod) = '${escapeLiteral(expectedType)}'\n AND NOT a.attisdropped\n)`;\n}\n\n/** Checks that a column default exists (or does not exist) via `information_schema.columns.column_default`. */\nexport function columnDefaultExistsCheck({\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 nullCheck = exists ? 'IS NOT NULL' : 'IS NULL';\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 column_default ${nullCheck}\n)`;\n}\n\nexport function tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nexport function columnHasNoDefaultCheck(opts: {\n schema: string;\n table: string;\n column: string;\n}): string {\n return `SELECT NOT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(opts.schema)}'\n AND table_name = '${escapeLiteral(opts.table)}'\n AND column_name = '${escapeLiteral(opts.column)}'\n AND column_default IS NOT NULL\n)`;\n}\n\nexport function buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n defaultLiteral?: string | null,\n): string {\n const typeSql = buildColumnTypeSql(column, codecHooks);\n const defaultSql =\n buildColumnDefaultSql(column.default, column) ||\n (defaultLiteral != null ? `DEFAULT ${defaultLiteral}` : '');\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\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\nexport function 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 { ifDefined } from '@prisma-next/utils/defined';\nimport type { OperationClass, PostgresPlanTargetDetails } from './planner';\n\nexport function 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","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { StorageColumn } from '@prisma-next/sql-contract/types';\nimport type { PostgresPlanTargetDetails } from './planner';\nimport {\n buildAddColumnSql,\n columnExistsCheck,\n columnHasNoDefaultCheck,\n columnNullabilityCheck,\n qualifyTableName,\n} from './planner-sql';\nimport { buildTargetDetails } from './planner-target-details';\n\nexport function buildAddColumnOperationIdentity(\n schema: string,\n tableName: string,\n columnName: string,\n): Pick<\n SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n 'id' | 'label' | 'summary' | 'target'\n> {\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schema),\n },\n };\n}\n\nexport function buildAddNotNullColumnWithTemporaryDefaultOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly temporaryDefault: string;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const { schema, tableName, columnName, column, codecHooks, temporaryDefault } = options;\n const qualified = qualifyTableName(schema, tableName);\n\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(qualified, columnName, column, codecHooks, temporaryDefault),\n },\n {\n description: `drop temporary default from column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n {\n description: `verify column \"${columnName}\" has no default after temporary default removal`,\n sql: columnHasNoDefaultCheck({ schema, table: tableName, column: columnName }),\n },\n ],\n };\n}\n","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport type { SqlContract, SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { invariant } from '@prisma-next/utils/assertions';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PlanningMode, PostgresPlanTargetDetails } from './planner';\nimport {\n buildColumnDefaultSql,\n buildColumnTypeSql,\n buildExpectedFormatType,\n columnDefaultExistsCheck,\n columnExistsCheck,\n columnNullabilityCheck,\n columnTypeCheck,\n constraintExistsCheck,\n qualifyTableName,\n toRegclassLiteral,\n} from './planner-sql';\nimport { buildTargetDetails } from './planner-target-details';\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nexport function buildReconciliationPlan(options: {\n readonly contract: SqlContract<SqlStorage>;\n readonly issues: readonly SchemaIssue[];\n readonly schemaName: string;\n readonly mode: PlanningMode;\n readonly policy: MigrationOperationPolicy;\n readonly 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 { mode } = options;\n const seenOperationIds = new Set<string>();\n\n for (const issue of sortSchemaIssues(options.issues)) {\n if (isAdditiveIssue(issue)) {\n continue;\n }\n\n const operation = buildReconciliationOperationFromIssue({\n issue,\n contract: options.contract,\n schemaName: options.schemaName,\n mode,\n codecHooks: options.codecHooks,\n });\n\n if (operation) {\n // Skip duplicates: different schema issues may produce the same operation id\n // (e.g., extra_unique_constraint and extra_index on the same object).\n if (!seenOperationIds.has(operation.id)) {\n seenOperationIds.add(operation.id);\n if (options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n operations.push(operation);\n } else {\n const conflict = convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n } else {\n const conflict = convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n\n return {\n operations,\n conflicts: conflicts.sort(conflictComparator),\n };\n}\n\n// ============================================================================\n// Issue Classification\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 'dependency_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\n// ============================================================================\n// Operation Builders\n// ============================================================================\n\nfunction buildReconciliationOperationFromIssue(options: {\n readonly issue: SchemaIssue;\n readonly contract: SqlContract<SqlStorage>;\n readonly schemaName: string;\n readonly mode: PlanningMode;\n readonly codecHooks: Map<string, CodecControlHooks>;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const { issue, contract, schemaName, mode, codecHooks } = options;\n switch (issue.kind) {\n case 'extra_table':\n if (!mode.allowDestructive || !issue.table) {\n return null;\n }\n return buildDropTableOperation(schemaName, issue.table);\n\n case 'extra_column':\n if (!mode.allowDestructive || !issue.table || !issue.column) {\n return null;\n }\n return buildDropColumnOperation(schemaName, issue.table, issue.column);\n\n case 'extra_index':\n if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) {\n return null;\n }\n return buildDropIndexOperation(schemaName, issue.table, issue.indexOrConstraint);\n\n case 'extra_foreign_key':\n case 'extra_unique_constraint': {\n if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) {\n return null;\n }\n const constraintKind = issue.kind === 'extra_foreign_key' ? 'foreignKey' : 'unique';\n return buildDropConstraintOperation(\n schemaName,\n issue.table,\n issue.indexOrConstraint,\n constraintKind,\n );\n }\n\n case 'extra_primary_key': {\n if (!mode.allowDestructive || !issue.table) {\n return null;\n }\n const constraintName = issue.indexOrConstraint ?? `${issue.table}_pkey`;\n return buildDropConstraintOperation(schemaName, issue.table, constraintName, 'primaryKey');\n }\n\n case 'nullability_mismatch': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (issue.expected === 'true') {\n // Contract wants nullable, DB has NOT NULL → widening\n return mode.allowWidening\n ? buildDropNotNullOperation(schemaName, issue.table, issue.column)\n : null;\n }\n // Contract wants NOT NULL, DB has nullable → destructive\n return mode.allowDestructive\n ? buildSetNotNullOperation(schemaName, issue.table, issue.column)\n : null;\n }\n\n case 'type_mismatch': {\n if (!mode.allowDestructive || !issue.table || !issue.column) {\n return null;\n }\n const contractColumn = getContractColumn(contract, issue.table, issue.column);\n if (!contractColumn) {\n return null;\n }\n return buildAlterColumnTypeOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColumn,\n codecHooks,\n );\n }\n\n case 'default_missing': {\n if (!issue.table || !issue.column) {\n return null;\n }\n const contractColMissing = getContractColumn(contract, issue.table, issue.column);\n if (!contractColMissing) {\n return null;\n }\n // NOTE: Being in the `default_missing` case means the verifier found the contract expects a default, so it should exist here. We must still narrow.\n invariant(\n contractColMissing.default !== undefined,\n `default_missing issue for \"${issue.table}\".\"${issue.column}\" but contract column has no default`,\n );\n return buildDefaultOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColMissing,\n contractColMissing.default,\n 'additive',\n 'Set',\n );\n }\n\n case 'default_mismatch': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (!mode.allowWidening) {\n return null;\n }\n const contractColMismatch = getContractColumn(contract, issue.table, issue.column);\n if (!contractColMismatch) {\n return null;\n }\n // NOTE: Being in the `default_mismatch` case means the verifier found the contract expects a different default, so it should exist here. We must still narrow.\n invariant(\n contractColMismatch.default !== undefined,\n `default_mismatch issue for \"${issue.table}\".\"${issue.column}\" but contract column has no default`,\n );\n return buildDefaultOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColMismatch,\n contractColMismatch.default,\n 'widening',\n 'Change',\n );\n }\n\n case 'extra_default': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (!mode.allowDestructive) {\n return null;\n }\n return buildDropDefaultOperation(schemaName, issue.table, issue.column);\n }\n\n // Remaining issue kinds (primary_key_mismatch, unique_constraint_mismatch,\n // index_mismatch, foreign_key_mismatch) do not yet have reconciliation operation\n // builders. They fall through to the caller, which converts them to conflicts via\n // convertIssueToConflict. When a new SchemaIssue kind is added, add a case here if\n // the planner can emit an operation for it; otherwise it becomes a conflict.\n default:\n return null;\n }\n}\n\nfunction getContractColumn(\n contract: SqlContract<SqlStorage>,\n tableName: string,\n columnName: string,\n): StorageColumn | null {\n const table = contract.storage.tables[tableName];\n if (!table) {\n return null;\n }\n return table.columns[columnName] ?? null;\n}\n\nfunction buildDropTableOperation(\n schemaName: string,\n tableName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops extra table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n execute: [\n {\n description: `drop table \"${tableName}\"`,\n sql: `DROP TABLE ${qualifyTableName(schemaName, tableName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" is removed`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n };\n}\n\nfunction buildDropColumnOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} from ${tableName}`,\n summary: `Drops extra column ${columnName} from table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" is removed`,\n sql: columnExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: false,\n }),\n },\n ],\n };\n}\n\nfunction buildDropIndexOperation(\n schemaName: string,\n tableName: string,\n indexName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops extra index ${indexName} on table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n execute: [\n {\n description: `drop index \"${indexName}\"`,\n sql: `DROP INDEX ${qualifyTableName(schemaName, indexName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" is removed`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n };\n}\n\nfunction buildDropConstraintOperation(\n schemaName: string,\n tableName: string,\n constraintName: string,\n constraintKind: 'foreignKey' | 'unique' | 'primaryKey',\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropConstraint.${tableName}.${constraintName}`,\n label: `Drop constraint ${constraintName} on ${tableName}`,\n summary: `Drops extra constraint ${constraintName} on table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails(constraintKind, constraintName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName, table: tableName }),\n },\n ],\n execute: [\n {\n description: `drop constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nDROP CONSTRAINT ${quoteIdentifier(constraintName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify constraint \"${constraintName}\" is removed`,\n sql: constraintExistsCheck({\n constraintName,\n schema: schemaName,\n table: tableName,\n exists: false,\n }),\n },\n ],\n };\n}\n\nfunction buildDropNotNullOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `alterNullability.${tableName}.${columnName}`,\n label: `Relax nullability for ${columnName} on ${tableName}`,\n summary: `Drops NOT NULL constraint for ${columnName} on table ${tableName}`,\n operationClass: 'widening',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop NOT NULL from \"${columnName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nALTER COLUMN ${quoteIdentifier(columnName)} DROP NOT NULL`,\n },\n ],\n postcheck: [\n {\n description: `verify \"${columnName}\" is nullable`,\n sql: columnNullabilityCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: true,\n }),\n },\n ],\n };\n}\n\nfunction buildSetNotNullOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n return {\n id: `alterNullability.${tableName}.${columnName}`,\n label: `Enforce NOT NULL for ${columnName} on ${tableName}`,\n summary: `Sets NOT NULL on ${columnName} for table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n {\n description: `ensure \"${columnName}\" has no NULL values`,\n sql: `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualified}\n WHERE ${quoteIdentifier(columnName)} IS NULL\n LIMIT 1\n)`,\n },\n ],\n execute: [\n {\n description: `set NOT NULL on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\nALTER COLUMN ${quoteIdentifier(columnName)} SET NOT NULL`,\n },\n ],\n postcheck: [\n {\n description: `verify \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ],\n };\n}\n\nfunction buildAlterColumnTypeOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n const expectedType = buildColumnTypeSql(column, codecHooks);\n return {\n id: `alterType.${tableName}.${columnName}`,\n label: `Alter type for ${columnName} on ${tableName}`,\n summary: `Changes type of ${columnName} to ${expectedType}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n meta: {\n warning: 'TABLE_REWRITE',\n detail:\n 'ALTER COLUMN TYPE requires a full table rewrite and acquires an ACCESS EXCLUSIVE lock. On large tables, this can cause significant downtime.',\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `alter type of \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\nALTER COLUMN ${quoteIdentifier(columnName)}\nTYPE ${expectedType}\nUSING ${quoteIdentifier(columnName)}::${expectedType}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has type ${expectedType}`,\n sql: columnTypeCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n expectedType: buildExpectedFormatType(column, codecHooks),\n }),\n },\n ],\n };\n}\n\nfunction buildDefaultOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n column: Omit<StorageColumn, 'default'>,\n columnDefault: NonNullable<StorageColumn['default']>,\n operationClass: 'additive' | 'widening',\n verb: 'Set' | 'Change',\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const qualified = qualifyTableName(schemaName, tableName);\n const defaultClause = buildColumnDefaultSql(columnDefault, column);\n // autoincrement defaults are handled by SERIAL types — buildColumnDefaultSql returns ''\n // for them. Until the IR is enriched to distinguish autoincrement (TML-2107), skip.\n if (!defaultClause) return null;\n const verbLower = verb.toLowerCase();\n return {\n id: `setDefault.${tableName}.${columnName}`,\n label: `${verb} default for ${columnName} on ${tableName}`,\n summary: `${verb}s default on column ${columnName} of table ${tableName}`,\n operationClass,\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `${verbLower} default on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\\nALTER COLUMN ${quoteIdentifier(columnName)} SET ${defaultClause}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has a default`,\n sql: columnDefaultExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: true,\n }),\n },\n ],\n };\n}\n\nfunction buildDropDefaultOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n return {\n id: `dropDefault.${tableName}.${columnName}`,\n label: `Drop default for ${columnName} on ${tableName}`,\n summary: `Drops default on column ${columnName} of table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop default on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\\nALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has no default`,\n sql: columnDefaultExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: false,\n }),\n },\n ],\n };\n}\n\n// ============================================================================\n// Conflict Conversion\n// ============================================================================\n\nfunction convertIssueToConflict(issue: SchemaIssue): SqlPlannerConflict | null {\n switch (issue.kind) {\n case 'type_mismatch':\n return buildConflict('typeMismatch', issue);\n case 'nullability_mismatch':\n return buildConflict('nullabilityConflict', issue);\n case 'default_missing':\n case 'default_mismatch':\n case 'extra_default':\n case 'extra_table':\n case 'extra_column':\n case 'extra_primary_key':\n case 'extra_foreign_key':\n case 'extra_unique_constraint':\n case 'extra_index':\n return buildConflict('missingButNonAdditive', issue);\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n return buildConflict('indexIncompatible', issue);\n case 'foreign_key_mismatch':\n return buildConflict('foreignKeyConflict', issue);\n // Additive issue kinds (missing_table, missing_column, type_missing, type_values_mismatch,\n // dependency_missing) are filtered by isAdditiveIssue before reaching this method.\n // If a new SchemaIssue kind is introduced, add a mapping here so it becomes a conflict\n // rather than being silently ignored.\n default:\n return null;\n }\n}\n\nfunction 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// ============================================================================\n// Sorting and Comparison Helpers\n// ============================================================================\n\nfunction sortSchemaIssues(issues: readonly SchemaIssue[]): readonly SchemaIssue[] {\n return [...issues].sort((a, b) => {\n const kindCompare = a.kind.localeCompare(b.kind);\n if (kindCompare !== 0) {\n return kindCompare;\n }\n const tableCompare = compareStrings(a.table, b.table);\n if (tableCompare !== 0) {\n return tableCompare;\n }\n const columnCompare = compareStrings(a.column, b.column);\n if (columnCompare !== 0) {\n return columnCompare;\n }\n return compareStrings(a.indexOrConstraint, b.indexOrConstraint);\n });\n}\n\nfunction buildConflictLocation(issue: SchemaIssue) {\n const location = {\n ...ifDefined('table', issue.table),\n ...ifDefined('column', issue.column),\n ...ifDefined('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 {\n escapeLiteral,\n normalizeSchemaNativeType,\n parsePostgresDefault,\n quoteIdentifier,\n} from '@prisma-next/adapter-postgres/control';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\n CodecControlHooks,\n ComponentDatabaseDependency,\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport {\n collectInitDependencies,\n createMigrationPlan,\n extractCodecControlHooks,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { ForeignKey, StorageColumn, StorageTable } from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { resolveIdentityValue } from './planner-identity-values';\nimport {\n buildAddColumnOperationIdentity,\n buildAddNotNullColumnWithTemporaryDefaultOperation,\n} from './planner-recipes';\nimport { buildReconciliationPlan } from './planner-reconciliation';\nimport {\n buildAddColumnSql,\n buildCreateTableSql,\n buildForeignKeySql,\n columnExistsCheck,\n columnNullabilityCheck,\n constraintExistsCheck,\n qualifyTableName,\n tableIsEmptyCheck,\n toRegclassLiteral,\n} from './planner-sql';\nimport { buildTargetDetails } from './planner-target-details';\n\nexport type OperationClass =\n | 'dependency'\n | 'type'\n | 'table'\n | 'column'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | '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};\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\nexport interface PlanningMode {\n readonly includeExtraObjects: boolean;\n readonly allowWidening: boolean;\n readonly allowDestructive: boolean;\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 planningMode = this.resolvePlanningMode(options.policy);\n const schemaIssues = this.collectSchemaIssues(options, planningMode.includeExtraObjects);\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 reconciliationPlan = buildReconciliationPlan({\n contract: options.contract,\n issues: schemaIssues,\n schemaName,\n mode: planningMode,\n policy: options.policy,\n codecHooks,\n });\n if (reconciliationPlan.conflicts.length > 0) {\n return plannerFailure(reconciliationPlan.conflicts);\n }\n\n const storageTypePlan = this.buildStorageTypeOperations(options, schemaName, codecHooks);\n if (storageTypePlan.conflicts.length > 0) {\n return plannerFailure(storageTypePlan.conflicts);\n }\n\n // Sort table entries once for reuse across all additive operation builders.\n const sortedTables = sortedEntries(options.contract.storage.tables);\n\n // Pre-compute constraint lookups once per schema table for O(1) checks across all builders.\n const schemaLookups = buildSchemaLookupMap(options.schema);\n\n // Build extension operations from component-owned database dependencies\n operations.push(\n ...this.buildDatabaseDependencyOperations(options),\n ...storageTypePlan.operations,\n ...reconciliationPlan.operations,\n ...this.buildTableOperations(sortedTables, options.schema, schemaName, codecHooks),\n ...this.buildColumnOperations(\n sortedTables,\n options.schema,\n schemaLookups,\n schemaName,\n codecHooks,\n ),\n ...this.buildPrimaryKeyOperations(sortedTables, options.schema, schemaName),\n ...this.buildUniqueOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildIndexOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildFkBackingIndexOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildForeignKeyOperations(sortedTables, schemaLookups, schemaName),\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: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\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 const installedIds = new Set(options.schema.dependencies.map((d) => d.id));\n\n for (const dependency of dependencies) {\n if (seenDependencyIds.has(dependency.id)) {\n continue;\n }\n seenDependencyIds.add(dependency.id);\n\n if (installedIds.has(dependency.id)) {\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 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 dependencies = collectInitDependencies(options.frameworkComponents);\n return sortDependencies(dependencies.filter(isPostgresPlannerDependency));\n }\n\n private buildTableOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of 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, codecHooks),\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: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const schemaTable = schema.tables[tableName];\n if (!schemaTable) {\n continue;\n }\n const schemaLookup = schemaLookups.get(tableName);\n for (const [columnName, column] of sortedEntries(table.columns)) {\n if (schemaTable.columns[columnName]) {\n continue;\n }\n operations.push(\n this.buildAddColumnOperation({\n schema: schemaName,\n tableName,\n table,\n schemaTable,\n schemaLookup,\n columnName,\n column,\n codecHooks,\n }),\n );\n }\n }\n return operations;\n }\n\n private buildAddColumnOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: SchemaTableLookup | undefined;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n }): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const { schema, tableName, table, schemaTable, schemaLookup, columnName, column, codecHooks } =\n options;\n const notNull = column.nullable === false;\n const hasDefault = column.default !== undefined;\n // Planner logic decides whether this column needs the coordinated multi-step\n // strategy. The strategy recipe itself is built by a dedicated helper.\n const needsTemporaryDefault = notNull && !hasDefault;\n const temporaryDefault = needsTemporaryDefault\n ? resolveIdentityValue(column, codecHooks)\n : null;\n const canUseSharedTemporaryDefault =\n needsTemporaryDefault &&\n temporaryDefault !== null &&\n canUseSharedTemporaryDefaultStrategy({\n table,\n schemaTable,\n schemaLookup,\n columnName,\n });\n\n if (canUseSharedTemporaryDefault) {\n return buildAddNotNullColumnWithTemporaryDefaultOperation({\n schema,\n tableName,\n columnName,\n column,\n codecHooks,\n temporaryDefault,\n });\n }\n\n const qualified = qualifyTableName(schema, tableName);\n const requiresEmptyTableCheck = needsTemporaryDefault && !canUseSharedTemporaryDefault;\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ...(requiresEmptyTableCheck\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 execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(qualified, columnName, column, codecHooks),\n },\n ],\n 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: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ]\n : []),\n ],\n };\n }\n\n private buildPrimaryKeyOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of 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: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const unique of table.uniques) {\n if (lookup && hasUniqueConstraint(lookup, 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({\n constraintName,\n schema: schemaName,\n table: tableName,\n exists: false,\n }),\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, table: tableName }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildIndexOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const index of table.indexes) {\n if (lookup && hasIndex(lookup, index.columns)) {\n continue;\n }\n const indexName = index.name ?? defaultIndexName(tableName, index.columns);\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: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(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 (lookup && hasIndex(lookup, fk.columns)) continue;\n\n const indexName = defaultIndexName(tableName, fk.columns);\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: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false) continue;\n if (lookup && hasForeignKey(lookup, 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 table: tableName,\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({\n constraintName: fkName,\n schema: schemaName,\n table: tableName,\n }),\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 buildTargetDetails(objectType, name, schema, table);\n }\n\n private resolvePlanningMode(policy: MigrationOperationPolicy): PlanningMode {\n const allowWidening = policy.allowedOperationClasses.includes('widening');\n const allowDestructive = policy.allowedOperationClasses.includes('destructive');\n // `db init` uses additive-only policy and intentionally ignores extras.\n // Any reconciliation-capable policy should inspect extras to reconcile strict equality.\n const includeExtraObjects = allowWidening || allowDestructive;\n return { includeExtraObjects, allowWidening, allowDestructive };\n }\n\n private collectSchemaIssues(\n options: PlannerOptionsWithComponents,\n strict: boolean,\n ): readonly SchemaIssue[] {\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n\nfunction canUseSharedTemporaryDefaultStrategy(options: {\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: SchemaTableLookup | undefined;\n readonly columnName: string;\n}): boolean {\n const { table, schemaTable, schemaLookup, columnName } = options;\n\n // Shared placeholders are only safe when later plan steps do not require\n // row-specific values for this newly added column.\n if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) {\n return false;\n }\n\n for (const unique of table.uniques) {\n if (!unique.columns.includes(columnName)) {\n continue;\n }\n if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) {\n return false;\n }\n }\n\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false || !foreignKey.columns.includes(columnName)) {\n continue;\n }\n if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction isPostgresPlannerDependency(\n dependency: ComponentDatabaseDependency<unknown>,\n): dependency is PlannerDatabaseDependency {\n return dependency.install.every((operation) => operation.target.id === 'postgres');\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 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 * Pre-computed lookup sets for a schema table's constraints.\n * Converts O(n*m) linear scans to O(1) Set lookups per constraint check.\n */\ninterface SchemaTableLookup {\n readonly uniqueKeys: Set<string>;\n readonly indexKeys: Set<string>;\n readonly uniqueIndexKeys: Set<string>;\n readonly fkKeys: Set<string>;\n}\n\nfunction buildSchemaLookupMap(schema: SqlSchemaIR): ReadonlyMap<string, SchemaTableLookup> {\n const map = new Map<string, SchemaTableLookup>();\n for (const [tableName, table] of Object.entries(schema.tables)) {\n map.set(tableName, buildSchemaTableLookup(table));\n }\n return map;\n}\n\nfunction buildSchemaTableLookup(table: SqlSchemaIR['tables'][string]): SchemaTableLookup {\n const uniqueKeys = new Set(table.uniques.map((u) => u.columns.join(',')));\n const indexKeys = new Set(table.indexes.map((i) => i.columns.join(',')));\n const uniqueIndexKeys = new Set(\n table.indexes.filter((i) => i.unique).map((i) => i.columns.join(',')),\n );\n const fkKeys = new Set(\n table.foreignKeys.map(\n (fk) => `${fk.columns.join(',')}|${fk.referencedTable}|${fk.referencedColumns.join(',')}`,\n ),\n );\n return { uniqueKeys, indexKeys, uniqueIndexKeys, fkKeys };\n}\n\nfunction hasUniqueConstraint(lookup: SchemaTableLookup, columns: readonly string[]): boolean {\n const key = columns.join(',');\n return lookup.uniqueKeys.has(key) || lookup.uniqueIndexKeys.has(key);\n}\n\nfunction hasIndex(lookup: SchemaTableLookup, columns: readonly string[]): boolean {\n const key = columns.join(',');\n return lookup.indexKeys.has(key) || lookup.uniqueKeys.has(key);\n}\n\nfunction hasForeignKey(lookup: SchemaTableLookup, fk: ForeignKey): boolean {\n return lookup.fkKeys.has(\n `${fk.columns.join(',')}|${fk.references.table}|${fk.references.columns.join(',')}`,\n );\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 // db update (origin: null) always applies; migration-apply (origin set) skips if marker matches.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const skipOperations = markerAtDestination && options.plan.origin != null;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\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 // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\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 { TargetBoundComponentDescriptor } from '@prisma-next/contract/framework-components';\nimport type { ColumnDefault } from '@prisma-next/contract/types';\nimport 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 { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { SqlContract, SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-sql';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n\n if (!input.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${input.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) {\n throw new Error(\n `Column declares typeParams for nativeType \"${input.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${input.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n operationSignatures: () => [],\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 contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as SqlContract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\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,KAAK;;;;;AAKjC,SAAS,YAAY,YAAY,YAAY;AAC5C,QAAO,GAAG,gBAAgB,WAAW,CAAC,GAAG,gBAAgB,WAAW;;;;;;;;;;;;;AAarE,SAAS,wBAAwB,OAAO,cAAc;AACrD,KAAI,MAAM,SAASA,wBAAuB,OAAM,IAAI,eAAe,eAAe,MAAM,MAAM,GAAG,GAAG,CAAC,iBAAiB,aAAa,yBAAyBA,wBAAsB,yBAAyB,OAAO,UAAU;;;;;ACrE7N,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB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