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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":["MAX_IDENTIFIER_LENGTH","control_default","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","deps: PlannerDatabaseDependency[]","constraintDefinitions: string[]","REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string>","ensurePrismaContractSchemaStatement: SqlStatement","ensureMarkerTableStatement: SqlStatement","ensureLedgerTableStatement: SqlStatement","params: readonly unknown[]","DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../../../6-adapters/postgres/dist/sql-utils-CSfAGEwF.mjs","../../../6-adapters/postgres/dist/codec-ids-Bsm9c7ns.mjs","../../../6-adapters/postgres/dist/descriptor-meta-ilnFI7bx.mjs","../../../6-adapters/postgres/dist/control.mjs","../src/core/migrations/planner-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\ttable: \"\",\n\t\t\ttypeName,\n\t\t\tmessage: `Type \"${typeName}\" is missing from database`\n\t\t}];\n\t\tif (!arraysEqual(existing, desired)) return [{\n\t\t\tkind: \"type_values_mismatch\",\n\t\t\ttable: \"\",\n\t\t\ttypeName,\n\t\t\texpected: desired.join(\", \"),\n\t\t\tactual: existing.join(\", \"),\n\t\t\tmessage: `Type \"${typeName}\" values do not match contract`\n\t\t}];\n\t\treturn [];\n\t},\n\tintrospectTypes: async ({ driver, schemaName }) => {\n\t\tconst namespace = schemaName ?? \"public\";\n\t\tconst result = await driver.query(ENUM_INTROSPECT_QUERY, [namespace]);\n\t\tconst types = {};\n\t\tfor (const row of result.rows) {\n\t\t\tconst values = parsePostgresArray(row.values);\n\t\t\tif (!values) throw new Error(`Failed to parse enum values for type \"${row.type_name}\": unexpected format: ${JSON.stringify(row.values)}`);\n\t\t\ttypes[row.type_name] = {\n\t\t\t\tcodecId: PG_ENUM_CODEC_ID,\n\t\t\t\tnativeType: row.type_name,\n\t\t\t\ttypeParams: { values }\n\t\t\t};\n\t\t}\n\t\treturn types;\n\t}\n};\n\n//#endregion\n//#region src/core/json-schema-type-expression.ts\nconst MAX_DEPTH = 32;\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction escapeStringLiteral(str) {\n\treturn str.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\\\\r\");\n}\nfunction quotePropertyKey(key) {\n\treturn /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;\n}\nfunction renderLiteral(value) {\n\tif (typeof value === \"string\") return `'${escapeStringLiteral(value)}'`;\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (value === null) return \"null\";\n\treturn \"unknown\";\n}\nfunction renderUnion(items, depth) {\n\treturn items.map((item) => render(item, depth)).join(\" | \");\n}\nfunction renderObjectType(schema, depth) {\n\tconst properties = isRecord(schema[\"properties\"]) ? schema[\"properties\"] : {};\n\tconst required = Array.isArray(schema[\"required\"]) ? new Set(schema[\"required\"].filter((key) => typeof key === \"string\")) : /* @__PURE__ */ new Set();\n\tconst keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));\n\tif (keys.length === 0) {\n\t\tconst additionalProperties = schema[\"additionalProperties\"];\n\t\tif (additionalProperties === true || additionalProperties === void 0) return \"Record<string, unknown>\";\n\t\treturn `Record<string, ${render(additionalProperties, depth)}>`;\n\t}\n\treturn `{ ${keys.map((key) => {\n\t\tconst valueSchema = properties[key];\n\t\tconst optionalMarker = required.has(key) ? \"\" : \"?\";\n\t\treturn `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;\n\t}).join(\"; \")} }`;\n}\nfunction renderArrayType(schema, depth) {\n\tif (Array.isArray(schema[\"items\"])) return `readonly [${schema[\"items\"].map((item) => render(item, depth)).join(\", \")}]`;\n\tif (schema[\"items\"] !== void 0) {\n\t\tconst itemType = render(schema[\"items\"], depth);\n\t\treturn itemType.includes(\" | \") || itemType.includes(\" & \") ? `(${itemType})[]` : `${itemType}[]`;\n\t}\n\treturn \"unknown[]\";\n}\nfunction render(schema, depth) {\n\tif (depth > MAX_DEPTH || !isRecord(schema)) return \"JsonValue\";\n\tconst nextDepth = depth + 1;\n\tif (\"const\" in schema) return renderLiteral(schema[\"const\"]);\n\tif (Array.isArray(schema[\"enum\"])) return schema[\"enum\"].map((value) => renderLiteral(value)).join(\" | \");\n\tif (Array.isArray(schema[\"oneOf\"])) return renderUnion(schema[\"oneOf\"], nextDepth);\n\tif (Array.isArray(schema[\"anyOf\"])) return renderUnion(schema[\"anyOf\"], nextDepth);\n\tif (Array.isArray(schema[\"allOf\"])) return schema[\"allOf\"].map((item) => render(item, nextDepth)).join(\" & \");\n\tif (Array.isArray(schema[\"type\"])) return schema[\"type\"].map((item) => render({\n\t\t...schema,\n\t\ttype: item\n\t}, nextDepth)).join(\" | \");\n\tswitch (schema[\"type\"]) {\n\t\tcase \"string\": return \"string\";\n\t\tcase \"number\":\n\t\tcase \"integer\": return \"number\";\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"null\": return \"null\";\n\t\tcase \"array\": return renderArrayType(schema, nextDepth);\n\t\tcase \"object\": return renderObjectType(schema, nextDepth);\n\t\tdefault: break;\n\t}\n\treturn \"JsonValue\";\n}\nfunction renderTypeScriptTypeFromJsonSchema(schema) {\n\treturn render(schema, 0);\n}\n\n//#endregion\n//#region src/core/parameterized-types.ts\n/**\n* Shared utility for expanding parameterized Postgres types to their full SQL representation.\n*\n* This module provides a single source of truth for type expansion logic, used by:\n* - Schema verification (verify-sql-schema.ts) via the expandNativeType codec control hook\n* - Migration planner (planner.ts) via direct import\n*\n* @module\n*/\n/** Set of codec IDs that use the 'length' parameter */\nconst LENGTH_CODEC_IDS = new Set([\n\tSQL_CHAR_CODEC_ID,\n\tSQL_VARCHAR_CODEC_ID,\n\tPG_CHAR_CODEC_ID,\n\tPG_VARCHAR_CODEC_ID,\n\tPG_BIT_CODEC_ID,\n\tPG_VARBIT_CODEC_ID\n]);\n/** Set of codec IDs that use the 'precision' parameter for temporal types */\nconst TEMPORAL_PRECISION_CODEC_IDS = new Set([\n\tPG_TIMESTAMP_CODEC_ID,\n\tPG_TIMESTAMPTZ_CODEC_ID,\n\tPG_TIME_CODEC_ID,\n\tPG_TIMETZ_CODEC_ID,\n\tPG_INTERVAL_CODEC_ID\n]);\n/**\n* Validates that a value is a valid type parameter number.\n* Type parameters must be finite, non-negative integers.\n*/\nfunction isValidTypeParamNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\n/**\n* Expands a parameterized native type to its full SQL representation.\n*\n* For example:\n* - { nativeType: 'character varying', typeParams: { length: 255 } } -> 'character varying(255)'\n* - { nativeType: 'numeric', typeParams: { precision: 10, scale: 2 } } -> 'numeric(10,2)'\n* - { nativeType: 'timestamp without time zone', typeParams: { precision: 3 } } -> 'timestamp without time zone(3)'\n*\n* Returns the original nativeType if:\n* - No typeParams are provided\n* - No codecId is provided\n* - The codecId is not a known parameterized type\n* - The typeParams values are invalid\n*/\nfunction expandParameterizedNativeType(input) {\n\tconst { nativeType, codecId, typeParams } = input;\n\tif (!typeParams || !codecId) return nativeType;\n\tif (LENGTH_CODEC_IDS.has(codecId)) {\n\t\tconst length = typeParams[\"length\"];\n\t\tif (isValidTypeParamNumber(length)) return `${nativeType}(${length})`;\n\t\treturn nativeType;\n\t}\n\tif (codecId === PG_NUMERIC_CODEC_ID) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tconst scale = typeParams[\"scale\"];\n\t\tif (isValidTypeParamNumber(precision)) {\n\t\t\tif (isValidTypeParamNumber(scale)) return `${nativeType}(${precision},${scale})`;\n\t\t\treturn `${nativeType}(${precision})`;\n\t\t}\n\t\treturn nativeType;\n\t}\n\tif (TEMPORAL_PRECISION_CODEC_IDS.has(codecId)) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (isValidTypeParamNumber(precision)) return `${nativeType}(${precision})`;\n\t\treturn nativeType;\n\t}\n\treturn nativeType;\n}\n\n//#endregion\n//#region src/core/descriptor-meta.ts\n/** Creates a type import spec for codec types */\nconst codecTypeImport = (named) => ({\n\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\tnamed,\n\talias: named\n});\n/** Creates a precision-based TypeScript type renderer for temporal types */\nconst precisionRenderer = (typeName) => ({\n\tkind: \"function\",\n\trender: (params) => {\n\t\tconst precision = params[\"precision\"];\n\t\treturn typeof precision === \"number\" ? `${typeName}<${precision}>` : typeName;\n\t}\n});\n/** Creates control hooks with just expandNativeType for parameterized types */\nconst parameterizedTypeHooks = { expandNativeType: expandParameterizedNativeType };\n/**\n* Validates that a type expression string is safe to embed in generated .d.ts files.\n* Rejects expressions containing patterns that could inject executable code.\n*/\nfunction isSafeTypeExpression(expr) {\n\treturn !/import\\s*\\(|require\\s*\\(|declare\\s|export\\s|eval\\s*\\(/.test(expr);\n}\nfunction renderJsonTypeExpression(params) {\n\tconst typeName = params[\"type\"];\n\tif (typeof typeName === \"string\" && typeName.trim().length > 0) {\n\t\tconst trimmed = typeName.trim();\n\t\tif (!isSafeTypeExpression(trimmed)) return \"JsonValue\";\n\t\treturn trimmed;\n\t}\n\tconst schema = params[\"schemaJson\"];\n\tif (schema && typeof schema === \"object\") {\n\t\tconst rendered = renderTypeScriptTypeFromJsonSchema(schema);\n\t\tif (!isSafeTypeExpression(rendered)) return \"JsonValue\";\n\t\treturn rendered;\n\t}\n\treturn \"JsonValue\";\n}\nconst postgresAdapterDescriptorMeta = {\n\tkind: \"adapter\",\n\tfamilyId: \"sql\",\n\ttargetId: \"postgres\",\n\tid: \"postgres\",\n\tversion: \"0.0.1\",\n\tcapabilities: {\n\t\tpostgres: {\n\t\t\torderBy: true,\n\t\t\tlimit: true,\n\t\t\tlateral: true,\n\t\t\tjsonAgg: true,\n\t\t\treturning: true\n\t\t},\n\t\tsql: { enums: true }\n\t},\n\ttypes: {\n\t\tcodecTypes: {\n\t\t\timport: {\n\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\tnamed: \"CodecTypes\",\n\t\t\t\talias: \"PgTypes\"\n\t\t\t},\n\t\t\tparameterized: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: \"Char<{{length}}>\",\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: \"Varchar<{{length}}>\",\n\t\t\t\t[PG_CHAR_CODEC_ID]: \"Char<{{length}}>\",\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: \"Varchar<{{length}}>\",\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: (params) => {\n\t\t\t\t\t\tconst precision = params[\"precision\"];\n\t\t\t\t\t\tif (typeof precision !== \"number\") throw new Error(\"pg/numeric@1 renderer expects precision\");\n\t\t\t\t\t\tconst scale = params[\"scale\"];\n\t\t\t\t\t\treturn typeof scale === \"number\" ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t[PG_BIT_CODEC_ID]: \"Bit<{{length}}>\",\n\t\t\t\t[PG_VARBIT_CODEC_ID]: \"VarBit<{{length}}>\",\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: precisionRenderer(\"Timestamp\"),\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: precisionRenderer(\"Timestamptz\"),\n\t\t\t\t[PG_TIME_CODEC_ID]: precisionRenderer(\"Time\"),\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: precisionRenderer(\"Timetz\"),\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: precisionRenderer(\"Interval\"),\n\t\t\t\t[PG_ENUM_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: (params) => {\n\t\t\t\t\t\tconst values = params[\"values\"];\n\t\t\t\t\t\tif (!Array.isArray(values)) throw new Error(\"pg/enum@1 renderer expects values array\");\n\t\t\t\t\t\treturn values.map((value) => `'${String(value).replace(/'/g, \"\\\\'\")}'`).join(\" | \");\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t[PG_JSON_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: renderJsonTypeExpression\n\t\t\t\t},\n\t\t\t\t[PG_JSONB_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: renderJsonTypeExpression\n\t\t\t\t}\n\t\t\t},\n\t\t\ttypeImports: [\n\t\t\t\t{\n\t\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\t\tnamed: \"JsonValue\",\n\t\t\t\t\talias: \"JsonValue\"\n\t\t\t\t},\n\t\t\t\tcodecTypeImport(\"Char\"),\n\t\t\t\tcodecTypeImport(\"Varchar\"),\n\t\t\t\tcodecTypeImport(\"Numeric\"),\n\t\t\t\tcodecTypeImport(\"Bit\"),\n\t\t\t\tcodecTypeImport(\"VarBit\"),\n\t\t\t\tcodecTypeImport(\"Timestamp\"),\n\t\t\t\tcodecTypeImport(\"Timestamptz\"),\n\t\t\t\tcodecTypeImport(\"Time\"),\n\t\t\t\tcodecTypeImport(\"Timetz\"),\n\t\t\t\tcodecTypeImport(\"Interval\")\n\t\t\t],\n\t\t\tcontrolPlaneHooks: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_CHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_BIT_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_VARBIT_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIME_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_ENUM_CODEC_ID]: pgEnumControlHooks\n\t\t\t}\n\t\t},\n\t\tstorage: [\n\t\t\t{\n\t\t\t\ttypeId: PG_TEXT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"text\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT2_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int2\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_NUMERIC_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"numeric\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMP_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamp\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMPTZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamptz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIME_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"time\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMETZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timetz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BOOL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bool\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARBIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INTERVAL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"interval\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSON_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"json\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSONB_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"jsonb\"\n\t\t\t}\n\t\t]\n\t}\n};\n\n//#endregion\nexport { expandParameterizedNativeType as n, pgEnumControlHooks as r, postgresAdapterDescriptorMeta as t };\n//# sourceMappingURL=descriptor-meta-ilnFI7bx.mjs.map","import { i as quoteIdentifier, n as escapeLiteral, r as qualifyName, t as SqlEscapeError } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { n as expandParameterizedNativeType, r as pgEnumControlHooks, t as postgresAdapterDescriptorMeta } from \"./descriptor-meta-ilnFI7bx.mjs\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/core/default-normalizer.ts\n/**\n* Pre-compiled regex patterns for performance.\n* These are compiled once at module load time rather than on each function call.\n*/\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst TIMESTAMP_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP|clock_timestamp\\s*\\(\\s*\\))$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n/**\n* Parses a raw Postgres column default expression into a normalized ColumnDefault.\n* This enables semantic comparison between contract defaults and introspected schema defaults.\n*\n* Used by the migration diff layer to normalize raw database defaults during comparison,\n* keeping the introspection layer focused on faithful data capture.\n*\n* @param rawDefault - Raw default expression from information_schema.columns.column_default\n* @param _nativeType - Native column type (currently unused, reserved for future type-aware parsing)\n* @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n*/\nfunction parsePostgresDefault(rawDefault, _nativeType) {\n\tconst trimmed = rawDefault.trim();\n\tconst normalizedType = _nativeType?.toLowerCase();\n\tconst isBigInt = normalizedType === \"bigint\" || normalizedType === \"int8\";\n\tif (NEXTVAL_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"autoincrement()\"\n\t};\n\tif (TIMESTAMP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"now()\"\n\t};\n\tif (UUID_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (UUID_OSSP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (TRUE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: true\n\t};\n\tif (FALSE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: false\n\t};\n\tif (NUMERIC_PATTERN.test(trimmed)) {\n\t\tif (isBigInt) return {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: {\n\t\t\t\t$type: \"bigint\",\n\t\t\t\tvalue: trimmed\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: Number(trimmed)\n\t\t};\n\t}\n\tconst stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n\tif (stringMatch?.[1] !== void 0) {\n\t\tconst unescaped = stringMatch[1].replace(/''/g, \"'\");\n\t\tif (normalizedType === \"json\" || normalizedType === \"jsonb\") try {\n\t\t\treturn {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: JSON.parse(unescaped)\n\t\t\t};\n\t\t} catch {}\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: unescaped\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"function\",\n\t\texpression: trimmed\n\t};\n}\n\n//#endregion\n//#region src/core/control-adapter.ts\n/**\n* Postgres control plane adapter for control-plane operations like introspection.\n* Provides target-specific implementations for control-plane domain actions.\n*/\nvar PostgresControlAdapter = class {\n\tfamilyId = \"sql\";\n\ttargetId = \"postgres\";\n\t/**\n\t* @deprecated Use targetId instead\n\t*/\n\ttarget = \"postgres\";\n\t/**\n\t* Target-specific normalizer for raw Postgres default expressions.\n\t* Used by schema verification to normalize raw defaults before comparison.\n\t*/\n\tnormalizeDefault = parsePostgresDefault;\n\t/**\n\t* Target-specific normalizer for Postgres schema native type names.\n\t* Used by schema verification to normalize introspected type names\n\t* before comparison with contract native types.\n\t*/\n\tnormalizeNativeType = normalizeSchemaNativeType;\n\t/**\n\t* Introspects a Postgres database schema and returns a raw SqlSchemaIR.\n\t*\n\t* This is a pure schema discovery operation that queries the Postgres catalog\n\t* and returns the schema structure without type mapping or contract enrichment.\n\t* Type mapping and enrichment are handled separately by enrichment helpers.\n\t*\n\t* Uses batched queries to minimize database round trips (7 queries instead of 5T+3).\n\t*\n\t* @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries\n\t* @param contractIR - Optional contract IR for contract-guided introspection (filtering, optimization)\n\t* @param schema - Schema name to introspect (defaults to 'public')\n\t* @returns Promise resolving to SqlSchemaIR representing the live database schema\n\t*/\n\tasync introspect(driver, _contractIR, schema = \"public\") {\n\t\tconst [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult, extensionsResult] = await Promise.all([\n\t\t\tdriver.query(`SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`, [schema]),\n\t\t\tdriver.query(`SELECT\n c.table_name,\n column_name,\n data_type,\n udt_name,\n is_nullable,\n character_maximum_length,\n numeric_precision,\n numeric_scale,\n column_default,\n format_type(a.atttypid, a.atttypmod) AS formatted_type\n FROM information_schema.columns c\n JOIN pg_catalog.pg_class cl\n ON cl.relname = c.table_name\n JOIN pg_catalog.pg_namespace ns\n ON ns.nspname = c.table_schema\n AND ns.oid = cl.relnamespace\n JOIN pg_catalog.pg_attribute a\n ON a.attrelid = cl.oid\n AND a.attname = c.column_name\n AND a.attnum > 0\n AND NOT a.attisdropped\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\n ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position,\n ref_ns.nspname AS referenced_table_schema,\n ref_cl.relname AS referenced_table_name,\n ref_att.attname AS referenced_column_name,\n rc.delete_rule,\n rc.update_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n JOIN pg_catalog.pg_constraint pgc\n ON pgc.conname = tc.constraint_name\n AND pgc.connamespace = (\n SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema\n )\n JOIN pg_catalog.pg_class ref_cl\n ON ref_cl.oid = pgc.confrelid\n JOIN pg_catalog.pg_namespace ref_ns\n ON ref_ns.oid = ref_cl.relnamespace\n JOIN pg_catalog.pg_attribute ref_att\n ON ref_att.attrelid = pgc.confrelid\n AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]\n JOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n i.tablename,\n i.indexname,\n ix.indisunique,\n a.attname,\n a.attnum\n FROM pg_indexes i\n JOIN pg_class ic ON ic.relname = i.indexname\n JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1\n JOIN pg_index ix ON ix.indexrelid = ic.oid\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0\n WHERE i.schemaname = $1\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.table_constraints tc\n WHERE tc.table_schema = $1\n AND tc.table_name = i.tablename\n AND tc.constraint_name = i.indexname\n )\n ORDER BY i.tablename, i.indexname, a.attnum`, [schema]),\n\t\t\tdriver.query(`SELECT extname\n FROM pg_extension\n ORDER BY extname`, [])\n\t\t]);\n\t\tconst columnsByTable = groupBy(columnsResult.rows, \"table_name\");\n\t\tconst pksByTable = groupBy(pkResult.rows, \"table_name\");\n\t\tconst fksByTable = groupBy(fkResult.rows, \"table_name\");\n\t\tconst uniquesByTable = groupBy(uniqueResult.rows, \"table_name\");\n\t\tconst indexesByTable = groupBy(indexResult.rows, \"tablename\");\n\t\tconst pkConstraintsByTable = /* @__PURE__ */ new Map();\n\t\tfor (const row of pkResult.rows) {\n\t\t\tlet constraints = pkConstraintsByTable.get(row.table_name);\n\t\t\tif (!constraints) {\n\t\t\t\tconstraints = /* @__PURE__ */ new Set();\n\t\t\t\tpkConstraintsByTable.set(row.table_name, constraints);\n\t\t\t}\n\t\t\tconstraints.add(row.constraint_name);\n\t\t}\n\t\tconst tables = {};\n\t\tfor (const tableRow of tablesResult.rows) {\n\t\t\tconst tableName = tableRow.table_name;\n\t\t\tconst columns = {};\n\t\t\tfor (const colRow of columnsByTable.get(tableName) ?? []) {\n\t\t\t\tlet nativeType = colRow.udt_name;\n\t\t\t\tconst formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;\n\t\t\t\tif (formattedType) nativeType = formattedType;\n\t\t\t\telse if (colRow.data_type === \"character varying\" || colRow.data_type === \"character\") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse if (colRow.data_type === \"numeric\" || colRow.data_type === \"decimal\") if (colRow.numeric_precision && colRow.numeric_scale !== null) nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;\n\t\t\t\telse if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse nativeType = colRow.udt_name || colRow.data_type;\n\t\t\t\tcolumns[colRow.column_name] = {\n\t\t\t\t\tname: colRow.column_name,\n\t\t\t\t\tnativeType,\n\t\t\t\t\tnullable: colRow.is_nullable === \"YES\",\n\t\t\t\t\t...ifDefined(\"default\", colRow.column_default ?? void 0)\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pkRows = [...pksByTable.get(tableName) ?? []];\n\t\t\tconst primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);\n\t\t\tconst primaryKey = primaryKeyColumns.length > 0 ? {\n\t\t\t\tcolumns: primaryKeyColumns,\n\t\t\t\t...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}\n\t\t\t} : void 0;\n\t\t\tconst foreignKeysMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const fkRow of fksByTable.get(tableName) ?? []) {\n\t\t\t\tconst existing = foreignKeysMap.get(fkRow.constraint_name);\n\t\t\t\tif (existing) {\n\t\t\t\t\texisting.columns.push(fkRow.column_name);\n\t\t\t\t\texisting.referencedColumns.push(fkRow.referenced_column_name);\n\t\t\t\t} else foreignKeysMap.set(fkRow.constraint_name, {\n\t\t\t\t\tcolumns: [fkRow.column_name],\n\t\t\t\t\treferencedTable: fkRow.referenced_table_name,\n\t\t\t\t\treferencedColumns: [fkRow.referenced_column_name],\n\t\t\t\t\tname: fkRow.constraint_name,\n\t\t\t\t\tdeleteRule: fkRow.delete_rule,\n\t\t\t\t\tupdateRule: fkRow.update_rule\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({\n\t\t\t\tcolumns: Object.freeze([...fk.columns]),\n\t\t\t\treferencedTable: fk.referencedTable,\n\t\t\t\treferencedColumns: Object.freeze([...fk.referencedColumns]),\n\t\t\t\tname: fk.name,\n\t\t\t\t...ifDefined(\"onDelete\", mapReferentialAction(fk.deleteRule)),\n\t\t\t\t...ifDefined(\"onUpdate\", mapReferentialAction(fk.updateRule))\n\t\t\t}));\n\t\t\tconst pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();\n\t\t\tconst uniquesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const uniqueRow of uniquesByTable.get(tableName) ?? []) {\n\t\t\t\tif (pkConstraints.has(uniqueRow.constraint_name)) continue;\n\t\t\t\tconst existing = uniquesMap.get(uniqueRow.constraint_name);\n\t\t\t\tif (existing) existing.columns.push(uniqueRow.column_name);\n\t\t\t\telse uniquesMap.set(uniqueRow.constraint_name, {\n\t\t\t\t\tcolumns: [uniqueRow.column_name],\n\t\t\t\t\tname: uniqueRow.constraint_name\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst uniques = Array.from(uniquesMap.values()).map((uq) => ({\n\t\t\t\tcolumns: Object.freeze([...uq.columns]),\n\t\t\t\tname: uq.name\n\t\t\t}));\n\t\t\tconst indexesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const idxRow of indexesByTable.get(tableName) ?? []) {\n\t\t\t\tif (!idxRow.attname) continue;\n\t\t\t\tconst existing = indexesMap.get(idxRow.indexname);\n\t\t\t\tif (existing) existing.columns.push(idxRow.attname);\n\t\t\t\telse indexesMap.set(idxRow.indexname, {\n\t\t\t\t\tcolumns: [idxRow.attname],\n\t\t\t\t\tname: idxRow.indexname,\n\t\t\t\t\tunique: idxRow.indisunique\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst indexes = Array.from(indexesMap.values()).map((idx) => ({\n\t\t\t\tcolumns: Object.freeze([...idx.columns]),\n\t\t\t\tname: idx.name,\n\t\t\t\tunique: idx.unique\n\t\t\t}));\n\t\t\ttables[tableName] = {\n\t\t\t\tname: tableName,\n\t\t\t\tcolumns,\n\t\t\t\t...ifDefined(\"primaryKey\", primaryKey),\n\t\t\t\tforeignKeys,\n\t\t\t\tuniques,\n\t\t\t\tindexes\n\t\t\t};\n\t\t}\n\t\tconst extensions = extensionsResult.rows.map((row) => row.extname);\n\t\tconst storageTypes = await pgEnumControlHooks.introspectTypes?.({\n\t\t\tdriver,\n\t\t\tschemaName: schema\n\t\t}) ?? {};\n\t\treturn {\n\t\t\ttables,\n\t\t\textensions,\n\t\t\tannotations: { pg: {\n\t\t\t\tschema,\n\t\t\t\tversion: await this.getPostgresVersion(driver),\n\t\t\t\t...ifDefined(\"storageTypes\", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)\n\t\t\t} }\n\t\t};\n\t}\n\t/**\n\t* Gets the Postgres version from the database.\n\t*/\n\tasync getPostgresVersion(driver) {\n\t\treturn ((await driver.query(\"SELECT version() AS version\", [])).rows[0]?.version ?? \"\").match(/PostgreSQL (\\d+\\.\\d+)/)?.[1] ?? \"unknown\";\n\t}\n};\n/**\n* Pre-computed lookup map for simple prefix-based type normalization.\n* Maps short Postgres type names to their canonical SQL names.\n* Using a Map for O(1) lookup instead of multiple startsWith checks.\n*/\nconst TYPE_PREFIX_MAP = new Map([\n\t[\"varchar\", \"character varying\"],\n\t[\"bpchar\", \"character\"],\n\t[\"varbit\", \"bit varying\"]\n]);\n/**\n* Normalizes a Postgres schema native type to its canonical form for comparison.\n*\n* Uses a pre-computed lookup map for simple prefix replacements (O(1))\n* and handles complex temporal type normalization separately.\n*/\nfunction normalizeSchemaNativeType(nativeType) {\n\tconst trimmed = nativeType.trim();\n\tfor (const [prefix, replacement] of TYPE_PREFIX_MAP) if (trimmed.startsWith(prefix)) return replacement + trimmed.slice(prefix.length);\n\tif (trimmed.includes(\" with time zone\")) {\n\t\tif (trimmed.startsWith(\"timestamp\")) return `timestamptz${trimmed.slice(9).replace(\" with time zone\", \"\")}`;\n\t\tif (trimmed.startsWith(\"time\")) return `timetz${trimmed.slice(4).replace(\" with time zone\", \"\")}`;\n\t}\n\tif (trimmed.includes(\" without time zone\")) return trimmed.replace(\" without time zone\", \"\");\n\treturn trimmed;\n}\nfunction normalizeFormattedType(formattedType, dataType, udtName) {\n\tif (formattedType === \"integer\") return \"int4\";\n\tif (formattedType === \"smallint\") return \"int2\";\n\tif (formattedType === \"bigint\") return \"int8\";\n\tif (formattedType === \"real\") return \"float4\";\n\tif (formattedType === \"double precision\") return \"float8\";\n\tif (formattedType === \"boolean\") return \"bool\";\n\tif (formattedType.startsWith(\"varchar\")) return formattedType.replace(\"varchar\", \"character varying\");\n\tif (formattedType.startsWith(\"bpchar\")) return formattedType.replace(\"bpchar\", \"character\");\n\tif (formattedType.startsWith(\"varbit\")) return formattedType.replace(\"varbit\", \"bit varying\");\n\tif (dataType === \"timestamp with time zone\" || udtName === \"timestamptz\") return formattedType.replace(\"timestamp\", \"timestamptz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"timestamp without time zone\" || udtName === \"timestamp\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (dataType === \"time with time zone\" || udtName === \"timetz\") return formattedType.replace(\"time\", \"timetz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"time without time zone\" || udtName === \"time\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (formattedType.startsWith(\"\\\"\") && formattedType.endsWith(\"\\\"\")) return formattedType.slice(1, -1);\n\treturn formattedType;\n}\nconst PG_REFERENTIAL_ACTION_MAP = {\n\t\"NO ACTION\": \"noAction\",\n\tRESTRICT: \"restrict\",\n\tCASCADE: \"cascade\",\n\t\"SET NULL\": \"setNull\",\n\t\"SET DEFAULT\": \"setDefault\"\n};\n/**\n* Maps a Postgres referential action rule to the canonical SqlReferentialAction.\n* Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.\n* Throws for unrecognized rules to prevent silent data loss.\n*/\nfunction mapReferentialAction(rule) {\n\tconst mapped = PG_REFERENTIAL_ACTION_MAP[rule];\n\tif (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: \"${rule}\". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);\n\tif (mapped === \"noAction\") return void 0;\n\treturn mapped;\n}\n/**\n* Groups an array of objects by a specified key.\n* Returns a Map for O(1) lookup by group key.\n*/\nfunction groupBy(items, key) {\n\tconst map = /* @__PURE__ */ new Map();\n\tfor (const item of items) {\n\t\tconst groupKey = item[key];\n\t\tlet group = map.get(groupKey);\n\t\tif (!group) {\n\t\t\tgroup = [];\n\t\t\tmap.set(groupKey, group);\n\t\t}\n\t\tgroup.push(item);\n\t}\n\treturn map;\n}\n\n//#endregion\n//#region src/exports/control.ts\nconst postgresAdapterDescriptor = {\n\t...postgresAdapterDescriptorMeta,\n\toperationSignatures: () => [],\n\tcreate() {\n\t\treturn new PostgresControlAdapter();\n\t}\n};\nvar control_default = postgresAdapterDescriptor;\n\n//#endregion\nexport { SqlEscapeError, control_default as default, escapeLiteral, expandParameterizedNativeType, normalizeSchemaNativeType, parsePostgresDefault, qualifyName, quoteIdentifier };\n//# sourceMappingURL=control.mjs.map","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\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 buildTargetDetails,\n columnExistsCheck,\n columnNullabilityCheck,\n constraintExistsCheck,\n qualifyTableName,\n toRegclassLiteral,\n} from './planner';\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}): {\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 });\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 'extension_missing':\n return true;\n case 'primary_key_mismatch':\n return issue.actual === undefined;\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'foreign_key_mismatch':\n return issue.indexOrConstraint === undefined;\n default:\n return false;\n }\n}\n\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}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const { issue, contract, schemaName, mode } = 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(schemaName, issue.table, issue.column, contractColumn);\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): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n const expectedType = buildColumnTypeSql(column);\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 // extension_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 expandParameterizedNativeType,\n normalizeSchemaNativeType,\n parsePostgresDefault,\n quoteIdentifier,\n} from '@prisma-next/adapter-postgres/control';\nimport { isTaggedBigInt } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport {\n createMigrationPlan,\n extractCodecControlHooks,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type {\n ForeignKey,\n ReferentialAction,\n StorageColumn,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresColumnDefault } from '../types';\nimport { buildReconciliationPlan } from './planner-reconciliation';\n\nexport type OperationClass =\n | 'extension'\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 readonly verifyDatabaseDependencyInstalled: (schema: SqlSchemaIR) => readonly SchemaIssue[];\n};\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\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 });\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),\n ...this.buildColumnOperations(sortedTables, options.schema, schemaName),\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 for (const dependency of dependencies) {\n if (seenDependencyIds.has(dependency.id)) {\n continue;\n }\n seenDependencyIds.add(dependency.id);\n\n const issues = dependency.verifyDatabaseDependencyInstalled(options.schema);\n if (issues.length === 0) {\n continue;\n }\n\n for (const installOp of dependency.install) {\n if (seenOperationIds.has(installOp.id)) {\n continue;\n }\n seenOperationIds.add(installOp.id);\n // SQL family components are expected to provide compatible target details. This would be better if\n // the type system could enforce it but it's not likely to occur in practice.\n operations.push(installOp as SqlMigrationPlanOperation<PostgresPlanTargetDetails>);\n }\n }\n\n return operations;\n }\n\n private buildStorageTypeOperations(\n options: PlannerOptionsWithComponents,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): {\n readonly operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly conflicts: readonly SqlPlannerConflict[];\n } {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n const storageTypes = options.contract.storage.types ?? {};\n\n for (const [typeName, typeInstance] of sortedEntries(storageTypes)) {\n const hook = codecHooks.get(typeInstance.codecId);\n const planResult = hook?.planTypeOperations?.({\n typeName,\n typeInstance,\n contract: options.contract,\n schema: options.schema,\n schemaName,\n policy: options.policy,\n });\n if (!planResult) {\n continue;\n }\n for (const operation of planResult.operations) {\n if (!options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n conflicts.push({\n kind: 'missingButNonAdditive',\n summary: `Storage type \"${typeName}\" requires \"${operation.operationClass}\" operation \"${operation.id}\"`,\n location: {\n type: typeName,\n },\n });\n continue;\n }\n operations.push({\n ...operation,\n target: {\n id: operation.target.id,\n details: this.buildTargetDetails('type', typeName, schemaName),\n },\n });\n }\n }\n\n return { operations, conflicts };\n }\n private collectDependencies(\n options: PlannerOptionsWithComponents,\n ): ReadonlyArray<PlannerDatabaseDependency> {\n const components = options.frameworkComponents;\n if (components.length === 0) {\n return [];\n }\n const deps: PlannerDatabaseDependency[] = [];\n for (const component of components) {\n if (!isSqlDependencyProvider(component)) {\n continue;\n }\n const initDeps = component.databaseDependencies?.init;\n if (initDeps && initDeps.length > 0) {\n deps.push(...initDeps);\n }\n }\n return sortDependencies(deps);\n }\n\n private buildTableOperations(\n tables: 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 (schema.tables[tableName]) {\n continue;\n }\n const qualified = qualifyTableName(schemaName, tableName);\n operations.push({\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" does not exist`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: buildCreateTableSql(qualified, table),\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n });\n }\n return operations;\n }\n\n private buildColumnOperations(\n tables: 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 const schemaTable = schema.tables[tableName];\n if (!schemaTable) {\n continue;\n }\n for (const [columnName, column] of sortedEntries(table.columns)) {\n if (schemaTable.columns[columnName]) {\n continue;\n }\n operations.push(this.buildAddColumnOperation(schemaName, tableName, columnName, column));\n }\n }\n return operations;\n }\n\n private buildAddColumnOperation(\n schema: string,\n tableName: string,\n columnName: string,\n column: StorageColumn,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schema, tableName);\n const notNull = column.nullable === false;\n const hasDefault = column.default !== undefined;\n // Only require empty table for NOT NULL columns WITHOUT defaults.\n // PostgreSQL allows adding NOT NULL columns with defaults to non-empty tables\n // because the default value is applied to existing rows.\n const requiresEmptyTable = notNull && !hasDefault;\n const precheck = [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ...(requiresEmptyTable\n ? [\n {\n description: `ensure table \"${tableName}\" is empty before adding NOT NULL column without default`,\n sql: tableIsEmptyCheck(qualified),\n },\n ]\n : []),\n ];\n const execute = [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(qualified, columnName, column),\n },\n ];\n const postcheck = [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n ...(notNull\n ? [\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ]\n : []),\n ];\n\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schema),\n },\n precheck,\n execute,\n postcheck,\n };\n }\n\n private buildPrimaryKeyOperations(\n tables: 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 ?? `${tableName}_${index.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${index.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n /**\n * Generates FK-backing index operations for FKs with `index: true`,\n * but only when no matching user-declared index exists in `contractTable.indexes`.\n */\n private buildFkBackingIndexOperations(\n tables: 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 = `${tableName}_${fk.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create FK-backing index ${indexName} on ${tableName}`,\n summary: `Creates FK-backing index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create FK-backing index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${fk.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildForeignKeyOperations(\n tables: 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 isSqlDependencyProvider(component: unknown): component is {\n readonly databaseDependencies?: {\n readonly init?: readonly PlannerDatabaseDependency[];\n };\n} {\n if (typeof component !== 'object' || component === null) {\n return false;\n }\n const record = component as Record<string, unknown>;\n\n // If present, enforce familyId match to avoid mixing families at runtime.\n if (Object.hasOwn(record, 'familyId') && record['familyId'] !== 'sql') {\n return false;\n }\n\n if (!Object.hasOwn(record, 'databaseDependencies')) {\n return false;\n }\n const deps = record['databaseDependencies'];\n return deps === undefined || (typeof deps === 'object' && deps !== null);\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n if (dependencies.length <= 1) {\n return dependencies;\n }\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction buildCreateTableSql(qualifiedTableName: string, table: StorageTable): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column),\n buildColumnDefaultSql(column.default, column),\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n },\n );\n\n const constraintDefinitions: string[] = [];\n if (table.primaryKey) {\n constraintDefinitions.push(\n `PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n );\n }\n\n const allDefinitions = [...columnDefinitions, ...constraintDefinitions];\n return `CREATE TABLE ${qualifiedTableName} (\\n ${allDefinitions.join(',\\n ')}\\n)`;\n}\n\n/**\n * 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\n/**\n * Builds the column type SQL, handling autoincrement as a special case.\n * For autoincrement on int4/int8, we use SERIAL/BIGSERIAL types.\n */\nexport function buildColumnTypeSql(column: StorageColumn): string {\n const columnDefault = column.default;\n\n // For autoincrement, use SERIAL/BIGSERIAL types instead of int4/int8\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (column.nativeType === 'int4' || column.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (column.nativeType === 'int8' || column.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (column.nativeType === 'int2' || column.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n\n if (column.typeRef) {\n return quoteIdentifier(column.nativeType);\n }\n\n // Validate nativeType before using it unquoted in DDL\n assertSafeNativeType(column.nativeType);\n return renderParameterizedTypeSql(column) ?? column.nativeType;\n}\n\n/**\n * Renders parameterized type SQL for a column, returning null if no expansion is needed.\n *\n * Uses the shared expandParameterizedNativeType utility from the postgres adapter.\n * Returns null when the column has no typeParams, allowing the caller to fall back\n * to the base nativeType.\n */\nfunction renderParameterizedTypeSql(column: StorageColumn): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n const expanded = expandParameterizedNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n // If no expansion happened (returned the same base type), return null\n // so caller can decide whether to use nativeType directly\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/**\n * Builds the DEFAULT clause for a column definition.\n * Returns empty string if no default is defined.\n *\n * Note: autoincrement is handled specially via SERIAL types, so we skip it here.\n */\nfunction buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n // autoincrement is handled by SERIAL type, no explicit DEFAULT needed\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n // Sequence names use quoteIdentifier for safe identifier handling\n return `DEFAULT nextval(${quoteIdentifier(columnDefault.name)}::regclass)`;\n }\n}\n\nfunction renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (!isJsonColumn && isTaggedBigInt(value)) {\n if (!/^-?\\d+$/.test(value.value)) {\n throw new Error(`Invalid tagged bigint value: \"${value.value}\" is not a valid integer`);\n }\n return value.value;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'NULL';\n }\n const json = JSON.stringify(value);\n if (isJsonColumn) {\n return `'${escapeLiteral(json)}'::${column.nativeType}`;\n }\n return `'${escapeLiteral(json)}'`;\n}\n\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\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\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\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\nfunction tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nfunction buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n): string {\n const typeSql = buildColumnTypeSql(column);\n const defaultSql = buildColumnDefaultSql(column.default, column);\n const parts = [\n `ALTER TABLE ${qualifiedTableName}`,\n `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,\n defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n}\n\nfunction tableHasPrimaryKeyCheck(\n schema: string,\n table: string,\n exists: boolean,\n constraintName?: string,\n): string {\n const comparison = exists ? '' : 'NOT ';\n const constraintFilter = constraintName\n ? `AND c2.relname = '${escapeLiteral(constraintName)}'`\n : '';\n return `SELECT ${comparison}EXISTS (\n SELECT 1\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid\n WHERE n.nspname = '${escapeLiteral(schema)}'\n AND c.relname = '${escapeLiteral(table)}'\n AND i.indisprimary\n ${constraintFilter}\n)`;\n}\n\n/**\n * 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\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\nfunction buildForeignKeySql(\n schemaName: string,\n tableName: string,\n fkName: string,\n foreignKey: ForeignKey,\n): string {\n let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`;\n\n if (foreignKey.onDelete !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];\n if (!action) {\n throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);\n }\n sql += `\\nON DELETE ${action}`;\n }\n if (foreignKey.onUpdate !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];\n if (!action) {\n throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);\n }\n sql += `\\nON UPDATE ${action}`;\n }\n\n return sql;\n}\n","import { bigintJsonReplacer } from '@prisma-next/contract/types';\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport const ensurePrismaContractSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}'\n )`,\n params: [],\n};\n\nexport const ensureLedgerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.ledger (\n id bigserial primary key,\n created_at timestamptz not null default now(),\n origin_core_hash text,\n origin_profile_hash text,\n destination_core_hash text not null,\n destination_profile_hash text,\n contract_json_before jsonb,\n contract_json_after jsonb,\n operations jsonb not null\n )`,\n params: [],\n};\n\nexport interface WriteMarkerInput {\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number | null;\n readonly appTag?: string | null;\n readonly meta?: Record<string, unknown>;\n}\n\nexport function buildWriteMarkerStatements(input: WriteMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n 1,\n input.storageHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n id,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb\n )`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set\n core_hash = $2,\n profile_hash = $3,\n contract_json = $4::jsonb,\n canonical_version = $5,\n updated_at = now(),\n app_tag = $6,\n meta = $7::jsonb\n where id = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originStorageHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationStorageHash: string;\n readonly destinationProfileHash?: string | null;\n readonly contractJsonBefore?: unknown;\n readonly contractJsonAfter?: unknown;\n readonly operations: unknown;\n}\n\nexport function buildLedgerInsertStatement(input: LedgerInsertInput): SqlStatement {\n return {\n sql: `insert into prisma_contract.ledger (\n origin_core_hash,\n origin_profile_hash,\n destination_core_hash,\n destination_profile_hash,\n contract_json_before,\n contract_json_after,\n operations\n ) values (\n $1,\n $2,\n $3,\n $4,\n $5::jsonb,\n $6::jsonb,\n $7::jsonb\n )`,\n params: [\n input.originStorageHash ?? null,\n input.originProfileHash ?? null,\n input.destinationStorageHash,\n input.destinationProfileHash ?? null,\n jsonParam(input.contractJsonBefore),\n jsonParam(input.contractJsonAfter),\n jsonParam(input.operations),\n ],\n };\n}\n\nfunction jsonParam(value: unknown): string {\n return JSON.stringify(value ?? null, bigintJsonReplacer);\n}\n","import {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n} from '@prisma-next/adapter-postgres/control';\nimport type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport { readMarker } from '@prisma-next/family-sql/verify';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport type { PostgresPlanTargetDetails } from './planner';\nimport {\n buildLedgerInsertStatement,\n buildWriteMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await readMarker(driver);\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // Apply plan operations or skip if marker already at destination\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n let applyValue: ApplyPlanSuccessValue;\n\n if (markerAtDestination) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contractIR: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Record marker and ledger entries\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // 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 {\n ControlTargetInstance,\n MigrationPlanner,\n MigrationRunner,\n} from '@prisma-next/core-control-plane/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n operationSignatures: () => [],\n /**\n * Migrations capability for CLI to access planner/runner via core types.\n * The SQL-specific planner/runner types are compatible with the generic\n * MigrationPlanner/MigrationRunner interfaces at runtime.\n */\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner() as MigrationPlanner<'sql', 'postgres'>;\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAWA,IAAI,iBAAiB,cAAc,MAAM;CACxC,YAAY,SAAS,OAAO,MAAM;AACjC,QAAM,QAAQ;AACd,OAAK,QAAQ;AACb,OAAK,OAAO;AACZ,OAAK,OAAO;;;;;;AAMd,MAAMA,0BAAwB;;;;;;;;;;;AAW9B,SAAS,gBAAgB,YAAY;AACpC,KAAI,WAAW,WAAW,EAAG,OAAM,IAAI,eAAe,8BAA8B,YAAY,aAAa;AAC7G,KAAI,WAAW,SAAS,KAAK,CAAE,OAAM,IAAI,eAAe,wCAAwC,WAAW,QAAQ,OAAO,MAAM,EAAE,aAAa;AAC/I,KAAI,WAAW,SAASA,wBAAuB,SAAQ,KAAK,eAAe,WAAW,MAAM,GAAG,GAAG,CAAC,4BAA4BA,wBAAsB,wCAAwC;AAC7L,QAAO,IAAI,WAAW,QAAQ,MAAM,OAAO,CAAC;;;;;;;;;;;;;AAa7C,SAAS,cAAc,OAAO;AAC7B,KAAI,MAAM,SAAS,KAAK,CAAE,OAAM,IAAI,eAAe,2CAA2C,MAAM,QAAQ,OAAO,MAAM,EAAE,UAAU;AACrI,QAAO,MAAM,QAAQ,MAAM,KAAK;;;;;AAK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,iBACZ,QACA,WACe;AACf,MAAI,UAAU,OAAO,SAAS,GAAG;AAC/B,SAAM,OAAO,MAAM,UAAU,KAAK,UAAU,OAAO;AACnD;;AAEF,QAAM,OAAO,MAAM,UAAU,IAAI;;;;;;AC9jBrC,MAAMC,2BACJ;CACE,GAAG;CACH,2BAA2B,EAAE;CAM7B,YAAY;EACV,cAAc,SAAmC;AAC/C,UAAO,gCAAgC;;EAEzC,aAAa,QAAQ;AACnB,UAAO,8BAA8B,OAAO;;EAE/C;CACD,SAAmD;AACjD,SAAO;GACL,UAAU;GACV,UAAU;GACX;;CAMH,cAAc,SAAmC;AAC/C,SAAO,gCAAgC;;CAMzC,aAAa,QAAQ;AACnB,SAAO,8BAA8B,OAAO;;CAE/C;AAEH,sBAAe"}
1
+ {"version":3,"file":"control.mjs","names":["MAX_IDENTIFIER_LENGTH","control_default","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","deps: PlannerDatabaseDependency[]","constraintDefinitions: string[]","REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string>","ensurePrismaContractSchemaStatement: SqlStatement","ensureMarkerTableStatement: SqlStatement","ensureLedgerTableStatement: SqlStatement","params: readonly unknown[]","DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../../../6-adapters/postgres/dist/codec-ids-Bsm9c7ns.mjs","../../../6-adapters/postgres/dist/sql-utils-CSfAGEwF.mjs","../../../6-adapters/postgres/dist/descriptor-meta-ilnFI7bx.mjs","../../../6-adapters/postgres/dist/control.mjs","../src/core/migrations/planner-reconciliation.ts","../src/core/migrations/planner.ts","../src/core/migrations/statement-builders.ts","../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import { SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_VARCHAR_CODEC_ID } from \"@prisma-next/sql-relational-core/ast\";\n\n//#region src/core/codec-ids.ts\nconst PG_TEXT_CODEC_ID = \"pg/text@1\";\nconst PG_ENUM_CODEC_ID = \"pg/enum@1\";\nconst PG_CHAR_CODEC_ID = \"pg/char@1\";\nconst PG_VARCHAR_CODEC_ID = \"pg/varchar@1\";\nconst PG_INT_CODEC_ID = \"pg/int@1\";\nconst PG_INT2_CODEC_ID = \"pg/int2@1\";\nconst PG_INT4_CODEC_ID = \"pg/int4@1\";\nconst PG_INT8_CODEC_ID = \"pg/int8@1\";\nconst PG_FLOAT_CODEC_ID = \"pg/float@1\";\nconst PG_FLOAT4_CODEC_ID = \"pg/float4@1\";\nconst PG_FLOAT8_CODEC_ID = \"pg/float8@1\";\nconst PG_NUMERIC_CODEC_ID = \"pg/numeric@1\";\nconst PG_BOOL_CODEC_ID = \"pg/bool@1\";\nconst PG_BIT_CODEC_ID = \"pg/bit@1\";\nconst PG_VARBIT_CODEC_ID = \"pg/varbit@1\";\nconst PG_TIMESTAMP_CODEC_ID = \"pg/timestamp@1\";\nconst PG_TIMESTAMPTZ_CODEC_ID = \"pg/timestamptz@1\";\nconst PG_TIME_CODEC_ID = \"pg/time@1\";\nconst PG_TIMETZ_CODEC_ID = \"pg/timetz@1\";\nconst PG_INTERVAL_CODEC_ID = \"pg/interval@1\";\nconst PG_JSON_CODEC_ID = \"pg/json@1\";\nconst PG_JSONB_CODEC_ID = \"pg/jsonb@1\";\n\n//#endregion\nexport { SQL_CHAR_CODEC_ID as C, SQL_VARCHAR_CODEC_ID as E, PG_VARCHAR_CODEC_ID as S, SQL_INT_CODEC_ID as T, PG_TIMESTAMPTZ_CODEC_ID as _, PG_FLOAT4_CODEC_ID as a, PG_TIME_CODEC_ID as b, PG_INT2_CODEC_ID as c, PG_INTERVAL_CODEC_ID as d, PG_INT_CODEC_ID as f, PG_TEXT_CODEC_ID as g, PG_NUMERIC_CODEC_ID as h, PG_ENUM_CODEC_ID as i, PG_INT4_CODEC_ID as l, PG_JSON_CODEC_ID as m, PG_BOOL_CODEC_ID as n, PG_FLOAT8_CODEC_ID as o, PG_JSONB_CODEC_ID as p, PG_CHAR_CODEC_ID as r, PG_FLOAT_CODEC_ID as s, PG_BIT_CODEC_ID as t, PG_INT8_CODEC_ID as u, PG_TIMESTAMP_CODEC_ID as v, SQL_FLOAT_CODEC_ID as w, PG_VARBIT_CODEC_ID as x, PG_TIMETZ_CODEC_ID as y };\n//# sourceMappingURL=codec-ids-Bsm9c7ns.mjs.map","//#region src/core/sql-utils.ts\n/**\n* Shared SQL utility functions for the Postgres adapter.\n*\n* These functions handle safe SQL identifier and literal escaping\n* with security validations to prevent injection and encoding issues.\n*/\n/**\n* Error thrown when an invalid SQL identifier or literal is detected.\n* Boundary layers map this to structured envelopes.\n*/\nvar SqlEscapeError = class extends Error {\n\tconstructor(message, value, kind) {\n\t\tsuper(message);\n\t\tthis.value = value;\n\t\tthis.kind = kind;\n\t\tthis.name = \"SqlEscapeError\";\n\t}\n};\n/**\n* Maximum length for PostgreSQL identifiers (NAMEDATALEN - 1).\n*/\nconst MAX_IDENTIFIER_LENGTH = 63;\n/**\n* Validates and quotes a PostgreSQL identifier (table, column, type, schema names).\n*\n* Security validations:\n* - Rejects null bytes which could cause truncation or unexpected behavior\n* - Rejects empty identifiers\n* - Warns on identifiers exceeding PostgreSQL's 63-character limit\n*\n* @throws {SqlEscapeError} If the identifier contains null bytes or is empty\n*/\nfunction quoteIdentifier(identifier) {\n\tif (identifier.length === 0) throw new SqlEscapeError(\"Identifier cannot be empty\", identifier, \"identifier\");\n\tif (identifier.includes(\"\\0\")) throw new SqlEscapeError(\"Identifier cannot contain null bytes\", identifier.replace(/\\0/g, \"\\\\0\"), \"identifier\");\n\tif (identifier.length > MAX_IDENTIFIER_LENGTH) console.warn(`Identifier \"${identifier.slice(0, 20)}...\" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character limit and will be truncated`);\n\treturn `\"${identifier.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n/**\n* Escapes a string literal for safe use in SQL statements.\n*\n* Security validations:\n* - Rejects null bytes which could cause truncation or unexpected behavior\n*\n* Note: This assumes PostgreSQL's `standard_conforming_strings` is ON (default since PG 9.1).\n* Backslashes are treated as literal characters, not escape sequences.\n*\n* @throws {SqlEscapeError} If the value contains null bytes\n*/\nfunction escapeLiteral(value) {\n\tif (value.includes(\"\\0\")) throw new SqlEscapeError(\"Literal value cannot contain null bytes\", value.replace(/\\0/g, \"\\\\0\"), \"literal\");\n\treturn value.replace(/'/g, \"''\");\n}\n/**\n* Builds a qualified name (schema.object) with proper quoting.\n*/\nfunction qualifyName(schemaName, objectName) {\n\treturn `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n/**\n* Validates that an enum value doesn't exceed PostgreSQL's label length limit.\n*\n* PostgreSQL enum labels have a maximum length of NAMEDATALEN-1 (63 bytes by default).\n* Unlike identifiers, enum labels that exceed this limit cause an error rather than\n* silent truncation.\n*\n* @param value - The enum value to validate\n* @param enumTypeName - Name of the enum type (for error messages)\n* @throws {SqlEscapeError} If the value exceeds the maximum length\n*/\nfunction validateEnumValueLength(value, enumTypeName) {\n\tif (value.length > MAX_IDENTIFIER_LENGTH) throw new SqlEscapeError(`Enum value \"${value.slice(0, 20)}...\" for type \"${enumTypeName}\" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character label limit`, value, \"literal\");\n}\n\n//#endregion\nexport { validateEnumValueLength as a, quoteIdentifier as i, escapeLiteral as n, qualifyName as r, SqlEscapeError as t };\n//# sourceMappingURL=sql-utils-CSfAGEwF.mjs.map","import { C as SQL_CHAR_CODEC_ID, E as SQL_VARCHAR_CODEC_ID, S as PG_VARCHAR_CODEC_ID, T as SQL_INT_CODEC_ID, _ as PG_TIMESTAMPTZ_CODEC_ID, a as PG_FLOAT4_CODEC_ID, b as PG_TIME_CODEC_ID, c as PG_INT2_CODEC_ID, d as PG_INTERVAL_CODEC_ID, f as PG_INT_CODEC_ID, g as PG_TEXT_CODEC_ID, h as PG_NUMERIC_CODEC_ID, i as PG_ENUM_CODEC_ID, l as PG_INT4_CODEC_ID, m as PG_JSON_CODEC_ID, n as PG_BOOL_CODEC_ID, o as PG_FLOAT8_CODEC_ID, p as PG_JSONB_CODEC_ID, r as PG_CHAR_CODEC_ID, s as PG_FLOAT_CODEC_ID, t as PG_BIT_CODEC_ID, u as PG_INT8_CODEC_ID, v as PG_TIMESTAMP_CODEC_ID, w as SQL_FLOAT_CODEC_ID, x as PG_VARBIT_CODEC_ID, y as PG_TIMETZ_CODEC_ID } from \"./codec-ids-Bsm9c7ns.mjs\";\nimport { a as validateEnumValueLength, i as quoteIdentifier, n as escapeLiteral, r as qualifyName } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { arraysEqual } from \"@prisma-next/family-sql/schema-verify\";\n\n//#region src/core/enum-control-hooks.ts\nconst ENUM_INTROSPECT_QUERY = `\n SELECT\n n.nspname AS schema_name,\n t.typname AS type_name,\n array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n JOIN pg_enum e ON t.oid = e.enumtypid\n WHERE n.nspname = $1\n GROUP BY n.nspname, t.typname\n ORDER BY n.nspname, t.typname\n`;\n/**\n* Type guard for string arrays. Used for runtime validation of introspected data.\n*/\nfunction isStringArray(value) {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n/**\n* Parses a PostgreSQL array value into a JavaScript string array.\n*\n* PostgreSQL's `pg` library may return `array_agg` results either as:\n* - A JavaScript array (when type parsers are configured)\n* - A string in PostgreSQL array literal format: `{value1,value2,...}`\n*\n* Handles PostgreSQL's quoting rules for array elements:\n* - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted\n* - Inside quoted elements, `\\\"` represents `\"` and `\\\\` represents `\\`\n*\n* @param value - The value to parse (array or PostgreSQL array string)\n* @returns A string array, or null if the value cannot be parsed\n*/\nfunction parsePostgresArray(value) {\n\tif (isStringArray(value)) return value;\n\tif (typeof value === \"string\" && value.startsWith(\"{\") && value.endsWith(\"}\")) {\n\t\tconst inner = value.slice(1, -1);\n\t\tif (inner === \"\") return [];\n\t\treturn parseArrayElements(inner);\n\t}\n\treturn null;\n}\nfunction parseArrayElements(input) {\n\tconst result = [];\n\tlet i = 0;\n\twhile (i < input.length) {\n\t\tif (input[i] === \",\") {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (input[i] === \"\\\"\") {\n\t\t\ti++;\n\t\t\tlet element = \"\";\n\t\t\twhile (i < input.length && input[i] !== \"\\\"\") {\n\t\t\t\tif (input[i] === \"\\\\\" && i + 1 < input.length) {\n\t\t\t\t\ti++;\n\t\t\t\t\telement += input[i];\n\t\t\t\t} else element += input[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tresult.push(element);\n\t\t} else {\n\t\t\tconst nextComma = input.indexOf(\",\", i);\n\t\t\tif (nextComma === -1) {\n\t\t\t\tresult.push(input.slice(i).trim());\n\t\t\t\ti = input.length;\n\t\t\t} else {\n\t\t\t\tresult.push(input.slice(i, nextComma).trim());\n\t\t\t\ti = nextComma;\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n/**\n* Extracts enum values from a StorageTypeInstance.\n* Returns null if values are missing or invalid.\n*/\nfunction getEnumValues(typeInstance) {\n\tconst values = typeInstance.typeParams?.[\"values\"];\n\treturn isStringArray(values) ? values : null;\n}\n/**\n* Reads existing enum values from the schema IR for a given native type.\n* Uses optional chaining to simplify navigation through the annotations structure.\n*/\nfunction readExistingEnumValues(schema, nativeType) {\n\tconst existing = ((schema.annotations?.[\"pg\"])?.[\"storageTypes\"])?.[nativeType];\n\tif (!existing || existing.codecId !== PG_ENUM_CODEC_ID) return null;\n\treturn getEnumValues(existing);\n}\n/**\n* Determines what changes are needed to transform existing enum values to desired values.\n*\n* Returns one of:\n* - `unchanged`: No changes needed, values match exactly\n* - `add_values`: New values can be safely appended (PostgreSQL supports this)\n* - `rebuild`: Full enum rebuild required (value removal, reordering, or both)\n*\n* Note: PostgreSQL enums can only have values added (not removed or reordered) without\n* a full type rebuild involving temp type creation and column migration.\n*\n* @param existing - Current enum values in the database\n* @param desired - Target enum values from the contract\n* @returns The type of change required\n*/\nfunction determineEnumDiff(existing, desired) {\n\tif (arraysEqual(existing, desired)) return { kind: \"unchanged\" };\n\tconst existingSet = new Set(existing);\n\tconst desiredSet = new Set(desired);\n\tconst missingValues = desired.filter((value) => !existingSet.has(value));\n\tconst removedValues = existing.filter((value) => !desiredSet.has(value));\n\tconst orderMismatch = missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);\n\tif (removedValues.length > 0 || orderMismatch) return {\n\t\tkind: \"rebuild\",\n\t\tremovedValues\n\t};\n\treturn {\n\t\tkind: \"add_values\",\n\t\tvalues: missingValues\n\t};\n}\nfunction enumTypeExistsCheck(schemaName, typeName, exists = true) {\n\treturn `SELECT ${exists ? \"EXISTS\" : \"NOT EXISTS\"} (\n SELECT 1\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = '${escapeLiteral(schemaName)}'\n AND t.typname = '${escapeLiteral(typeName)}'\n)`;\n}\nfunction buildCreateEnumOperation(typeName, nativeType, schemaName, values) {\n\tfor (const value of values) validateEnumValueLength(value, typeName);\n\tconst literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst qualifiedType = qualifyName(schemaName, nativeType);\n\treturn {\n\t\tid: `type.${typeName}`,\n\t\tlabel: `Create type ${typeName}`,\n\t\tsummary: `Creates enum type ${typeName}`,\n\t\toperationClass: \"additive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${nativeType}\" does not exist`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType, false)\n\t\t}],\n\t\texecute: [{\n\t\t\tdescription: `create type \"${nativeType}\"`,\n\t\t\tsql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`\n\t\t}],\n\t\tpostcheck: [{\n\t\t\tdescription: `verify type \"${nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType)\n\t\t}]\n\t};\n}\n/**\n* Computes the optimal position for inserting a new enum value to maintain\n* the desired order relative to existing values.\n*\n* PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.\n* This function finds the best reference value by:\n* 1. Looking for the nearest preceding value that already exists\n* 2. Falling back to the nearest following value if no preceding exists\n* 3. Defaulting to end-of-list if no reference is found\n*\n* @param options.desired - The target ordered list of all enum values\n* @param options.desiredIndex - Index of the value being inserted in the desired list\n* @param options.current - Current list of enum values (being built up incrementally)\n* @returns SQL clause (e.g., \" AFTER 'x'\") and insert position for tracking\n*/\nfunction computeInsertPosition(options) {\n\tconst { desired, desiredIndex, current } = options;\n\tconst currentSet = new Set(current);\n\tconst previous = desired.slice(0, desiredIndex).reverse().find((candidate) => currentSet.has(candidate));\n\tconst next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));\n\treturn {\n\t\tclause: previous ? ` AFTER '${escapeLiteral(previous)}'` : next ? ` BEFORE '${escapeLiteral(next)}'` : \"\",\n\t\tinsertAt: previous ? current.indexOf(previous) + 1 : next ? current.indexOf(next) : current.length\n\t};\n}\n/**\n* Builds operations to add new enum values to an existing PostgreSQL enum type.\n*\n* Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.\n* Values are inserted in the correct order using BEFORE/AFTER positioning to match\n* the desired final order.\n*\n* This is a safe, non-destructive operation - existing data is not affected.\n*\n* @param options.typeName - Contract-level type name (e.g., 'Role')\n* @param options.nativeType - PostgreSQL type name (e.g., 'role')\n* @param options.schemaName - PostgreSQL schema (e.g., 'public')\n* @param options.desired - Target ordered list of all enum values\n* @param options.existing - Current enum values in the database\n* @returns Array of migration operations to add each missing value\n*/\nfunction buildAddValueOperations(options) {\n\tconst { typeName, nativeType, schemaName } = options;\n\tconst current = [...options.existing];\n\tconst currentSet = new Set(current);\n\tconst operations = [];\n\tfor (let index = 0; index < options.desired.length; index += 1) {\n\t\tconst value = options.desired[index];\n\t\tif (value === void 0) continue;\n\t\tif (currentSet.has(value)) continue;\n\t\tvalidateEnumValueLength(value, typeName);\n\t\tconst { clause, insertAt } = computeInsertPosition({\n\t\t\tdesired: options.desired,\n\t\t\tdesiredIndex: index,\n\t\t\tcurrent\n\t\t});\n\t\toperations.push({\n\t\t\tid: `type.${typeName}.value.${value}`,\n\t\t\tlabel: `Add value ${value} to ${typeName}`,\n\t\t\tsummary: `Adds enum value ${value} to ${typeName}`,\n\t\t\toperationClass: \"widening\",\n\t\t\ttarget: { id: \"postgres\" },\n\t\t\tprecheck: [],\n\t\t\texecute: [{\n\t\t\t\tdescription: `add value \"${value}\" if not exists`,\n\t\t\t\tsql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(value)}'${clause}`\n\t\t\t}],\n\t\t\tpostcheck: []\n\t\t});\n\t\tcurrent.splice(insertAt, 0, value);\n\t\tcurrentSet.add(value);\n\t}\n\treturn operations;\n}\n/**\n* Collects columns using the enum type from the contract (desired state).\n* Used for type-safe reference tracking.\n*/\nfunction collectEnumColumnsFromContract(contract, typeName, nativeType) {\n\tconst columns = [];\n\tfor (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeRef === typeName || column.nativeType === nativeType && column.codecId === PG_ENUM_CODEC_ID) columns.push({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects columns using the enum type from the schema IR (live database state).\n* This ensures we find ALL dependent columns, including those added outside the contract\n* (e.g., manual DDL), which is critical for safe enum rebuild operations.\n*/\nfunction collectEnumColumnsFromSchema(schema, nativeType) {\n\tconst columns = [];\n\tfor (const [tableName, table] of Object.entries(schema.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.nativeType === nativeType) columns.push({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects all columns using the enum type from both contract AND live database.\n* Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.\n*\n* This is critical for data integrity: if a column exists in the database using\n* this enum but is not in the contract (e.g., added via manual DDL), we must\n* still migrate it to avoid DROP TYPE failures.\n*/\nfunction collectAllEnumColumns(contract, schema, typeName, nativeType) {\n\tconst contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);\n\tconst schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst result = [];\n\tfor (const col of [...contractColumns, ...schemaColumns]) {\n\t\tconst key = `${col.table}.${col.column}`;\n\t\tif (!seen.has(key)) {\n\t\t\tseen.add(key);\n\t\t\tresult.push(col);\n\t\t}\n\t}\n\treturn result.sort((a, b) => {\n\t\tconst tableCompare = a.table.localeCompare(b.table);\n\t\treturn tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);\n\t});\n}\n/**\n* Builds a SQL check to verify a column's type matches an expected type.\n*/\nfunction columnTypeCheck(options) {\n\treturn `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(options.schemaName)}'\n AND table_name = '${escapeLiteral(options.tableName)}'\n AND column_name = '${escapeLiteral(options.columnName)}'\n AND udt_name = '${escapeLiteral(options.expectedType)}'\n)`;\n}\n/** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */\nconst MAX_IDENTIFIER_LENGTH = 63;\n/** Suffix added to enum type names during rebuild operations */\nconst REBUILD_SUFFIX = \"__pn_rebuild\";\n/**\n* Builds an SQL check to verify no rows contain any of the removed enum values.\n* This prevents data loss during enum rebuild operations.\n*\n* @param schemaName - PostgreSQL schema name\n* @param tableName - Table containing the enum column\n* @param columnName - Column using the enum type\n* @param removedValues - Array of enum values being removed\n* @returns SQL query that returns true if no rows contain removed values\n*/\nfunction noRemovedValuesExistCheck(schemaName, tableName, columnName, removedValues) {\n\tif (removedValues.length === 0) return \"SELECT true\";\n\tconst valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(\", \");\n\treturn `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualifyName(schemaName, tableName)}\n WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})\n LIMIT 1\n)`;\n}\n/**\n* Builds a migration operation to recreate a PostgreSQL enum type with updated values.\n*\n* This is required when:\n* - Enum values are removed (PostgreSQL doesn't support direct removal)\n* - Enum values are reordered (PostgreSQL doesn't support reordering)\n*\n* The operation:\n* 1. Creates a new enum type with the desired values (temp name)\n* 2. Migrates all columns to use the new type via text cast\n* 3. Drops the original type\n* 4. Renames the temp type to the original name\n*\n* IMPORTANT: If values are being removed and data exists using those values,\n* the operation will fail at the precheck stage with a clear error message.\n* This prevents silent data loss.\n*\n* @param options.typeName - Contract-level type name\n* @param options.nativeType - PostgreSQL type name\n* @param options.schemaName - PostgreSQL schema\n* @param options.values - Desired final enum values\n* @param options.removedValues - Values being removed (for data loss checks)\n* @param options.contract - Full contract for column discovery\n* @param options.schema - Current schema IR for column discovery\n* @returns Migration operation for full enum rebuild\n*/\nfunction buildRecreateEnumOperation(options) {\n\tconst tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;\n\tif (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {\n\t\tconst maxBaseLength = MAX_IDENTIFIER_LENGTH - 12;\n\t\tthrow new Error(`Enum type name \"${options.nativeType}\" is too long for rebuild operation. Maximum length is ${maxBaseLength} characters (type name + \"${REBUILD_SUFFIX}\" suffix must fit within PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character identifier limit).`);\n\t}\n\tconst qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);\n\tconst qualifiedTemp = qualifyName(options.schemaName, tempTypeName);\n\tconst literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst columnRefs = collectAllEnumColumns(options.contract, options.schema, options.typeName, options.nativeType);\n\tconst alterColumns = columnRefs.map((ref) => ({\n\t\tdescription: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,\n\t\tsql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}\nALTER COLUMN ${quoteIdentifier(ref.column)}\nTYPE ${qualifiedTemp}\nUSING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`\n\t}));\n\tconst postchecks = [\n\t\t{\n\t\t\tdescription: `verify type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t},\n\t\t{\n\t\t\tdescription: `verify temp type \"${tempTypeName}\" was removed`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, tempTypeName, false)\n\t\t},\n\t\t...columnRefs.map((ref) => ({\n\t\t\tdescription: `verify ${ref.table}.${ref.column} uses type \"${options.nativeType}\"`,\n\t\t\tsql: columnTypeCheck({\n\t\t\t\tschemaName: options.schemaName,\n\t\t\t\ttableName: ref.table,\n\t\t\t\tcolumnName: ref.column,\n\t\t\t\texpectedType: options.nativeType\n\t\t\t})\n\t\t}))\n\t];\n\treturn {\n\t\tid: `type.${options.typeName}.rebuild`,\n\t\tlabel: `Rebuild type ${options.typeName}`,\n\t\tsummary: `Recreates enum type ${options.typeName} with updated values`,\n\t\toperationClass: \"destructive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t}, ...options.removedValues.length > 0 ? columnRefs.map((ref) => ({\n\t\t\tdescription: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(\", \")})`,\n\t\t\tsql: noRemovedValuesExistCheck(options.schemaName, ref.table, ref.column, options.removedValues)\n\t\t})) : []],\n\t\texecute: [\n\t\t\t{\n\t\t\t\tdescription: `drop orphaned temp type \"${tempTypeName}\" if exists`,\n\t\t\t\tsql: `DROP TYPE IF EXISTS ${qualifiedTemp}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `create temp type \"${tempTypeName}\"`,\n\t\t\t\tsql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`\n\t\t\t},\n\t\t\t...alterColumns,\n\t\t\t{\n\t\t\t\tdescription: `drop type \"${options.nativeType}\"`,\n\t\t\t\tsql: `DROP TYPE ${qualifiedOriginal}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `rename type \"${tempTypeName}\" to \"${options.nativeType}\"`,\n\t\t\t\tsql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`\n\t\t\t}\n\t\t],\n\t\tpostcheck: postchecks\n\t};\n}\n/**\n* Postgres enum hooks for planning, verifying, and introspecting `storage.types`.\n*/\nconst pgEnumControlHooks = {\n\tplanTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired || desired.length === 0) return { operations: [] };\n\t\tconst schemaNamespace = schemaName ?? \"public\";\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return { operations: [buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired)] };\n\t\tconst diff = determineEnumDiff(existing, desired);\n\t\tif (diff.kind === \"unchanged\") return { operations: [] };\n\t\tif (diff.kind === \"rebuild\") return { operations: [buildRecreateEnumOperation({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tvalues: desired,\n\t\t\tremovedValues: diff.removedValues,\n\t\t\tcontract,\n\t\t\tschema\n\t\t})] };\n\t\treturn { operations: buildAddValueOperations({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tdesired,\n\t\t\texisting\n\t\t}) };\n\t},\n\tverifyType: ({ typeName, typeInstance, schema }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired) return [];\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return [{\n\t\t\tkind: \"type_missing\",\n\t\t\ttable: \"\",\n\t\t\ttypeName,\n\t\t\tmessage: `Type \"${typeName}\" is missing from database`\n\t\t}];\n\t\tif (!arraysEqual(existing, desired)) return [{\n\t\t\tkind: \"type_values_mismatch\",\n\t\t\ttable: \"\",\n\t\t\ttypeName,\n\t\t\texpected: desired.join(\", \"),\n\t\t\tactual: existing.join(\", \"),\n\t\t\tmessage: `Type \"${typeName}\" values do not match contract`\n\t\t}];\n\t\treturn [];\n\t},\n\tintrospectTypes: async ({ driver, schemaName }) => {\n\t\tconst namespace = schemaName ?? \"public\";\n\t\tconst result = await driver.query(ENUM_INTROSPECT_QUERY, [namespace]);\n\t\tconst types = {};\n\t\tfor (const row of result.rows) {\n\t\t\tconst values = parsePostgresArray(row.values);\n\t\t\tif (!values) throw new Error(`Failed to parse enum values for type \"${row.type_name}\": unexpected format: ${JSON.stringify(row.values)}`);\n\t\t\ttypes[row.type_name] = {\n\t\t\t\tcodecId: PG_ENUM_CODEC_ID,\n\t\t\t\tnativeType: row.type_name,\n\t\t\t\ttypeParams: { values }\n\t\t\t};\n\t\t}\n\t\treturn types;\n\t}\n};\n\n//#endregion\n//#region src/core/json-schema-type-expression.ts\nconst MAX_DEPTH = 32;\nfunction isRecord(value) {\n\treturn typeof value === \"object\" && value !== null;\n}\nfunction escapeStringLiteral(str) {\n\treturn str.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\").replace(/\\n/g, \"\\\\n\").replace(/\\r/g, \"\\\\r\");\n}\nfunction quotePropertyKey(key) {\n\treturn /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;\n}\nfunction renderLiteral(value) {\n\tif (typeof value === \"string\") return `'${escapeStringLiteral(value)}'`;\n\tif (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\tif (value === null) return \"null\";\n\treturn \"unknown\";\n}\nfunction renderUnion(items, depth) {\n\treturn items.map((item) => render(item, depth)).join(\" | \");\n}\nfunction renderObjectType(schema, depth) {\n\tconst properties = isRecord(schema[\"properties\"]) ? schema[\"properties\"] : {};\n\tconst required = Array.isArray(schema[\"required\"]) ? new Set(schema[\"required\"].filter((key) => typeof key === \"string\")) : /* @__PURE__ */ new Set();\n\tconst keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));\n\tif (keys.length === 0) {\n\t\tconst additionalProperties = schema[\"additionalProperties\"];\n\t\tif (additionalProperties === true || additionalProperties === void 0) return \"Record<string, unknown>\";\n\t\treturn `Record<string, ${render(additionalProperties, depth)}>`;\n\t}\n\treturn `{ ${keys.map((key) => {\n\t\tconst valueSchema = properties[key];\n\t\tconst optionalMarker = required.has(key) ? \"\" : \"?\";\n\t\treturn `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;\n\t}).join(\"; \")} }`;\n}\nfunction renderArrayType(schema, depth) {\n\tif (Array.isArray(schema[\"items\"])) return `readonly [${schema[\"items\"].map((item) => render(item, depth)).join(\", \")}]`;\n\tif (schema[\"items\"] !== void 0) {\n\t\tconst itemType = render(schema[\"items\"], depth);\n\t\treturn itemType.includes(\" | \") || itemType.includes(\" & \") ? `(${itemType})[]` : `${itemType}[]`;\n\t}\n\treturn \"unknown[]\";\n}\nfunction render(schema, depth) {\n\tif (depth > MAX_DEPTH || !isRecord(schema)) return \"JsonValue\";\n\tconst nextDepth = depth + 1;\n\tif (\"const\" in schema) return renderLiteral(schema[\"const\"]);\n\tif (Array.isArray(schema[\"enum\"])) return schema[\"enum\"].map((value) => renderLiteral(value)).join(\" | \");\n\tif (Array.isArray(schema[\"oneOf\"])) return renderUnion(schema[\"oneOf\"], nextDepth);\n\tif (Array.isArray(schema[\"anyOf\"])) return renderUnion(schema[\"anyOf\"], nextDepth);\n\tif (Array.isArray(schema[\"allOf\"])) return schema[\"allOf\"].map((item) => render(item, nextDepth)).join(\" & \");\n\tif (Array.isArray(schema[\"type\"])) return schema[\"type\"].map((item) => render({\n\t\t...schema,\n\t\ttype: item\n\t}, nextDepth)).join(\" | \");\n\tswitch (schema[\"type\"]) {\n\t\tcase \"string\": return \"string\";\n\t\tcase \"number\":\n\t\tcase \"integer\": return \"number\";\n\t\tcase \"boolean\": return \"boolean\";\n\t\tcase \"null\": return \"null\";\n\t\tcase \"array\": return renderArrayType(schema, nextDepth);\n\t\tcase \"object\": return renderObjectType(schema, nextDepth);\n\t\tdefault: break;\n\t}\n\treturn \"JsonValue\";\n}\nfunction renderTypeScriptTypeFromJsonSchema(schema) {\n\treturn render(schema, 0);\n}\n\n//#endregion\n//#region src/core/parameterized-types.ts\n/**\n* Shared utility for expanding parameterized Postgres types to their full SQL representation.\n*\n* This module provides a single source of truth for type expansion logic, used by:\n* - Schema verification (verify-sql-schema.ts) via the expandNativeType codec control hook\n* - Migration planner (planner.ts) via direct import\n*\n* @module\n*/\n/** Set of codec IDs that use the 'length' parameter */\nconst LENGTH_CODEC_IDS = new Set([\n\tSQL_CHAR_CODEC_ID,\n\tSQL_VARCHAR_CODEC_ID,\n\tPG_CHAR_CODEC_ID,\n\tPG_VARCHAR_CODEC_ID,\n\tPG_BIT_CODEC_ID,\n\tPG_VARBIT_CODEC_ID\n]);\n/** Set of codec IDs that use the 'precision' parameter for temporal types */\nconst TEMPORAL_PRECISION_CODEC_IDS = new Set([\n\tPG_TIMESTAMP_CODEC_ID,\n\tPG_TIMESTAMPTZ_CODEC_ID,\n\tPG_TIME_CODEC_ID,\n\tPG_TIMETZ_CODEC_ID,\n\tPG_INTERVAL_CODEC_ID\n]);\n/**\n* Validates that a value is a valid type parameter number.\n* Type parameters must be finite, non-negative integers.\n*/\nfunction isValidTypeParamNumber(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\n/**\n* Expands a parameterized native type to its full SQL representation.\n*\n* For example:\n* - { nativeType: 'character varying', typeParams: { length: 255 } } -> 'character varying(255)'\n* - { nativeType: 'numeric', typeParams: { precision: 10, scale: 2 } } -> 'numeric(10,2)'\n* - { nativeType: 'timestamp without time zone', typeParams: { precision: 3 } } -> 'timestamp without time zone(3)'\n*\n* Returns the original nativeType if:\n* - No typeParams are provided\n* - No codecId is provided\n* - The codecId is not a known parameterized type\n* - The typeParams values are invalid\n*/\nfunction expandParameterizedNativeType(input) {\n\tconst { nativeType, codecId, typeParams } = input;\n\tif (!typeParams || !codecId) return nativeType;\n\tif (LENGTH_CODEC_IDS.has(codecId)) {\n\t\tconst length = typeParams[\"length\"];\n\t\tif (isValidTypeParamNumber(length)) return `${nativeType}(${length})`;\n\t\treturn nativeType;\n\t}\n\tif (codecId === PG_NUMERIC_CODEC_ID) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tconst scale = typeParams[\"scale\"];\n\t\tif (isValidTypeParamNumber(precision)) {\n\t\t\tif (isValidTypeParamNumber(scale)) return `${nativeType}(${precision},${scale})`;\n\t\t\treturn `${nativeType}(${precision})`;\n\t\t}\n\t\treturn nativeType;\n\t}\n\tif (TEMPORAL_PRECISION_CODEC_IDS.has(codecId)) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (isValidTypeParamNumber(precision)) return `${nativeType}(${precision})`;\n\t\treturn nativeType;\n\t}\n\treturn nativeType;\n}\n\n//#endregion\n//#region src/core/descriptor-meta.ts\n/** Creates a type import spec for codec types */\nconst codecTypeImport = (named) => ({\n\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\tnamed,\n\talias: named\n});\n/** Creates a precision-based TypeScript type renderer for temporal types */\nconst precisionRenderer = (typeName) => ({\n\tkind: \"function\",\n\trender: (params) => {\n\t\tconst precision = params[\"precision\"];\n\t\treturn typeof precision === \"number\" ? `${typeName}<${precision}>` : typeName;\n\t}\n});\n/** Creates control hooks with just expandNativeType for parameterized types */\nconst parameterizedTypeHooks = { expandNativeType: expandParameterizedNativeType };\n/**\n* Validates that a type expression string is safe to embed in generated .d.ts files.\n* Rejects expressions containing patterns that could inject executable code.\n*/\nfunction isSafeTypeExpression(expr) {\n\treturn !/import\\s*\\(|require\\s*\\(|declare\\s|export\\s|eval\\s*\\(/.test(expr);\n}\nfunction renderJsonTypeExpression(params) {\n\tconst typeName = params[\"type\"];\n\tif (typeof typeName === \"string\" && typeName.trim().length > 0) {\n\t\tconst trimmed = typeName.trim();\n\t\tif (!isSafeTypeExpression(trimmed)) return \"JsonValue\";\n\t\treturn trimmed;\n\t}\n\tconst schema = params[\"schemaJson\"];\n\tif (schema && typeof schema === \"object\") {\n\t\tconst rendered = renderTypeScriptTypeFromJsonSchema(schema);\n\t\tif (!isSafeTypeExpression(rendered)) return \"JsonValue\";\n\t\treturn rendered;\n\t}\n\treturn \"JsonValue\";\n}\nconst postgresAdapterDescriptorMeta = {\n\tkind: \"adapter\",\n\tfamilyId: \"sql\",\n\ttargetId: \"postgres\",\n\tid: \"postgres\",\n\tversion: \"0.0.1\",\n\tcapabilities: {\n\t\tpostgres: {\n\t\t\torderBy: true,\n\t\t\tlimit: true,\n\t\t\tlateral: true,\n\t\t\tjsonAgg: true,\n\t\t\treturning: true\n\t\t},\n\t\tsql: { enums: true }\n\t},\n\ttypes: {\n\t\tcodecTypes: {\n\t\t\timport: {\n\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\tnamed: \"CodecTypes\",\n\t\t\t\talias: \"PgTypes\"\n\t\t\t},\n\t\t\tparameterized: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: \"Char<{{length}}>\",\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: \"Varchar<{{length}}>\",\n\t\t\t\t[PG_CHAR_CODEC_ID]: \"Char<{{length}}>\",\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: \"Varchar<{{length}}>\",\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: (params) => {\n\t\t\t\t\t\tconst precision = params[\"precision\"];\n\t\t\t\t\t\tif (typeof precision !== \"number\") throw new Error(\"pg/numeric@1 renderer expects precision\");\n\t\t\t\t\t\tconst scale = params[\"scale\"];\n\t\t\t\t\t\treturn typeof scale === \"number\" ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t[PG_BIT_CODEC_ID]: \"Bit<{{length}}>\",\n\t\t\t\t[PG_VARBIT_CODEC_ID]: \"VarBit<{{length}}>\",\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: precisionRenderer(\"Timestamp\"),\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: precisionRenderer(\"Timestamptz\"),\n\t\t\t\t[PG_TIME_CODEC_ID]: precisionRenderer(\"Time\"),\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: precisionRenderer(\"Timetz\"),\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: precisionRenderer(\"Interval\"),\n\t\t\t\t[PG_ENUM_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: (params) => {\n\t\t\t\t\t\tconst values = params[\"values\"];\n\t\t\t\t\t\tif (!Array.isArray(values)) throw new Error(\"pg/enum@1 renderer expects values array\");\n\t\t\t\t\t\treturn values.map((value) => `'${String(value).replace(/'/g, \"\\\\'\")}'`).join(\" | \");\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t[PG_JSON_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: renderJsonTypeExpression\n\t\t\t\t},\n\t\t\t\t[PG_JSONB_CODEC_ID]: {\n\t\t\t\t\tkind: \"function\",\n\t\t\t\t\trender: renderJsonTypeExpression\n\t\t\t\t}\n\t\t\t},\n\t\t\ttypeImports: [\n\t\t\t\t{\n\t\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\t\tnamed: \"JsonValue\",\n\t\t\t\t\talias: \"JsonValue\"\n\t\t\t\t},\n\t\t\t\tcodecTypeImport(\"Char\"),\n\t\t\t\tcodecTypeImport(\"Varchar\"),\n\t\t\t\tcodecTypeImport(\"Numeric\"),\n\t\t\t\tcodecTypeImport(\"Bit\"),\n\t\t\t\tcodecTypeImport(\"VarBit\"),\n\t\t\t\tcodecTypeImport(\"Timestamp\"),\n\t\t\t\tcodecTypeImport(\"Timestamptz\"),\n\t\t\t\tcodecTypeImport(\"Time\"),\n\t\t\t\tcodecTypeImport(\"Timetz\"),\n\t\t\t\tcodecTypeImport(\"Interval\")\n\t\t\t],\n\t\t\tcontrolPlaneHooks: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_CHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_BIT_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_VARBIT_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIME_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: parameterizedTypeHooks,\n\t\t\t\t[PG_ENUM_CODEC_ID]: pgEnumControlHooks\n\t\t\t}\n\t\t},\n\t\tstorage: [\n\t\t\t{\n\t\t\t\ttypeId: PG_TEXT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"text\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT2_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int2\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_NUMERIC_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"numeric\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMP_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamp\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMPTZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamptz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIME_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"time\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMETZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timetz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BOOL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bool\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARBIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INTERVAL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"interval\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSON_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"json\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSONB_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"jsonb\"\n\t\t\t}\n\t\t]\n\t}\n};\n\n//#endregion\nexport { expandParameterizedNativeType as n, pgEnumControlHooks as r, postgresAdapterDescriptorMeta as t };\n//# sourceMappingURL=descriptor-meta-ilnFI7bx.mjs.map","import \"./codec-ids-Bsm9c7ns.mjs\";\nimport { i as quoteIdentifier, n as escapeLiteral, r as qualifyName, t as SqlEscapeError } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { n as expandParameterizedNativeType, r as pgEnumControlHooks, t as postgresAdapterDescriptorMeta } from \"./descriptor-meta-ilnFI7bx.mjs\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/core/default-normalizer.ts\n/**\n* Pre-compiled regex patterns for performance.\n* These are compiled once at module load time rather than on each function call.\n*/\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst TIMESTAMP_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP|clock_timestamp\\s*\\(\\s*\\))$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n/**\n* Parses a raw Postgres column default expression into a normalized ColumnDefault.\n* This enables semantic comparison between contract defaults and introspected schema defaults.\n*\n* Used by the migration diff layer to normalize raw database defaults during comparison,\n* keeping the introspection layer focused on faithful data capture.\n*\n* @param rawDefault - Raw default expression from information_schema.columns.column_default\n* @param _nativeType - Native column type (currently unused, reserved for future type-aware parsing)\n* @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n*/\nfunction parsePostgresDefault(rawDefault, _nativeType) {\n\tconst trimmed = rawDefault.trim();\n\tconst normalizedType = _nativeType?.toLowerCase();\n\tconst isBigInt = normalizedType === \"bigint\" || normalizedType === \"int8\";\n\tif (NEXTVAL_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"autoincrement()\"\n\t};\n\tif (TIMESTAMP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"now()\"\n\t};\n\tif (UUID_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (UUID_OSSP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (TRUE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: true\n\t};\n\tif (FALSE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: false\n\t};\n\tif (NUMERIC_PATTERN.test(trimmed)) {\n\t\tif (isBigInt) return {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: {\n\t\t\t\t$type: \"bigint\",\n\t\t\t\tvalue: trimmed\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: Number(trimmed)\n\t\t};\n\t}\n\tconst stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n\tif (stringMatch?.[1] !== void 0) {\n\t\tconst unescaped = stringMatch[1].replace(/''/g, \"'\");\n\t\tif (normalizedType === \"json\" || normalizedType === \"jsonb\") try {\n\t\t\treturn {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: JSON.parse(unescaped)\n\t\t\t};\n\t\t} catch {}\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: unescaped\n\t\t};\n\t}\n\treturn {\n\t\tkind: \"function\",\n\t\texpression: trimmed\n\t};\n}\n\n//#endregion\n//#region src/core/control-adapter.ts\n/**\n* Postgres control plane adapter for control-plane operations like introspection.\n* Provides target-specific implementations for control-plane domain actions.\n*/\nvar PostgresControlAdapter = class {\n\tfamilyId = \"sql\";\n\ttargetId = \"postgres\";\n\t/**\n\t* @deprecated Use targetId instead\n\t*/\n\ttarget = \"postgres\";\n\t/**\n\t* Target-specific normalizer for raw Postgres default expressions.\n\t* Used by schema verification to normalize raw defaults before comparison.\n\t*/\n\tnormalizeDefault = parsePostgresDefault;\n\t/**\n\t* Target-specific normalizer for Postgres schema native type names.\n\t* Used by schema verification to normalize introspected type names\n\t* before comparison with contract native types.\n\t*/\n\tnormalizeNativeType = normalizeSchemaNativeType;\n\t/**\n\t* Introspects a Postgres database schema and returns a raw SqlSchemaIR.\n\t*\n\t* This is a pure schema discovery operation that queries the Postgres catalog\n\t* and returns the schema structure without type mapping or contract enrichment.\n\t* Type mapping and enrichment are handled separately by enrichment helpers.\n\t*\n\t* Uses batched queries to minimize database round trips (7 queries instead of 5T+3).\n\t*\n\t* @param driver - ControlDriverInstance<'sql', 'postgres'> instance for executing queries\n\t* @param contractIR - Optional contract IR for contract-guided introspection (filtering, optimization)\n\t* @param schema - Schema name to introspect (defaults to 'public')\n\t* @returns Promise resolving to SqlSchemaIR representing the live database schema\n\t*/\n\tasync introspect(driver, _contractIR, schema = \"public\") {\n\t\tconst [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult, extensionsResult] = await Promise.all([\n\t\t\tdriver.query(`SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`, [schema]),\n\t\t\tdriver.query(`SELECT\n c.table_name,\n column_name,\n data_type,\n udt_name,\n is_nullable,\n character_maximum_length,\n numeric_precision,\n numeric_scale,\n column_default,\n format_type(a.atttypid, a.atttypmod) AS formatted_type\n FROM information_schema.columns c\n JOIN pg_catalog.pg_class cl\n ON cl.relname = c.table_name\n JOIN pg_catalog.pg_namespace ns\n ON ns.nspname = c.table_schema\n AND ns.oid = cl.relnamespace\n JOIN pg_catalog.pg_attribute a\n ON a.attrelid = cl.oid\n AND a.attname = c.column_name\n AND a.attnum > 0\n AND NOT a.attisdropped\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\n ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position,\n ref_ns.nspname AS referenced_table_schema,\n ref_cl.relname AS referenced_table_name,\n ref_att.attname AS referenced_column_name,\n rc.delete_rule,\n rc.update_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n JOIN pg_catalog.pg_constraint pgc\n ON pgc.conname = tc.constraint_name\n AND pgc.connamespace = (\n SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema\n )\n JOIN pg_catalog.pg_class ref_cl\n ON ref_cl.oid = pgc.confrelid\n JOIN pg_catalog.pg_namespace ref_ns\n ON ref_ns.oid = ref_cl.relnamespace\n JOIN pg_catalog.pg_attribute ref_att\n ON ref_att.attrelid = pgc.confrelid\n AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]\n JOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n i.tablename,\n i.indexname,\n ix.indisunique,\n a.attname,\n a.attnum\n FROM pg_indexes i\n JOIN pg_class ic ON ic.relname = i.indexname\n JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1\n JOIN pg_index ix ON ix.indexrelid = ic.oid\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0\n WHERE i.schemaname = $1\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.table_constraints tc\n WHERE tc.table_schema = $1\n AND tc.table_name = i.tablename\n AND tc.constraint_name = i.indexname\n )\n ORDER BY i.tablename, i.indexname, a.attnum`, [schema]),\n\t\t\tdriver.query(`SELECT extname\n FROM pg_extension\n ORDER BY extname`, [])\n\t\t]);\n\t\tconst columnsByTable = groupBy(columnsResult.rows, \"table_name\");\n\t\tconst pksByTable = groupBy(pkResult.rows, \"table_name\");\n\t\tconst fksByTable = groupBy(fkResult.rows, \"table_name\");\n\t\tconst uniquesByTable = groupBy(uniqueResult.rows, \"table_name\");\n\t\tconst indexesByTable = groupBy(indexResult.rows, \"tablename\");\n\t\tconst pkConstraintsByTable = /* @__PURE__ */ new Map();\n\t\tfor (const row of pkResult.rows) {\n\t\t\tlet constraints = pkConstraintsByTable.get(row.table_name);\n\t\t\tif (!constraints) {\n\t\t\t\tconstraints = /* @__PURE__ */ new Set();\n\t\t\t\tpkConstraintsByTable.set(row.table_name, constraints);\n\t\t\t}\n\t\t\tconstraints.add(row.constraint_name);\n\t\t}\n\t\tconst tables = {};\n\t\tfor (const tableRow of tablesResult.rows) {\n\t\t\tconst tableName = tableRow.table_name;\n\t\t\tconst columns = {};\n\t\t\tfor (const colRow of columnsByTable.get(tableName) ?? []) {\n\t\t\t\tlet nativeType = colRow.udt_name;\n\t\t\t\tconst formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;\n\t\t\t\tif (formattedType) nativeType = formattedType;\n\t\t\t\telse if (colRow.data_type === \"character varying\" || colRow.data_type === \"character\") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse if (colRow.data_type === \"numeric\" || colRow.data_type === \"decimal\") if (colRow.numeric_precision && colRow.numeric_scale !== null) nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;\n\t\t\t\telse if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse nativeType = colRow.udt_name || colRow.data_type;\n\t\t\t\tcolumns[colRow.column_name] = {\n\t\t\t\t\tname: colRow.column_name,\n\t\t\t\t\tnativeType,\n\t\t\t\t\tnullable: colRow.is_nullable === \"YES\",\n\t\t\t\t\t...ifDefined(\"default\", colRow.column_default ?? void 0)\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pkRows = [...pksByTable.get(tableName) ?? []];\n\t\t\tconst primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);\n\t\t\tconst primaryKey = primaryKeyColumns.length > 0 ? {\n\t\t\t\tcolumns: primaryKeyColumns,\n\t\t\t\t...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}\n\t\t\t} : void 0;\n\t\t\tconst foreignKeysMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const fkRow of fksByTable.get(tableName) ?? []) {\n\t\t\t\tconst existing = foreignKeysMap.get(fkRow.constraint_name);\n\t\t\t\tif (existing) {\n\t\t\t\t\texisting.columns.push(fkRow.column_name);\n\t\t\t\t\texisting.referencedColumns.push(fkRow.referenced_column_name);\n\t\t\t\t} else foreignKeysMap.set(fkRow.constraint_name, {\n\t\t\t\t\tcolumns: [fkRow.column_name],\n\t\t\t\t\treferencedTable: fkRow.referenced_table_name,\n\t\t\t\t\treferencedColumns: [fkRow.referenced_column_name],\n\t\t\t\t\tname: fkRow.constraint_name,\n\t\t\t\t\tdeleteRule: fkRow.delete_rule,\n\t\t\t\t\tupdateRule: fkRow.update_rule\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({\n\t\t\t\tcolumns: Object.freeze([...fk.columns]),\n\t\t\t\treferencedTable: fk.referencedTable,\n\t\t\t\treferencedColumns: Object.freeze([...fk.referencedColumns]),\n\t\t\t\tname: fk.name,\n\t\t\t\t...ifDefined(\"onDelete\", mapReferentialAction(fk.deleteRule)),\n\t\t\t\t...ifDefined(\"onUpdate\", mapReferentialAction(fk.updateRule))\n\t\t\t}));\n\t\t\tconst pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();\n\t\t\tconst uniquesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const uniqueRow of uniquesByTable.get(tableName) ?? []) {\n\t\t\t\tif (pkConstraints.has(uniqueRow.constraint_name)) continue;\n\t\t\t\tconst existing = uniquesMap.get(uniqueRow.constraint_name);\n\t\t\t\tif (existing) existing.columns.push(uniqueRow.column_name);\n\t\t\t\telse uniquesMap.set(uniqueRow.constraint_name, {\n\t\t\t\t\tcolumns: [uniqueRow.column_name],\n\t\t\t\t\tname: uniqueRow.constraint_name\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst uniques = Array.from(uniquesMap.values()).map((uq) => ({\n\t\t\t\tcolumns: Object.freeze([...uq.columns]),\n\t\t\t\tname: uq.name\n\t\t\t}));\n\t\t\tconst indexesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const idxRow of indexesByTable.get(tableName) ?? []) {\n\t\t\t\tif (!idxRow.attname) continue;\n\t\t\t\tconst existing = indexesMap.get(idxRow.indexname);\n\t\t\t\tif (existing) existing.columns.push(idxRow.attname);\n\t\t\t\telse indexesMap.set(idxRow.indexname, {\n\t\t\t\t\tcolumns: [idxRow.attname],\n\t\t\t\t\tname: idxRow.indexname,\n\t\t\t\t\tunique: idxRow.indisunique\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst indexes = Array.from(indexesMap.values()).map((idx) => ({\n\t\t\t\tcolumns: Object.freeze([...idx.columns]),\n\t\t\t\tname: idx.name,\n\t\t\t\tunique: idx.unique\n\t\t\t}));\n\t\t\ttables[tableName] = {\n\t\t\t\tname: tableName,\n\t\t\t\tcolumns,\n\t\t\t\t...ifDefined(\"primaryKey\", primaryKey),\n\t\t\t\tforeignKeys,\n\t\t\t\tuniques,\n\t\t\t\tindexes\n\t\t\t};\n\t\t}\n\t\tconst extensions = extensionsResult.rows.map((row) => row.extname);\n\t\tconst storageTypes = await pgEnumControlHooks.introspectTypes?.({\n\t\t\tdriver,\n\t\t\tschemaName: schema\n\t\t}) ?? {};\n\t\treturn {\n\t\t\ttables,\n\t\t\textensions,\n\t\t\tannotations: { pg: {\n\t\t\t\tschema,\n\t\t\t\tversion: await this.getPostgresVersion(driver),\n\t\t\t\t...ifDefined(\"storageTypes\", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)\n\t\t\t} }\n\t\t};\n\t}\n\t/**\n\t* Gets the Postgres version from the database.\n\t*/\n\tasync getPostgresVersion(driver) {\n\t\treturn ((await driver.query(\"SELECT version() AS version\", [])).rows[0]?.version ?? \"\").match(/PostgreSQL (\\d+\\.\\d+)/)?.[1] ?? \"unknown\";\n\t}\n};\n/**\n* Pre-computed lookup map for simple prefix-based type normalization.\n* Maps short Postgres type names to their canonical SQL names.\n* Using a Map for O(1) lookup instead of multiple startsWith checks.\n*/\nconst TYPE_PREFIX_MAP = new Map([\n\t[\"varchar\", \"character varying\"],\n\t[\"bpchar\", \"character\"],\n\t[\"varbit\", \"bit varying\"]\n]);\n/**\n* Normalizes a Postgres schema native type to its canonical form for comparison.\n*\n* Uses a pre-computed lookup map for simple prefix replacements (O(1))\n* and handles complex temporal type normalization separately.\n*/\nfunction normalizeSchemaNativeType(nativeType) {\n\tconst trimmed = nativeType.trim();\n\tfor (const [prefix, replacement] of TYPE_PREFIX_MAP) if (trimmed.startsWith(prefix)) return replacement + trimmed.slice(prefix.length);\n\tif (trimmed.includes(\" with time zone\")) {\n\t\tif (trimmed.startsWith(\"timestamp\")) return `timestamptz${trimmed.slice(9).replace(\" with time zone\", \"\")}`;\n\t\tif (trimmed.startsWith(\"time\")) return `timetz${trimmed.slice(4).replace(\" with time zone\", \"\")}`;\n\t}\n\tif (trimmed.includes(\" without time zone\")) return trimmed.replace(\" without time zone\", \"\");\n\treturn trimmed;\n}\nfunction normalizeFormattedType(formattedType, dataType, udtName) {\n\tif (formattedType === \"integer\") return \"int4\";\n\tif (formattedType === \"smallint\") return \"int2\";\n\tif (formattedType === \"bigint\") return \"int8\";\n\tif (formattedType === \"real\") return \"float4\";\n\tif (formattedType === \"double precision\") return \"float8\";\n\tif (formattedType === \"boolean\") return \"bool\";\n\tif (formattedType.startsWith(\"varchar\")) return formattedType.replace(\"varchar\", \"character varying\");\n\tif (formattedType.startsWith(\"bpchar\")) return formattedType.replace(\"bpchar\", \"character\");\n\tif (formattedType.startsWith(\"varbit\")) return formattedType.replace(\"varbit\", \"bit varying\");\n\tif (dataType === \"timestamp with time zone\" || udtName === \"timestamptz\") return formattedType.replace(\"timestamp\", \"timestamptz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"timestamp without time zone\" || udtName === \"timestamp\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (dataType === \"time with time zone\" || udtName === \"timetz\") return formattedType.replace(\"time\", \"timetz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"time without time zone\" || udtName === \"time\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (formattedType.startsWith(\"\\\"\") && formattedType.endsWith(\"\\\"\")) return formattedType.slice(1, -1);\n\treturn formattedType;\n}\nconst PG_REFERENTIAL_ACTION_MAP = {\n\t\"NO ACTION\": \"noAction\",\n\tRESTRICT: \"restrict\",\n\tCASCADE: \"cascade\",\n\t\"SET NULL\": \"setNull\",\n\t\"SET DEFAULT\": \"setDefault\"\n};\n/**\n* Maps a Postgres referential action rule to the canonical SqlReferentialAction.\n* Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.\n* Throws for unrecognized rules to prevent silent data loss.\n*/\nfunction mapReferentialAction(rule) {\n\tconst mapped = PG_REFERENTIAL_ACTION_MAP[rule];\n\tif (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: \"${rule}\". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);\n\tif (mapped === \"noAction\") return void 0;\n\treturn mapped;\n}\n/**\n* Groups an array of objects by a specified key.\n* Returns a Map for O(1) lookup by group key.\n*/\nfunction groupBy(items, key) {\n\tconst map = /* @__PURE__ */ new Map();\n\tfor (const item of items) {\n\t\tconst groupKey = item[key];\n\t\tlet group = map.get(groupKey);\n\t\tif (!group) {\n\t\t\tgroup = [];\n\t\t\tmap.set(groupKey, group);\n\t\t}\n\t\tgroup.push(item);\n\t}\n\treturn map;\n}\n\n//#endregion\n//#region src/exports/control.ts\nconst postgresAdapterDescriptor = {\n\t...postgresAdapterDescriptorMeta,\n\toperationSignatures: () => [],\n\tcreate() {\n\t\treturn new PostgresControlAdapter();\n\t}\n};\nvar control_default = postgresAdapterDescriptor;\n\n//#endregion\nexport { SqlEscapeError, control_default as default, escapeLiteral, expandParameterizedNativeType, normalizeSchemaNativeType, parsePostgresDefault, qualifyName, quoteIdentifier };\n//# sourceMappingURL=control.mjs.map","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\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 buildTargetDetails,\n columnExistsCheck,\n columnNullabilityCheck,\n constraintExistsCheck,\n qualifyTableName,\n toRegclassLiteral,\n} from './planner';\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}): {\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 });\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 'extension_missing':\n return true;\n case 'primary_key_mismatch':\n return issue.actual === undefined;\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'foreign_key_mismatch':\n return issue.indexOrConstraint === undefined;\n default:\n return false;\n }\n}\n\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}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const { issue, contract, schemaName, mode } = 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(schemaName, issue.table, issue.column, contractColumn);\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): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n const expectedType = buildColumnTypeSql(column);\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 // extension_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 expandParameterizedNativeType,\n normalizeSchemaNativeType,\n parsePostgresDefault,\n quoteIdentifier,\n} from '@prisma-next/adapter-postgres/control';\nimport { isTaggedBigInt } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/core-control-plane/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport {\n createMigrationPlan,\n extractCodecControlHooks,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type {\n ForeignKey,\n ReferentialAction,\n StorageColumn,\n StorageTable,\n} from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresColumnDefault } from '../types';\nimport { buildReconciliationPlan } from './planner-reconciliation';\n\nexport type OperationClass =\n | 'extension'\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 readonly verifyDatabaseDependencyInstalled: (schema: SqlSchemaIR) => readonly SchemaIssue[];\n};\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\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 });\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),\n ...this.buildColumnOperations(sortedTables, options.schema, schemaName),\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 for (const dependency of dependencies) {\n if (seenDependencyIds.has(dependency.id)) {\n continue;\n }\n seenDependencyIds.add(dependency.id);\n\n const issues = dependency.verifyDatabaseDependencyInstalled(options.schema);\n if (issues.length === 0) {\n continue;\n }\n\n for (const installOp of dependency.install) {\n if (seenOperationIds.has(installOp.id)) {\n continue;\n }\n seenOperationIds.add(installOp.id);\n // SQL family components are expected to provide compatible target details. This would be better if\n // the type system could enforce it but it's not likely to occur in practice.\n operations.push(installOp as SqlMigrationPlanOperation<PostgresPlanTargetDetails>);\n }\n }\n\n return operations;\n }\n\n private buildStorageTypeOperations(\n options: PlannerOptionsWithComponents,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): {\n readonly operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly conflicts: readonly SqlPlannerConflict[];\n } {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n const storageTypes = options.contract.storage.types ?? {};\n\n for (const [typeName, typeInstance] of sortedEntries(storageTypes)) {\n const hook = codecHooks.get(typeInstance.codecId);\n const planResult = hook?.planTypeOperations?.({\n typeName,\n typeInstance,\n contract: options.contract,\n schema: options.schema,\n schemaName,\n policy: options.policy,\n });\n if (!planResult) {\n continue;\n }\n for (const operation of planResult.operations) {\n if (!options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n conflicts.push({\n kind: 'missingButNonAdditive',\n summary: `Storage type \"${typeName}\" requires \"${operation.operationClass}\" operation \"${operation.id}\"`,\n location: {\n type: typeName,\n },\n });\n continue;\n }\n operations.push({\n ...operation,\n target: {\n id: operation.target.id,\n details: this.buildTargetDetails('type', typeName, schemaName),\n },\n });\n }\n }\n\n return { operations, conflicts };\n }\n private collectDependencies(\n options: PlannerOptionsWithComponents,\n ): ReadonlyArray<PlannerDatabaseDependency> {\n const components = options.frameworkComponents;\n if (components.length === 0) {\n return [];\n }\n const deps: PlannerDatabaseDependency[] = [];\n for (const component of components) {\n if (!isSqlDependencyProvider(component)) {\n continue;\n }\n const initDeps = component.databaseDependencies?.init;\n if (initDeps && initDeps.length > 0) {\n deps.push(...initDeps);\n }\n }\n return sortDependencies(deps);\n }\n\n private buildTableOperations(\n tables: 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 (schema.tables[tableName]) {\n continue;\n }\n const qualified = qualifyTableName(schemaName, tableName);\n operations.push({\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" does not exist`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: buildCreateTableSql(qualified, table),\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n });\n }\n return operations;\n }\n\n private buildColumnOperations(\n tables: 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 const schemaTable = schema.tables[tableName];\n if (!schemaTable) {\n continue;\n }\n for (const [columnName, column] of sortedEntries(table.columns)) {\n if (schemaTable.columns[columnName]) {\n continue;\n }\n operations.push(this.buildAddColumnOperation(schemaName, tableName, columnName, column));\n }\n }\n return operations;\n }\n\n private buildAddColumnOperation(\n schema: string,\n tableName: string,\n columnName: string,\n column: StorageColumn,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schema, tableName);\n const notNull = column.nullable === false;\n const hasDefault = column.default !== undefined;\n // Only require empty table for NOT NULL columns WITHOUT defaults.\n // PostgreSQL allows adding NOT NULL columns with defaults to non-empty tables\n // because the default value is applied to existing rows.\n const requiresEmptyTable = notNull && !hasDefault;\n const precheck = [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ...(requiresEmptyTable\n ? [\n {\n description: `ensure table \"${tableName}\" is empty before adding NOT NULL column without default`,\n sql: tableIsEmptyCheck(qualified),\n },\n ]\n : []),\n ];\n const execute = [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(qualified, columnName, column),\n },\n ];\n const postcheck = [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n ...(notNull\n ? [\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ]\n : []),\n ];\n\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schema),\n },\n precheck,\n execute,\n postcheck,\n };\n }\n\n private buildPrimaryKeyOperations(\n tables: 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 ?? `${tableName}_${index.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${index.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n /**\n * Generates FK-backing index operations for FKs with `index: true`,\n * but only when no matching user-declared index exists in `contractTable.indexes`.\n */\n private buildFkBackingIndexOperations(\n tables: 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 = `${tableName}_${fk.columns.join('_')}_idx`;\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create FK-backing index ${indexName} on ${tableName}`,\n summary: `Creates FK-backing index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create FK-backing index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${fk.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildForeignKeyOperations(\n tables: 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 isSqlDependencyProvider(component: unknown): component is {\n readonly databaseDependencies?: {\n readonly init?: readonly PlannerDatabaseDependency[];\n };\n} {\n if (typeof component !== 'object' || component === null) {\n return false;\n }\n const record = component as Record<string, unknown>;\n\n // If present, enforce familyId match to avoid mixing families at runtime.\n if (Object.hasOwn(record, 'familyId') && record['familyId'] !== 'sql') {\n return false;\n }\n\n if (!Object.hasOwn(record, 'databaseDependencies')) {\n return false;\n }\n const deps = record['databaseDependencies'];\n return deps === undefined || (typeof deps === 'object' && deps !== null);\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n if (dependencies.length <= 1) {\n return dependencies;\n }\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction buildCreateTableSql(qualifiedTableName: string, table: StorageTable): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column),\n buildColumnDefaultSql(column.default, column),\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n },\n );\n\n const constraintDefinitions: string[] = [];\n if (table.primaryKey) {\n constraintDefinitions.push(\n `PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n );\n }\n\n const allDefinitions = [...columnDefinitions, ...constraintDefinitions];\n return `CREATE TABLE ${qualifiedTableName} (\\n ${allDefinitions.join(',\\n ')}\\n)`;\n}\n\n/**\n * 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\n/**\n * Builds the column type SQL, handling autoincrement as a special case.\n * For autoincrement on int4/int8, we use SERIAL/BIGSERIAL types.\n */\nexport function buildColumnTypeSql(column: StorageColumn): string {\n const columnDefault = column.default;\n\n // For autoincrement, use SERIAL/BIGSERIAL types instead of int4/int8\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (column.nativeType === 'int4' || column.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (column.nativeType === 'int8' || column.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (column.nativeType === 'int2' || column.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n\n if (column.typeRef) {\n return quoteIdentifier(column.nativeType);\n }\n\n // Validate nativeType before using it unquoted in DDL\n assertSafeNativeType(column.nativeType);\n return renderParameterizedTypeSql(column) ?? column.nativeType;\n}\n\n/**\n * Renders parameterized type SQL for a column, returning null if no expansion is needed.\n *\n * Uses the shared expandParameterizedNativeType utility from the postgres adapter.\n * Returns null when the column has no typeParams, allowing the caller to fall back\n * to the base nativeType.\n */\nfunction renderParameterizedTypeSql(column: StorageColumn): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n const expanded = expandParameterizedNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n // If no expansion happened (returned the same base type), return null\n // so caller can decide whether to use nativeType directly\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/**\n * Builds the DEFAULT clause for a column definition.\n * Returns empty string if no default is defined.\n *\n * Note: autoincrement is handled specially via SERIAL types, so we skip it here.\n */\nfunction buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n // autoincrement is handled by SERIAL type, no explicit DEFAULT needed\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n // Sequence names use quoteIdentifier for safe identifier handling\n return `DEFAULT nextval(${quoteIdentifier(columnDefault.name)}::regclass)`;\n }\n}\n\nfunction renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (!isJsonColumn && isTaggedBigInt(value)) {\n if (!/^-?\\d+$/.test(value.value)) {\n throw new Error(`Invalid tagged bigint value: \"${value.value}\" is not a valid integer`);\n }\n return value.value;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'NULL';\n }\n const json = JSON.stringify(value);\n if (isJsonColumn) {\n return `'${escapeLiteral(json)}'::${column.nativeType}`;\n }\n return `'${escapeLiteral(json)}'`;\n}\n\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\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\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\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\nfunction tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nfunction buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n): string {\n const typeSql = buildColumnTypeSql(column);\n const defaultSql = buildColumnDefaultSql(column.default, column);\n const parts = [\n `ALTER TABLE ${qualifiedTableName}`,\n `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,\n defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n}\n\nfunction tableHasPrimaryKeyCheck(\n schema: string,\n table: string,\n exists: boolean,\n constraintName?: string,\n): string {\n const comparison = exists ? '' : 'NOT ';\n const constraintFilter = constraintName\n ? `AND c2.relname = '${escapeLiteral(constraintName)}'`\n : '';\n return `SELECT ${comparison}EXISTS (\n SELECT 1\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_class c2 ON c2.oid = i.indexrelid\n WHERE n.nspname = '${escapeLiteral(schema)}'\n AND c.relname = '${escapeLiteral(table)}'\n AND i.indisprimary\n ${constraintFilter}\n)`;\n}\n\n/**\n * 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\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\nfunction buildForeignKeySql(\n schemaName: string,\n tableName: string,\n fkName: string,\n foreignKey: ForeignKey,\n): string {\n let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`;\n\n if (foreignKey.onDelete !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];\n if (!action) {\n throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);\n }\n sql += `\\nON DELETE ${action}`;\n }\n if (foreignKey.onUpdate !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];\n if (!action) {\n throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);\n }\n sql += `\\nON UPDATE ${action}`;\n }\n\n return sql;\n}\n","import { bigintJsonReplacer } from '@prisma-next/contract/types';\n\nexport interface SqlStatement {\n readonly sql: string;\n readonly params: readonly unknown[];\n}\n\nexport const ensurePrismaContractSchemaStatement: SqlStatement = {\n sql: 'create schema if not exists prisma_contract',\n params: [],\n};\n\nexport const ensureMarkerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.marker (\n id smallint primary key default 1,\n core_hash text not null,\n profile_hash text not null,\n contract_json jsonb,\n canonical_version int,\n updated_at timestamptz not null default now(),\n app_tag text,\n meta jsonb not null default '{}'\n )`,\n params: [],\n};\n\nexport const ensureLedgerTableStatement: SqlStatement = {\n sql: `create table if not exists prisma_contract.ledger (\n id bigserial primary key,\n created_at timestamptz not null default now(),\n origin_core_hash text,\n origin_profile_hash text,\n destination_core_hash text not null,\n destination_profile_hash text,\n contract_json_before jsonb,\n contract_json_after jsonb,\n operations jsonb not null\n )`,\n params: [],\n};\n\nexport interface WriteMarkerInput {\n readonly storageHash: string;\n readonly profileHash: string;\n readonly contractJson?: unknown;\n readonly canonicalVersion?: number | null;\n readonly appTag?: string | null;\n readonly meta?: Record<string, unknown>;\n}\n\nexport function buildWriteMarkerStatements(input: WriteMarkerInput): {\n readonly insert: SqlStatement;\n readonly update: SqlStatement;\n} {\n const params: readonly unknown[] = [\n 1,\n input.storageHash,\n input.profileHash,\n jsonParam(input.contractJson),\n input.canonicalVersion ?? null,\n input.appTag ?? null,\n jsonParam(input.meta ?? {}),\n ];\n\n return {\n insert: {\n sql: `insert into prisma_contract.marker (\n id,\n core_hash,\n profile_hash,\n contract_json,\n canonical_version,\n updated_at,\n app_tag,\n meta\n ) values (\n $1,\n $2,\n $3,\n $4::jsonb,\n $5,\n now(),\n $6,\n $7::jsonb\n )`,\n params,\n },\n update: {\n sql: `update prisma_contract.marker set\n core_hash = $2,\n profile_hash = $3,\n contract_json = $4::jsonb,\n canonical_version = $5,\n updated_at = now(),\n app_tag = $6,\n meta = $7::jsonb\n where id = $1`,\n params,\n },\n };\n}\n\nexport interface LedgerInsertInput {\n readonly originStorageHash?: string | null;\n readonly originProfileHash?: string | null;\n readonly destinationStorageHash: string;\n readonly destinationProfileHash?: string | null;\n readonly contractJsonBefore?: unknown;\n readonly contractJsonAfter?: unknown;\n readonly operations: unknown;\n}\n\nexport function buildLedgerInsertStatement(input: LedgerInsertInput): SqlStatement {\n return {\n sql: `insert into prisma_contract.ledger (\n origin_core_hash,\n origin_profile_hash,\n destination_core_hash,\n destination_profile_hash,\n contract_json_before,\n contract_json_after,\n operations\n ) values (\n $1,\n $2,\n $3,\n $4,\n $5::jsonb,\n $6::jsonb,\n $7::jsonb\n )`,\n params: [\n input.originStorageHash ?? null,\n input.originProfileHash ?? null,\n input.destinationStorageHash,\n input.destinationProfileHash ?? null,\n jsonParam(input.contractJsonBefore),\n jsonParam(input.contractJsonAfter),\n jsonParam(input.operations),\n ],\n };\n}\n\nfunction jsonParam(value: unknown): string {\n return JSON.stringify(value ?? null, bigintJsonReplacer);\n}\n","import {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n} from '@prisma-next/adapter-postgres/control';\nimport type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport { readMarker } from '@prisma-next/family-sql/verify';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport type { PostgresPlanTargetDetails } from './planner';\nimport {\n buildLedgerInsertStatement,\n buildWriteMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await readMarker(driver);\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // Apply plan operations or skip if marker already at destination\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n let applyValue: ApplyPlanSuccessValue;\n\n if (markerAtDestination) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contractIR: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Record marker and ledger entries\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // 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 { expandParameterizedNativeType } from '@prisma-next/adapter-postgres/control';\nimport type { ContractIR } from '@prisma-next/contract/ir';\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 } from '@prisma-next/family-sql/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n operationSignatures: () => [],\n 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: ContractIR | null) {\n const storage = contract ? (contract.storage as SqlStorage) : { tables: {} };\n return contractToSchemaIR(storage, expandParameterizedNativeType);\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;AAGA,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;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