@prisma-next/target-postgres 0.4.0-dev.4 → 0.4.0-dev.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/control.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"control.mjs","names":["MAX_IDENTIFIER_LENGTH","renderLiteral","enumTypeExistsCheck","columnTypeCheck","REBUILD_SUFFIX","control_default","columnRefs: { table: string; column: string }[]","notNullBackfillStrategy: MigrationStrategy","matched: SchemaIssue[]","ops: PostgresMigrationOpDescriptor[]","TODO","typeChangeStrategy: MigrationStrategy","nullableTighteningStrategy: MigrationStrategy","enumChangeStrategy: MigrationStrategy","migrationPlanStrategies: readonly MigrationStrategy[]","ISSUE_KIND_ORDER: Record<string, number>","ops: PostgresMigrationOpDescriptor[]","context: StrategyContext","patternOps: PostgresMigrationOpDescriptor[]","defaultOps: PostgresMigrationOpDescriptor[]","conflicts: SqlPlannerConflict[]","descriptors: PostgresMigrationOpDescriptor[]","sql","FORMAT_TYPE_DISPLAY: ReadonlyMap<string, string>","constraintDefinitions: string[]","REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string>","sql","column: StorageColumn","quoteId","values: readonly string[]","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","ensurePrismaContractSchemaStatement: SqlStatement","ensureMarkerTableStatement: SqlStatement","ensureLedgerTableStatement: SqlStatement","params: readonly unknown[]","DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","step","entries: Record<string, SqlOperationEntry>","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../../../6-adapters/postgres/dist/sql-utils-CSfAGEwF.mjs","../../../6-adapters/postgres/dist/codec-ids-BwjcIf74.mjs","../../../6-adapters/postgres/dist/codecs-C3wlpdV7.mjs","../../../6-adapters/postgres/dist/descriptor-meta-DemWrTfB.mjs","../../../../1-framework/2-authoring/ids/dist/index.mjs","../../../6-adapters/postgres/dist/control.mjs","../src/core/migrations/planner-strategies.ts","../src/core/migrations/descriptor-planner.ts","../../../6-adapters/postgres/dist/adapter-7pXt8ej9.mjs","../src/core/migrations/planner-type-resolution.ts","../src/core/migrations/planner-sql-checks.ts","../src/core/migrations/planner-ddl-builders.ts","../src/core/migrations/operation-resolver.ts","../src/core/migrations/planner-identity-values.ts","../src/core/migrations/planner-target-details.ts","../src/core/migrations/planner-recipes.ts","../src/core/migrations/planner-reconciliation.ts","../src/core/migrations/planner-schema-lookup.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_TEXT_CODEC_ID, SQL_TIMESTAMP_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_TIMESTAMP_CODEC_ID as D, SQL_TEXT_CODEC_ID as E, SQL_VARCHAR_CODEC_ID as O, 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-BwjcIf74.mjs.map","import { S as PG_VARCHAR_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, x as PG_VARBIT_CODEC_ID, y as PG_TIMETZ_CODEC_ID } from \"./codec-ids-BwjcIf74.mjs\";\nimport { codec, defineCodecs, sqlCodecDefinitions } from \"@prisma-next/sql-relational-core/ast\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\nimport { type } from \"arktype\";\n\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/codecs.ts\nconst lengthParamsSchema = type({ length: \"number.integer > 0\" });\nconst numericParamsSchema = type({\n\tprecision: \"number.integer > 0 & number.integer <= 1000\",\n\t\"scale?\": \"number.integer >= 0\"\n});\nconst precisionParamsSchema = type({ \"precision?\": \"number.integer >= 0 & number.integer <= 6\" });\nfunction renderLength(typeName, typeParams) {\n\tconst length = typeParams[\"length\"];\n\tif (length === void 0) return;\n\tif (typeof length !== \"number\" || !Number.isFinite(length) || !Number.isInteger(length)) throw new Error(`renderOutputType: expected integer \"length\" in typeParams for ${typeName}, got ${String(length)}`);\n\treturn `${typeName}<${length}>`;\n}\nfunction renderPrecision(typeName, typeParams) {\n\tconst precision = typeParams[\"precision\"];\n\tif (precision === void 0) return typeName;\n\tif (typeof precision !== \"number\" || !Number.isFinite(precision) || !Number.isInteger(precision)) throw new Error(`renderOutputType: expected integer \"precision\" in typeParams for ${typeName}, got ${String(precision)}`);\n\treturn `${typeName}<${precision}>`;\n}\nfunction renderJsonOutputType(typeParams) {\n\tconst typeName = typeParams[\"type\"];\n\tif (typeof typeName === \"string\" && typeName.trim().length > 0) return typeName.trim();\n\tconst schema = typeParams[\"schemaJson\"];\n\tif (schema && typeof schema === \"object\") return renderTypeScriptTypeFromJsonSchema(schema);\n\tthrow new Error(`renderOutputType: JSON codec typeParams must contain \"type\" (string) or \"schemaJson\" (object), got keys: ${Object.keys(typeParams).join(\", \")}`);\n}\nfunction aliasCodec(base, options) {\n\treturn {\n\t\tid: options.typeId,\n\t\ttargetTypes: options.targetTypes,\n\t\t...ifDefined(\"meta\", options.meta),\n\t\t...ifDefined(\"paramsSchema\", base.paramsSchema),\n\t\t...ifDefined(\"init\", base.init),\n\t\t...ifDefined(\"encode\", base.encode),\n\t\t...ifDefined(\"traits\", base.traits),\n\t\t...ifDefined(\"renderOutputType\", base.renderOutputType),\n\t\tdecode: base.decode,\n\t\tencodeJson: base.encodeJson,\n\t\tdecodeJson: base.decodeJson\n\t};\n}\nconst sqlCharCodec = sqlCodecDefinitions.char.codec;\nconst sqlVarcharCodec = sqlCodecDefinitions.varchar.codec;\nconst sqlIntCodec = sqlCodecDefinitions.int.codec;\nconst sqlFloatCodec = sqlCodecDefinitions.float.codec;\nconst sqlTextCodec = sqlCodecDefinitions.text.codec;\nconst sqlTimestampCodec = sqlCodecDefinitions.timestamp.codec;\nconst pgTextCodec = codec({\n\ttypeId: PG_TEXT_CODEC_ID,\n\ttargetTypes: [\"text\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"textual\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"text\" } } } }\n});\nconst pgCharCodec = aliasCodec(sqlCharCodec, {\n\ttypeId: PG_CHAR_CODEC_ID,\n\ttargetTypes: [\"character\"],\n\tmeta: { db: { sql: { postgres: { nativeType: \"character\" } } } }\n});\nconst pgVarcharCodec = aliasCodec(sqlVarcharCodec, {\n\ttypeId: PG_VARCHAR_CODEC_ID,\n\ttargetTypes: [\"character varying\"],\n\tmeta: { db: { sql: { postgres: { nativeType: \"character varying\" } } } }\n});\nconst pgIntCodec = aliasCodec(sqlIntCodec, {\n\ttypeId: PG_INT_CODEC_ID,\n\ttargetTypes: [\"int4\"],\n\tmeta: { db: { sql: { postgres: { nativeType: \"integer\" } } } }\n});\nconst pgFloatCodec = aliasCodec(sqlFloatCodec, {\n\ttypeId: PG_FLOAT_CODEC_ID,\n\ttargetTypes: [\"float8\"],\n\tmeta: { db: { sql: { postgres: { nativeType: \"double precision\" } } } }\n});\nconst pgInt4Codec = codec({\n\ttypeId: PG_INT4_CODEC_ID,\n\ttargetTypes: [\"int4\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"integer\" } } } }\n});\nconst pgNumericCodec = codec({\n\ttypeId: PG_NUMERIC_CODEC_ID,\n\ttargetTypes: [\"numeric\", \"decimal\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => {\n\t\tif (typeof wire === \"number\") return String(wire);\n\t\treturn wire;\n\t},\n\tparamsSchema: numericParamsSchema,\n\trenderOutputType: (typeParams) => {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (precision === void 0) return void 0;\n\t\tif (typeof precision !== \"number\" || !Number.isFinite(precision) || !Number.isInteger(precision)) throw new Error(`renderOutputType: expected integer \"precision\" in typeParams for Numeric, got ${String(precision)}`);\n\t\tconst scale = typeParams[\"scale\"];\n\t\treturn typeof scale === \"number\" ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;\n\t},\n\tmeta: { db: { sql: { postgres: { nativeType: \"numeric\" } } } }\n});\nconst pgInt2Codec = codec({\n\ttypeId: PG_INT2_CODEC_ID,\n\ttargetTypes: [\"int2\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"smallint\" } } } }\n});\nconst pgInt8Codec = codec({\n\ttypeId: PG_INT8_CODEC_ID,\n\ttargetTypes: [\"int8\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"bigint\" } } } }\n});\nconst pgFloat4Codec = codec({\n\ttypeId: PG_FLOAT4_CODEC_ID,\n\ttargetTypes: [\"float4\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"real\" } } } }\n});\nconst pgFloat8Codec = codec({\n\ttypeId: PG_FLOAT8_CODEC_ID,\n\ttargetTypes: [\"float8\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"double precision\" } } } }\n});\nconst pgTimestampCodec = codec({\n\ttypeId: PG_TIMESTAMP_CODEC_ID,\n\ttargetTypes: [\"timestamp\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => {\n\t\tif (value instanceof Date) return value.toISOString();\n\t\tif (typeof value === \"string\") return value;\n\t\treturn String(value);\n\t},\n\tdecode: (wire) => {\n\t\tif (wire instanceof Date) return wire.toISOString();\n\t\treturn wire;\n\t},\n\tencodeJson: (value) => value instanceof Date ? value.toISOString() : value,\n\tdecodeJson: (json) => {\n\t\tif (typeof json !== \"string\") throw new Error(`Expected ISO date string for pg/timestamp@1, got ${typeof json}`);\n\t\tconst date = new Date(json);\n\t\tif (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date string for pg/timestamp@1: ${json}`);\n\t\treturn date;\n\t},\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Timestamp\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"timestamp without time zone\" } } } }\n});\nconst pgTimestamptzCodec = codec({\n\ttypeId: PG_TIMESTAMPTZ_CODEC_ID,\n\ttargetTypes: [\"timestamptz\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => {\n\t\tif (value instanceof Date) return value.toISOString();\n\t\tif (typeof value === \"string\") return value;\n\t\treturn String(value);\n\t},\n\tdecode: (wire) => {\n\t\tif (wire instanceof Date) return wire.toISOString();\n\t\treturn wire;\n\t},\n\tencodeJson: (value) => value instanceof Date ? value.toISOString() : value,\n\tdecodeJson: (json) => {\n\t\tif (typeof json !== \"string\") throw new Error(`Expected ISO date string for pg/timestamptz@1, got ${typeof json}`);\n\t\tconst date = new Date(json);\n\t\tif (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date string for pg/timestamptz@1: ${json}`);\n\t\treturn date;\n\t},\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Timestamptz\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"timestamp with time zone\" } } } }\n});\nconst pgTimeCodec = codec({\n\ttypeId: PG_TIME_CODEC_ID,\n\ttargetTypes: [\"time\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Time\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"time\" } } } }\n});\nconst pgTimetzCodec = codec({\n\ttypeId: PG_TIMETZ_CODEC_ID,\n\ttargetTypes: [\"timetz\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Timetz\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"timetz\" } } } }\n});\nconst pgBoolCodec = codec({\n\ttypeId: PG_BOOL_CODEC_ID,\n\ttargetTypes: [\"bool\"],\n\ttraits: [\"equality\", \"boolean\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"boolean\" } } } }\n});\nconst pgBitCodec = codec({\n\ttypeId: PG_BIT_CODEC_ID,\n\ttargetTypes: [\"bit\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tparamsSchema: lengthParamsSchema,\n\trenderOutputType: (typeParams) => renderLength(\"Bit\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"bit\" } } } }\n});\nconst pgVarbitCodec = codec({\n\ttypeId: PG_VARBIT_CODEC_ID,\n\ttargetTypes: [\"bit varying\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tparamsSchema: lengthParamsSchema,\n\trenderOutputType: (typeParams) => renderLength(\"VarBit\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"bit varying\" } } } }\n});\nconst pgEnumCodec = codec({\n\ttypeId: PG_ENUM_CODEC_ID,\n\ttargetTypes: [\"enum\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\trenderOutputType: (typeParams) => {\n\t\tconst values = typeParams[\"values\"];\n\t\tif (!Array.isArray(values)) throw new Error(`renderOutputType: expected array \"values\" in typeParams for enum, got ${typeof values}`);\n\t\treturn values.map((value) => `'${String(value).replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`).join(\" | \");\n\t}\n});\nconst pgIntervalCodec = codec({\n\ttypeId: PG_INTERVAL_CODEC_ID,\n\ttargetTypes: [\"interval\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => {\n\t\tif (typeof wire === \"string\") return wire;\n\t\treturn JSON.stringify(wire);\n\t},\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Interval\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"interval\" } } } }\n});\nconst pgJsonCodec = codec({\n\ttypeId: PG_JSON_CODEC_ID,\n\ttargetTypes: [\"json\"],\n\ttraits: [],\n\tencode: (value) => JSON.stringify(value),\n\tdecode: (wire) => typeof wire === \"string\" ? JSON.parse(wire) : wire,\n\trenderOutputType: renderJsonOutputType,\n\tmeta: { db: { sql: { postgres: { nativeType: \"json\" } } } }\n});\nconst pgJsonbCodec = codec({\n\ttypeId: PG_JSONB_CODEC_ID,\n\ttargetTypes: [\"jsonb\"],\n\ttraits: [\"equality\"],\n\tencode: (value) => JSON.stringify(value),\n\tdecode: (wire) => typeof wire === \"string\" ? JSON.parse(wire) : wire,\n\trenderOutputType: renderJsonOutputType,\n\tmeta: { db: { sql: { postgres: { nativeType: \"jsonb\" } } } }\n});\nconst codecs = defineCodecs().add(\"char\", sqlCharCodec).add(\"varchar\", sqlVarcharCodec).add(\"int\", sqlIntCodec).add(\"float\", sqlFloatCodec).add(\"sql-text\", sqlTextCodec).add(\"sql-timestamp\", sqlTimestampCodec).add(\"text\", pgTextCodec).add(\"character\", pgCharCodec).add(\"character varying\", pgVarcharCodec).add(\"integer\", pgIntCodec).add(\"double precision\", pgFloatCodec).add(\"int4\", pgInt4Codec).add(\"int2\", pgInt2Codec).add(\"int8\", pgInt8Codec).add(\"float4\", pgFloat4Codec).add(\"float8\", pgFloat8Codec).add(\"numeric\", pgNumericCodec).add(\"timestamp\", pgTimestampCodec).add(\"timestamptz\", pgTimestamptzCodec).add(\"time\", pgTimeCodec).add(\"timetz\", pgTimetzCodec).add(\"bool\", pgBoolCodec).add(\"bit\", pgBitCodec).add(\"bit varying\", pgVarbitCodec).add(\"interval\", pgIntervalCodec).add(\"enum\", pgEnumCodec).add(\"json\", pgJsonCodec).add(\"jsonb\", pgJsonbCodec);\nconst codecDefinitions = codecs.codecDefinitions;\nconst dataTypes = codecs.dataTypes;\n\n//#endregion\nexport { dataTypes as n, codecDefinitions as t };\n//# sourceMappingURL=codecs-C3wlpdV7.mjs.map","import { C as SQL_CHAR_CODEC_ID, D as SQL_TIMESTAMP_CODEC_ID, E as SQL_TEXT_CODEC_ID, O 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-BwjcIf74.mjs\";\nimport { t as codecDefinitions } from \"./codecs-C3wlpdV7.mjs\";\nimport { a as validateEnumValueLength, i as quoteIdentifier, n as escapeLiteral, r as qualifyName } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { arraysEqual } from \"@prisma-next/family-sql/schema-verify\";\n\n//#region src/core/enum-control-hooks.ts\nconst ENUM_INTROSPECT_QUERY = `\n SELECT\n n.nspname AS schema_name,\n t.typname AS type_name,\n array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n JOIN pg_enum e ON t.oid = e.enumtypid\n WHERE n.nspname = $1\n GROUP BY n.nspname, t.typname\n ORDER BY n.nspname, t.typname\n`;\n/**\n* Type guard for string arrays. Used for runtime validation of introspected data.\n*/\nfunction isStringArray(value) {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n/**\n* Parses a PostgreSQL array value into a JavaScript string array.\n*\n* PostgreSQL's `pg` library may return `array_agg` results either as:\n* - A JavaScript array (when type parsers are configured)\n* - A string in PostgreSQL array literal format: `{value1,value2,...}`\n*\n* Handles PostgreSQL's quoting rules for array elements:\n* - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted\n* - Inside quoted elements, `\\\"` represents `\"` and `\\\\` represents `\\`\n*\n* @param value - The value to parse (array or PostgreSQL array string)\n* @returns A string array, or null if the value cannot be parsed\n*/\nfunction parsePostgresArray(value) {\n\tif (isStringArray(value)) return value;\n\tif (typeof value === \"string\" && value.startsWith(\"{\") && value.endsWith(\"}\")) {\n\t\tconst inner = value.slice(1, -1);\n\t\tif (inner === \"\") return [];\n\t\treturn parseArrayElements(inner);\n\t}\n\treturn null;\n}\nfunction parseArrayElements(input) {\n\tconst result = [];\n\tlet i = 0;\n\twhile (i < input.length) {\n\t\tif (input[i] === \",\") {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (input[i] === \"\\\"\") {\n\t\t\ti++;\n\t\t\tlet element = \"\";\n\t\t\twhile (i < input.length && input[i] !== \"\\\"\") {\n\t\t\t\tif (input[i] === \"\\\\\" && i + 1 < input.length) {\n\t\t\t\t\ti++;\n\t\t\t\t\telement += input[i];\n\t\t\t\t} else element += input[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tresult.push(element);\n\t\t} else {\n\t\t\tconst nextComma = input.indexOf(\",\", i);\n\t\t\tif (nextComma === -1) {\n\t\t\t\tresult.push(input.slice(i).trim());\n\t\t\t\ti = input.length;\n\t\t\t} else {\n\t\t\t\tresult.push(input.slice(i, nextComma).trim());\n\t\t\t\ti = nextComma;\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n/**\n* Extracts enum values from a StorageTypeInstance.\n* Returns null if values are missing or invalid.\n*/\nfunction getEnumValues(typeInstance) {\n\tconst values = typeInstance.typeParams?.[\"values\"];\n\treturn isStringArray(values) ? values : null;\n}\n/**\n* Reads existing enum values from the schema IR for a given native type.\n* Uses optional chaining to simplify navigation through the annotations structure.\n*/\nfunction readExistingEnumValues(schema, nativeType) {\n\tconst existing = ((schema.annotations?.[\"pg\"])?.[\"storageTypes\"])?.[nativeType];\n\tif (!existing || existing.codecId !== PG_ENUM_CODEC_ID) return null;\n\treturn getEnumValues(existing);\n}\n/**\n* Determines what changes are needed to transform existing enum values to desired values.\n*\n* Returns one of:\n* - `unchanged`: No changes needed, values match exactly\n* - `add_values`: New values can be safely appended (PostgreSQL supports this)\n* - `rebuild`: Full enum rebuild required (value removal, reordering, or both)\n*\n* Note: PostgreSQL enums can only have values added (not removed or reordered) without\n* a full type rebuild involving temp type creation and column migration.\n*\n* @param existing - Current enum values in the database\n* @param desired - Target enum values from the contract\n* @returns The type of change required\n*/\nfunction determineEnumDiff(existing, desired) {\n\tif (arraysEqual(existing, desired)) return { kind: \"unchanged\" };\n\tconst existingSet = new Set(existing);\n\tconst desiredSet = new Set(desired);\n\tconst missingValues = desired.filter((value) => !existingSet.has(value));\n\tconst removedValues = existing.filter((value) => !desiredSet.has(value));\n\tconst orderMismatch = missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);\n\tif (removedValues.length > 0 || orderMismatch) return {\n\t\tkind: \"rebuild\",\n\t\tremovedValues\n\t};\n\treturn {\n\t\tkind: \"add_values\",\n\t\tvalues: missingValues\n\t};\n}\nfunction enumTypeExistsCheck(schemaName, typeName, exists = true) {\n\treturn `SELECT ${exists ? \"EXISTS\" : \"NOT EXISTS\"} (\n SELECT 1\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = '${escapeLiteral(schemaName)}'\n AND t.typname = '${escapeLiteral(typeName)}'\n)`;\n}\nfunction buildCreateEnumOperation(typeName, nativeType, schemaName, values) {\n\tfor (const value of values) validateEnumValueLength(value, typeName);\n\tconst literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst qualifiedType = qualifyName(schemaName, nativeType);\n\treturn {\n\t\tid: `type.${typeName}`,\n\t\tlabel: `Create type ${typeName}`,\n\t\tsummary: `Creates enum type ${typeName}`,\n\t\toperationClass: \"additive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${nativeType}\" does not exist`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType, false)\n\t\t}],\n\t\texecute: [{\n\t\t\tdescription: `create type \"${nativeType}\"`,\n\t\t\tsql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`\n\t\t}],\n\t\tpostcheck: [{\n\t\t\tdescription: `verify type \"${nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType)\n\t\t}]\n\t};\n}\n/**\n* Computes the optimal position for inserting a new enum value to maintain\n* the desired order relative to existing values.\n*\n* PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.\n* This function finds the best reference value by:\n* 1. Looking for the nearest preceding value that already exists\n* 2. Falling back to the nearest following value if no preceding exists\n* 3. Defaulting to end-of-list if no reference is found\n*\n* @param options.desired - The target ordered list of all enum values\n* @param options.desiredIndex - Index of the value being inserted in the desired list\n* @param options.current - Current list of enum values (being built up incrementally)\n* @returns SQL clause (e.g., \" AFTER 'x'\") and insert position for tracking\n*/\nfunction computeInsertPosition(options) {\n\tconst { desired, desiredIndex, current } = options;\n\tconst currentSet = new Set(current);\n\tconst previous = desired.slice(0, desiredIndex).reverse().find((candidate) => currentSet.has(candidate));\n\tconst next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));\n\treturn {\n\t\tclause: previous ? ` AFTER '${escapeLiteral(previous)}'` : next ? ` BEFORE '${escapeLiteral(next)}'` : \"\",\n\t\tinsertAt: previous ? current.indexOf(previous) + 1 : next ? current.indexOf(next) : current.length\n\t};\n}\n/**\n* Builds operations to add new enum values to an existing PostgreSQL enum type.\n*\n* Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.\n* Values are inserted in the correct order using BEFORE/AFTER positioning to match\n* the desired final order.\n*\n* This is a safe, non-destructive operation - existing data is not affected.\n*\n* @param options.typeName - Contract-level type name (e.g., 'Role')\n* @param options.nativeType - PostgreSQL type name (e.g., 'role')\n* @param options.schemaName - PostgreSQL schema (e.g., 'public')\n* @param options.desired - Target ordered list of all enum values\n* @param options.existing - Current enum values in the database\n* @returns Array of migration operations to add each missing value\n*/\nfunction buildAddValueOperations(options) {\n\tconst { typeName, nativeType, schemaName } = options;\n\tconst current = [...options.existing];\n\tconst currentSet = new Set(current);\n\tconst operations = [];\n\tfor (let index = 0; index < options.desired.length; index += 1) {\n\t\tconst value = options.desired[index];\n\t\tif (value === void 0) continue;\n\t\tif (currentSet.has(value)) continue;\n\t\tvalidateEnumValueLength(value, typeName);\n\t\tconst { clause, insertAt } = computeInsertPosition({\n\t\t\tdesired: options.desired,\n\t\t\tdesiredIndex: index,\n\t\t\tcurrent\n\t\t});\n\t\toperations.push({\n\t\t\tid: `type.${typeName}.value.${value}`,\n\t\t\tlabel: `Add value ${value} to ${typeName}`,\n\t\t\tsummary: `Adds enum value ${value} to ${typeName}`,\n\t\t\toperationClass: \"widening\",\n\t\t\ttarget: { id: \"postgres\" },\n\t\t\tprecheck: [],\n\t\t\texecute: [{\n\t\t\t\tdescription: `add value \"${value}\" if not exists`,\n\t\t\t\tsql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(value)}'${clause}`\n\t\t\t}],\n\t\t\tpostcheck: []\n\t\t});\n\t\tcurrent.splice(insertAt, 0, value);\n\t\tcurrentSet.add(value);\n\t}\n\treturn operations;\n}\n/**\n* Collects columns using the enum type from the contract (desired state).\n* Used for type-safe reference tracking.\n*/\nfunction collectEnumColumnsFromContract(contract, typeName, nativeType) {\n\tconst columns = [];\n\tfor (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeRef === typeName || column.nativeType === nativeType && column.codecId === PG_ENUM_CODEC_ID) columns.push({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects columns using the enum type from the schema IR (live database state).\n* This ensures we find ALL dependent columns, including those added outside the contract\n* (e.g., manual DDL), which is critical for safe enum rebuild operations.\n*/\nfunction collectEnumColumnsFromSchema(schema, nativeType) {\n\tconst columns = [];\n\tfor (const [tableName, table] of Object.entries(schema.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.nativeType === nativeType) columns.push({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects all columns using the enum type from both contract AND live database.\n* Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.\n*\n* This is critical for data integrity: if a column exists in the database using\n* this enum but is not in the contract (e.g., added via manual DDL), we must\n* still migrate it to avoid DROP TYPE failures.\n*/\nfunction collectAllEnumColumns(contract, schema, typeName, nativeType) {\n\tconst contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);\n\tconst schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst result = [];\n\tfor (const col of [...contractColumns, ...schemaColumns]) {\n\t\tconst key = `${col.table}.${col.column}`;\n\t\tif (!seen.has(key)) {\n\t\t\tseen.add(key);\n\t\t\tresult.push(col);\n\t\t}\n\t}\n\treturn result.sort((a, b) => {\n\t\tconst tableCompare = a.table.localeCompare(b.table);\n\t\treturn tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);\n\t});\n}\n/**\n* Builds a SQL check to verify a column's type matches an expected type.\n*/\nfunction columnTypeCheck(options) {\n\treturn `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(options.schemaName)}'\n AND table_name = '${escapeLiteral(options.tableName)}'\n AND column_name = '${escapeLiteral(options.columnName)}'\n AND udt_name = '${escapeLiteral(options.expectedType)}'\n)`;\n}\n/** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */\nconst MAX_IDENTIFIER_LENGTH = 63;\n/** Suffix added to enum type names during rebuild operations */\nconst REBUILD_SUFFIX = \"__pn_rebuild\";\n/**\n* Builds an SQL check to verify no rows contain any of the removed enum values.\n* This prevents data loss during enum rebuild operations.\n*\n* @param schemaName - PostgreSQL schema name\n* @param tableName - Table containing the enum column\n* @param columnName - Column using the enum type\n* @param removedValues - Array of enum values being removed\n* @returns SQL query that returns true if no rows contain removed values\n*/\nfunction noRemovedValuesExistCheck(schemaName, tableName, columnName, removedValues) {\n\tif (removedValues.length === 0) return \"SELECT true\";\n\tconst valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(\", \");\n\treturn `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualifyName(schemaName, tableName)}\n WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})\n LIMIT 1\n)`;\n}\n/**\n* Builds a migration operation to recreate a PostgreSQL enum type with updated values.\n*\n* This is required when:\n* - Enum values are removed (PostgreSQL doesn't support direct removal)\n* - Enum values are reordered (PostgreSQL doesn't support reordering)\n*\n* The operation:\n* 1. Creates a new enum type with the desired values (temp name)\n* 2. Migrates all columns to use the new type via text cast\n* 3. Drops the original type\n* 4. Renames the temp type to the original name\n*\n* IMPORTANT: If values are being removed and data exists using those values,\n* the operation will fail at the precheck stage with a clear error message.\n* This prevents silent data loss.\n*\n* @param options.typeName - Contract-level type name\n* @param options.nativeType - PostgreSQL type name\n* @param options.schemaName - PostgreSQL schema\n* @param options.values - Desired final enum values\n* @param options.removedValues - Values being removed (for data loss checks)\n* @param options.contract - Full contract for column discovery\n* @param options.schema - Current schema IR for column discovery\n* @returns Migration operation for full enum rebuild\n*/\nfunction buildRecreateEnumOperation(options) {\n\tconst tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;\n\tif (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {\n\t\tconst maxBaseLength = MAX_IDENTIFIER_LENGTH - 12;\n\t\tthrow new Error(`Enum type name \"${options.nativeType}\" is too long for rebuild operation. Maximum length is ${maxBaseLength} characters (type name + \"${REBUILD_SUFFIX}\" suffix must fit within PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character identifier limit).`);\n\t}\n\tconst qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);\n\tconst qualifiedTemp = qualifyName(options.schemaName, tempTypeName);\n\tconst literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst columnRefs = collectAllEnumColumns(options.contract, options.schema, options.typeName, options.nativeType);\n\tconst alterColumns = columnRefs.map((ref) => ({\n\t\tdescription: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,\n\t\tsql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}\nALTER COLUMN ${quoteIdentifier(ref.column)}\nTYPE ${qualifiedTemp}\nUSING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`\n\t}));\n\tconst postchecks = [\n\t\t{\n\t\t\tdescription: `verify type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t},\n\t\t{\n\t\t\tdescription: `verify temp type \"${tempTypeName}\" was removed`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, tempTypeName, false)\n\t\t},\n\t\t...columnRefs.map((ref) => ({\n\t\t\tdescription: `verify ${ref.table}.${ref.column} uses type \"${options.nativeType}\"`,\n\t\t\tsql: columnTypeCheck({\n\t\t\t\tschemaName: options.schemaName,\n\t\t\t\ttableName: ref.table,\n\t\t\t\tcolumnName: ref.column,\n\t\t\t\texpectedType: options.nativeType\n\t\t\t})\n\t\t}))\n\t];\n\treturn {\n\t\tid: `type.${options.typeName}.rebuild`,\n\t\tlabel: `Rebuild type ${options.typeName}`,\n\t\tsummary: `Recreates enum type ${options.typeName} with updated values`,\n\t\toperationClass: \"destructive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t}, ...options.removedValues.length > 0 ? columnRefs.map((ref) => ({\n\t\t\tdescription: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(\", \")})`,\n\t\t\tsql: noRemovedValuesExistCheck(options.schemaName, ref.table, ref.column, options.removedValues)\n\t\t})) : []],\n\t\texecute: [\n\t\t\t{\n\t\t\t\tdescription: `drop orphaned temp type \"${tempTypeName}\" if exists`,\n\t\t\t\tsql: `DROP TYPE IF EXISTS ${qualifiedTemp}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `create temp type \"${tempTypeName}\"`,\n\t\t\t\tsql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`\n\t\t\t},\n\t\t\t...alterColumns,\n\t\t\t{\n\t\t\t\tdescription: `drop type \"${options.nativeType}\"`,\n\t\t\t\tsql: `DROP TYPE ${qualifiedOriginal}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `rename type \"${tempTypeName}\" to \"${options.nativeType}\"`,\n\t\t\t\tsql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`\n\t\t\t}\n\t\t],\n\t\tpostcheck: postchecks\n\t};\n}\n/**\n* Postgres enum hooks for planning, verifying, and introspecting `storage.types`.\n*/\nconst pgEnumControlHooks = {\n\tplanTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired || desired.length === 0) return { operations: [] };\n\t\tconst schemaNamespace = schemaName ?? \"public\";\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return { operations: [buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired)] };\n\t\tconst diff = determineEnumDiff(existing, desired);\n\t\tif (diff.kind === \"unchanged\") return { operations: [] };\n\t\tif (diff.kind === \"rebuild\") return { operations: [buildRecreateEnumOperation({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tvalues: desired,\n\t\t\tremovedValues: diff.removedValues,\n\t\t\tcontract,\n\t\t\tschema\n\t\t})] };\n\t\treturn { operations: buildAddValueOperations({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tdesired,\n\t\t\texisting\n\t\t}) };\n\t},\n\tverifyType: ({ typeName, typeInstance, schema }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired) return [];\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return [{\n\t\t\tkind: \"type_missing\",\n\t\t\ttypeName,\n\t\t\tmessage: `Type \"${typeName}\" is missing from database`\n\t\t}];\n\t\tconst diff = determineEnumDiff(existing, desired);\n\t\tif (diff.kind === \"unchanged\") return [];\n\t\tconst existingSet = new Set(existing);\n\t\tconst desiredSet = new Set(desired);\n\t\tconst addedValues = desired.filter((v) => !existingSet.has(v));\n\t\tconst removedValues = existing.filter((v) => !desiredSet.has(v));\n\t\treturn [{\n\t\t\tkind: \"enum_values_changed\",\n\t\t\ttypeName,\n\t\t\taddedValues,\n\t\t\tremovedValues,\n\t\t\tmessage: diff.kind === \"add_values\" ? `Enum type \"${typeName}\" needs new values: ${addedValues.join(\", \")}` : `Enum type \"${typeName}\" values changed (requires rebuild): +[${addedValues.join(\", \")}] -[${removedValues.join(\", \")}]`\n\t\t}];\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/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});\nfunction isPositiveInteger(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value > 0;\n}\nfunction isNonNegativeInteger(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\nfunction expandLength({ nativeType, typeParams }) {\n\tif (!typeParams || !(\"length\" in typeParams)) return nativeType;\n\tconst length = typeParams[\"length\"];\n\tif (!isPositiveInteger(length)) throw new Error(`Invalid \"length\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(length)}`);\n\treturn `${nativeType}(${length})`;\n}\nfunction expandPrecision({ nativeType, typeParams }) {\n\tif (!typeParams || !(\"precision\" in typeParams)) return nativeType;\n\tconst precision = typeParams[\"precision\"];\n\tif (!isPositiveInteger(precision)) throw new Error(`Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`);\n\treturn `${nativeType}(${precision})`;\n}\nfunction expandNumeric({ nativeType, typeParams }) {\n\tconst hasPrecision = typeParams && \"precision\" in typeParams;\n\tconst hasScale = typeParams && \"scale\" in typeParams;\n\tif (!hasPrecision && !hasScale) return nativeType;\n\tif (!hasPrecision && hasScale) throw new Error(`Invalid type parameters for \"${nativeType}\": \"scale\" requires \"precision\" to be specified`);\n\tif (hasPrecision) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (!isPositiveInteger(precision)) throw new Error(`Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`);\n\t\tif (hasScale) {\n\t\t\tconst scale = typeParams[\"scale\"];\n\t\t\tif (!isNonNegativeInteger(scale)) throw new Error(`Invalid \"scale\" type parameter for \"${nativeType}\": expected a non-negative integer, got ${JSON.stringify(scale)}`);\n\t\t\treturn `${nativeType}(${precision},${scale})`;\n\t\t}\n\t\treturn `${nativeType}(${precision})`;\n\t}\n\treturn nativeType;\n}\nconst lengthHooks = { expandNativeType: expandLength };\nconst precisionHooks = { expandNativeType: expandPrecision };\nconst numericHooks = { expandNativeType: expandNumeric };\nconst identityHooks = { expandNativeType: ({ nativeType }) => nativeType };\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: {\n\t\t\tenums: true,\n\t\t\treturning: true,\n\t\t\tdefaultInInsert: true\n\t\t}\n\t},\n\ttypes: {\n\t\tcodecTypes: {\n\t\t\tcodecInstances: Object.values(codecDefinitions).map((def) => def.codec),\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\ttypeImports: [\n\t\t\t\t{\n\t\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\t\tnamed: \"JsonValue\",\n\t\t\t\t\talias: \"JsonValue\"\n\t\t\t\t},\n\t\t\t\tcodecTypeImport(\"Char\"),\n\t\t\t\tcodecTypeImport(\"Varchar\"),\n\t\t\t\tcodecTypeImport(\"Numeric\"),\n\t\t\t\tcodecTypeImport(\"Bit\"),\n\t\t\t\tcodecTypeImport(\"VarBit\"),\n\t\t\t\tcodecTypeImport(\"Timestamp\"),\n\t\t\t\tcodecTypeImport(\"Timestamptz\"),\n\t\t\t\tcodecTypeImport(\"Time\"),\n\t\t\t\tcodecTypeImport(\"Timetz\"),\n\t\t\t\tcodecTypeImport(\"Interval\")\n\t\t\t],\n\t\t\tcontrolPlaneHooks: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[SQL_TIMESTAMP_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_CHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: numericHooks,\n\t\t\t\t[PG_BIT_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_VARBIT_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIME_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_ENUM_CODEC_ID]: pgEnumControlHooks,\n\t\t\t\t[PG_JSON_CODEC_ID]: identityHooks,\n\t\t\t\t[PG_JSONB_CODEC_ID]: identityHooks\n\t\t\t}\n\t\t},\n\t\tstorage: [\n\t\t\t{\n\t\t\t\ttypeId: PG_TEXT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"text\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_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: SQL_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_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT2_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int2\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_NUMERIC_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"numeric\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMP_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamp\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMPTZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamptz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIME_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"time\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMETZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timetz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BOOL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bool\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARBIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INTERVAL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"interval\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSON_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"json\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSONB_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"jsonb\"\n\t\t\t}\n\t\t]\n\t}\n};\n\n//#endregion\nexport { pgEnumControlHooks as n, postgresAdapterDescriptorMeta as t };\n//# sourceMappingURL=descriptor-meta-DemWrTfB.mjs.map","import { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/generator-ids.ts\nconst builtinGeneratorIds = [\n\t\"ulid\",\n\t\"nanoid\",\n\t\"uuidv7\",\n\t\"uuidv4\",\n\t\"cuid2\",\n\t\"ksuid\"\n];\n\n//#endregion\n//#region src/index.ts\nfunction resolveNanoidColumnDescriptor(params) {\n\tconst rawSize = params?.[\"size\"];\n\tif (rawSize === void 0) return {\n\t\ttype: {\n\t\t\tcodecId: \"sql/char@1\",\n\t\t\tnativeType: \"character\"\n\t\t},\n\t\ttypeParams: { length: 21 }\n\t};\n\tif (typeof rawSize !== \"number\" || !Number.isInteger(rawSize) || rawSize < 2 || rawSize > 255) throw new Error(\"nanoid size must be an integer between 2 and 255\");\n\treturn {\n\t\ttype: {\n\t\t\tcodecId: \"sql/char@1\",\n\t\t\tnativeType: \"character\"\n\t\t},\n\t\ttypeParams: { length: rawSize }\n\t};\n}\nconst builtinGeneratorMetadataById = {\n\tulid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 26 }\n\t\t}\n\t},\n\tnanoid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 21 }\n\t\t},\n\t\tresolveGeneratedColumnDescriptor: resolveNanoidColumnDescriptor\n\t},\n\tuuidv7: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 36 }\n\t\t}\n\t},\n\tuuidv4: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 36 }\n\t\t}\n\t},\n\tcuid2: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 24 }\n\t\t}\n\t},\n\tksuid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 27 }\n\t\t}\n\t}\n};\nconst builtinGeneratorRegistryMetadata = builtinGeneratorIds.map((id) => ({\n\tid,\n\tapplicableCodecIds: builtinGeneratorMetadataById[id].applicableCodecIds\n}));\nfunction resolveBuiltinGeneratedColumnDescriptor(input) {\n\tconst metadata = builtinGeneratorMetadataById[input.id];\n\tif (metadata.resolveGeneratedColumnDescriptor) return metadata.resolveGeneratedColumnDescriptor(input.params);\n\treturn metadata.generatedColumnDescriptor;\n}\nfunction createGeneratedSpec(id, options) {\n\tconst params = options;\n\tconst resolvedDescriptor = resolveBuiltinGeneratedColumnDescriptor({\n\t\tid,\n\t\t...ifDefined(\"params\", params)\n\t});\n\treturn {\n\t\ttype: resolvedDescriptor.type,\n\t\tnullable: false,\n\t\t...ifDefined(\"typeParams\", resolvedDescriptor.typeParams),\n\t\tgenerated: {\n\t\t\tkind: \"generator\",\n\t\t\tid,\n\t\t\t...ifDefined(\"params\", params)\n\t\t}\n\t};\n}\nconst ulid = (options) => createGeneratedSpec(\"ulid\", options);\nconst nanoid = (options) => createGeneratedSpec(\"nanoid\", options);\nconst uuidv7 = (options) => createGeneratedSpec(\"uuidv7\", options);\nconst uuidv4 = (options) => createGeneratedSpec(\"uuidv4\", options);\nconst cuid2 = (options) => createGeneratedSpec(\"cuid2\", options);\nconst ksuid = (options) => createGeneratedSpec(\"ksuid\", options);\n\n//#endregion\nexport { builtinGeneratorIds, builtinGeneratorRegistryMetadata, cuid2, ksuid, nanoid, resolveBuiltinGeneratedColumnDescriptor, ulid, uuidv4, uuidv7 };\n//# sourceMappingURL=index.mjs.map","import { i as quoteIdentifier, n as escapeLiteral, r as qualifyName, t as SqlEscapeError } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { n as pgEnumControlHooks, t as postgresAdapterDescriptorMeta } from \"./descriptor-meta-DemWrTfB.mjs\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\nimport { builtinGeneratorRegistryMetadata, resolveBuiltinGeneratedColumnDescriptor } from \"@prisma-next/ids\";\n\n//#region src/core/default-normalizer.ts\n/**\n* Pre-compiled regex patterns for performance.\n* These are compiled once at module load time rather than on each function call.\n*/\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n/**\n* Returns the canonical expression for a timestamp default function, or undefined\n* if the expression is not a recognized timestamp default.\n*\n* Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n* - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n* - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n*\n* These are semantically different in Postgres: now() returns the transaction\n* start time (constant within a transaction), while clock_timestamp() returns\n* the actual wall-clock time (can differ across rows in a single INSERT).\n*/\nfunction canonicalizeTimestampDefault(expr) {\n\tif (NOW_FUNCTION_PATTERN.test(expr)) return \"now()\";\n\tif (CLOCK_TIMESTAMP_PATTERN.test(expr)) return \"clock_timestamp()\";\n\tif (!TIMESTAMP_CAST_SUFFIX.test(expr)) return void 0;\n\tlet inner = expr.replace(TIMESTAMP_CAST_SUFFIX, \"\").trim();\n\tif (inner.startsWith(\"(\") && inner.endsWith(\")\")) inner = inner.slice(1, -1).trim();\n\tif (NOW_FUNCTION_PATTERN.test(inner)) return \"now()\";\n\tif (CLOCK_TIMESTAMP_PATTERN.test(inner)) return \"clock_timestamp()\";\n\tinner = inner.replace(TEXT_CAST_SUFFIX, \"\").trim();\n\tif (NOW_LITERAL_PATTERN.test(inner)) return \"now()\";\n}\n/**\n* Parses a raw Postgres column default expression into a normalized ColumnDefault.\n* This enables semantic comparison between contract defaults and introspected schema defaults.\n*\n* Used by the migration diff layer to normalize raw database defaults during comparison,\n* keeping the introspection layer focused on faithful data capture.\n*\n* @param rawDefault - Raw default expression from information_schema.columns.column_default\n* @param nativeType - Native column type, used for type-aware parsing (bigint tagging, JSON detection)\n* @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n*/\nfunction parsePostgresDefault(rawDefault, nativeType) {\n\tconst trimmed = rawDefault.trim();\n\tconst normalizedType = nativeType?.toLowerCase();\n\tconst isBigInt = normalizedType === \"bigint\" || normalizedType === \"int8\";\n\tif (NEXTVAL_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"autoincrement()\"\n\t};\n\tconst canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n\tif (canonicalTimestamp) return {\n\t\tkind: \"function\",\n\t\texpression: canonicalTimestamp\n\t};\n\tif (UUID_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (UUID_OSSP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (NULL_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: null\n\t};\n\tif (TRUE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: true\n\t};\n\tif (FALSE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: false\n\t};\n\tif (NUMERIC_PATTERN.test(trimmed)) {\n\t\tconst num = Number(trimmed);\n\t\tif (!Number.isFinite(num)) return void 0;\n\t\tif (isBigInt && !Number.isSafeInteger(num)) return {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: trimmed\n\t\t};\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: num\n\t\t};\n\t}\n\tconst stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n\tif (stringMatch?.[1] !== void 0) {\n\t\tconst unescaped = stringMatch[1].replace(/''/g, \"'\");\n\t\tif (normalizedType === \"json\" || normalizedType === \"jsonb\") try {\n\t\t\treturn {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: JSON.parse(unescaped)\n\t\t\t};\n\t\t} catch {}\n\t\tif (isBigInt && NUMERIC_PATTERN.test(unescaped)) {\n\t\t\tconst num = Number(unescaped);\n\t\t\tif (Number.isSafeInteger(num)) return {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: num\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: unescaped\n\t\t\t};\n\t\t}\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* 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 contract - Optional contract 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, _contract, schema = \"public\") {\n\t\tconst [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult, extensionsResult] = await Promise.all([\n\t\t\tdriver.query(`SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`, [schema]),\n\t\t\tdriver.query(`SELECT\n c.table_name,\n column_name,\n data_type,\n udt_name,\n is_nullable,\n character_maximum_length,\n numeric_precision,\n numeric_scale,\n column_default,\n format_type(a.atttypid, a.atttypmod) AS formatted_type\n FROM information_schema.columns c\n JOIN pg_catalog.pg_class cl\n ON cl.relname = c.table_name\n JOIN pg_catalog.pg_namespace ns\n ON ns.nspname = c.table_schema\n AND ns.oid = cl.relnamespace\n JOIN pg_catalog.pg_attribute a\n ON a.attrelid = cl.oid\n AND a.attname = c.column_name\n AND a.attnum > 0\n AND NOT a.attisdropped\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\n ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position,\n ref_ns.nspname AS referenced_table_schema,\n ref_cl.relname AS referenced_table_name,\n ref_att.attname AS referenced_column_name,\n rc.delete_rule,\n rc.update_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n JOIN pg_catalog.pg_constraint pgc\n ON pgc.conname = tc.constraint_name\n AND pgc.connamespace = (\n SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema\n )\n JOIN pg_catalog.pg_class ref_cl\n ON ref_cl.oid = pgc.confrelid\n JOIN pg_catalog.pg_namespace ref_ns\n ON ref_ns.oid = ref_cl.relnamespace\n JOIN pg_catalog.pg_attribute ref_att\n ON ref_att.attrelid = pgc.confrelid\n AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]\n JOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n i.tablename,\n i.indexname,\n ix.indisunique,\n a.attname,\n a.attnum\n FROM pg_indexes i\n JOIN pg_class ic ON ic.relname = i.indexname\n JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1\n JOIN pg_index ix ON ix.indexrelid = ic.oid\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0\n WHERE i.schemaname = $1\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.table_constraints tc\n WHERE tc.table_schema = $1\n AND tc.table_name = i.tablename\n AND tc.constraint_name = i.indexname\n )\n ORDER BY i.tablename, i.indexname, a.attnum`, [schema]),\n\t\t\tdriver.query(`SELECT extname\n FROM pg_extension\n ORDER BY extname`, [])\n\t\t]);\n\t\tconst columnsByTable = groupBy(columnsResult.rows, \"table_name\");\n\t\tconst pksByTable = groupBy(pkResult.rows, \"table_name\");\n\t\tconst fksByTable = groupBy(fkResult.rows, \"table_name\");\n\t\tconst uniquesByTable = groupBy(uniqueResult.rows, \"table_name\");\n\t\tconst indexesByTable = groupBy(indexResult.rows, \"tablename\");\n\t\tconst pkConstraintsByTable = /* @__PURE__ */ new Map();\n\t\tfor (const row of pkResult.rows) {\n\t\t\tlet constraints = pkConstraintsByTable.get(row.table_name);\n\t\t\tif (!constraints) {\n\t\t\t\tconstraints = /* @__PURE__ */ new Set();\n\t\t\t\tpkConstraintsByTable.set(row.table_name, constraints);\n\t\t\t}\n\t\t\tconstraints.add(row.constraint_name);\n\t\t}\n\t\tconst tables = {};\n\t\tfor (const tableRow of tablesResult.rows) {\n\t\t\tconst tableName = tableRow.table_name;\n\t\t\tconst columns = {};\n\t\t\tfor (const colRow of columnsByTable.get(tableName) ?? []) {\n\t\t\t\tlet nativeType = colRow.udt_name;\n\t\t\t\tconst formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;\n\t\t\t\tif (formattedType) nativeType = formattedType;\n\t\t\t\telse if (colRow.data_type === \"character varying\" || colRow.data_type === \"character\") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse if (colRow.data_type === \"numeric\" || colRow.data_type === \"decimal\") if (colRow.numeric_precision && colRow.numeric_scale !== null) nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;\n\t\t\t\telse if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse nativeType = colRow.udt_name || colRow.data_type;\n\t\t\t\tcolumns[colRow.column_name] = {\n\t\t\t\t\tname: colRow.column_name,\n\t\t\t\t\tnativeType,\n\t\t\t\t\tnullable: colRow.is_nullable === \"YES\",\n\t\t\t\t\t...ifDefined(\"default\", colRow.column_default ?? void 0)\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pkRows = [...pksByTable.get(tableName) ?? []];\n\t\t\tconst primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);\n\t\t\tconst primaryKey = primaryKeyColumns.length > 0 ? {\n\t\t\t\tcolumns: primaryKeyColumns,\n\t\t\t\t...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}\n\t\t\t} : void 0;\n\t\t\tconst foreignKeysMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const fkRow of fksByTable.get(tableName) ?? []) {\n\t\t\t\tconst existing = foreignKeysMap.get(fkRow.constraint_name);\n\t\t\t\tif (existing) {\n\t\t\t\t\texisting.columns.push(fkRow.column_name);\n\t\t\t\t\texisting.referencedColumns.push(fkRow.referenced_column_name);\n\t\t\t\t} else foreignKeysMap.set(fkRow.constraint_name, {\n\t\t\t\t\tcolumns: [fkRow.column_name],\n\t\t\t\t\treferencedTable: fkRow.referenced_table_name,\n\t\t\t\t\treferencedColumns: [fkRow.referenced_column_name],\n\t\t\t\t\tname: fkRow.constraint_name,\n\t\t\t\t\tdeleteRule: fkRow.delete_rule,\n\t\t\t\t\tupdateRule: fkRow.update_rule\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({\n\t\t\t\tcolumns: Object.freeze([...fk.columns]),\n\t\t\t\treferencedTable: fk.referencedTable,\n\t\t\t\treferencedColumns: Object.freeze([...fk.referencedColumns]),\n\t\t\t\tname: fk.name,\n\t\t\t\t...ifDefined(\"onDelete\", mapReferentialAction(fk.deleteRule)),\n\t\t\t\t...ifDefined(\"onUpdate\", mapReferentialAction(fk.updateRule))\n\t\t\t}));\n\t\t\tconst pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();\n\t\t\tconst uniquesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const uniqueRow of uniquesByTable.get(tableName) ?? []) {\n\t\t\t\tif (pkConstraints.has(uniqueRow.constraint_name)) continue;\n\t\t\t\tconst existing = uniquesMap.get(uniqueRow.constraint_name);\n\t\t\t\tif (existing) existing.columns.push(uniqueRow.column_name);\n\t\t\t\telse uniquesMap.set(uniqueRow.constraint_name, {\n\t\t\t\t\tcolumns: [uniqueRow.column_name],\n\t\t\t\t\tname: uniqueRow.constraint_name\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst uniques = Array.from(uniquesMap.values()).map((uq) => ({\n\t\t\t\tcolumns: Object.freeze([...uq.columns]),\n\t\t\t\tname: uq.name\n\t\t\t}));\n\t\t\tconst indexesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const idxRow of indexesByTable.get(tableName) ?? []) {\n\t\t\t\tif (!idxRow.attname) continue;\n\t\t\t\tconst existing = indexesMap.get(idxRow.indexname);\n\t\t\t\tif (existing) existing.columns.push(idxRow.attname);\n\t\t\t\telse indexesMap.set(idxRow.indexname, {\n\t\t\t\t\tcolumns: [idxRow.attname],\n\t\t\t\t\tname: idxRow.indexname,\n\t\t\t\t\tunique: idxRow.indisunique\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst indexes = Array.from(indexesMap.values()).map((idx) => ({\n\t\t\t\tcolumns: Object.freeze([...idx.columns]),\n\t\t\t\tname: idx.name,\n\t\t\t\tunique: idx.unique\n\t\t\t}));\n\t\t\ttables[tableName] = {\n\t\t\t\tname: tableName,\n\t\t\t\tcolumns,\n\t\t\t\t...ifDefined(\"primaryKey\", primaryKey),\n\t\t\t\tforeignKeys,\n\t\t\t\tuniques,\n\t\t\t\tindexes\n\t\t\t};\n\t\t}\n\t\tconst dependencies = extensionsResult.rows.map((row) => ({ id: `postgres.extension.${row.extname}` }));\n\t\tconst storageTypes = await pgEnumControlHooks.introspectTypes?.({\n\t\t\tdriver,\n\t\t\tschemaName: schema\n\t\t}) ?? {};\n\t\treturn {\n\t\t\ttables,\n\t\t\tdependencies,\n\t\t\tannotations: { pg: {\n\t\t\t\tschema,\n\t\t\t\tversion: await this.getPostgresVersion(driver),\n\t\t\t\t...ifDefined(\"storageTypes\", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)\n\t\t\t} }\n\t\t};\n\t}\n\t/**\n\t* Gets the Postgres version from the database.\n\t*/\n\tasync getPostgresVersion(driver) {\n\t\treturn ((await driver.query(\"SELECT version() AS version\", [])).rows[0]?.version ?? \"\").match(/PostgreSQL (\\d+\\.\\d+)/)?.[1] ?? \"unknown\";\n\t}\n};\n/**\n* Pre-computed lookup map for simple prefix-based type normalization.\n* Maps short Postgres type names to their canonical SQL names.\n* Using a Map for O(1) lookup instead of multiple startsWith checks.\n*/\nconst TYPE_PREFIX_MAP = new Map([\n\t[\"varchar\", \"character varying\"],\n\t[\"bpchar\", \"character\"],\n\t[\"varbit\", \"bit varying\"]\n]);\n/**\n* Normalizes a Postgres schema native type to its canonical form for comparison.\n*\n* Uses a pre-computed lookup map for simple prefix replacements (O(1))\n* and handles complex temporal type normalization separately.\n*/\nfunction normalizeSchemaNativeType(nativeType) {\n\tconst trimmed = nativeType.trim();\n\tfor (const [prefix, replacement] of TYPE_PREFIX_MAP) if (trimmed.startsWith(prefix)) return replacement + trimmed.slice(prefix.length);\n\tif (trimmed.includes(\" with time zone\")) {\n\t\tif (trimmed.startsWith(\"timestamp\")) return `timestamptz${trimmed.slice(9).replace(\" with time zone\", \"\")}`;\n\t\tif (trimmed.startsWith(\"time\")) return `timetz${trimmed.slice(4).replace(\" with time zone\", \"\")}`;\n\t}\n\tif (trimmed.includes(\" without time zone\")) return trimmed.replace(\" without time zone\", \"\");\n\treturn trimmed;\n}\nfunction normalizeFormattedType(formattedType, dataType, udtName) {\n\tif (formattedType === \"integer\") return \"int4\";\n\tif (formattedType === \"smallint\") return \"int2\";\n\tif (formattedType === \"bigint\") return \"int8\";\n\tif (formattedType === \"real\") return \"float4\";\n\tif (formattedType === \"double precision\") return \"float8\";\n\tif (formattedType === \"boolean\") return \"bool\";\n\tif (formattedType.startsWith(\"varchar\")) return formattedType.replace(\"varchar\", \"character varying\");\n\tif (formattedType.startsWith(\"bpchar\")) return formattedType.replace(\"bpchar\", \"character\");\n\tif (formattedType.startsWith(\"varbit\")) return formattedType.replace(\"varbit\", \"bit varying\");\n\tif (dataType === \"timestamp with time zone\" || udtName === \"timestamptz\") return formattedType.replace(\"timestamp\", \"timestamptz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"timestamp without time zone\" || udtName === \"timestamp\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (dataType === \"time with time zone\" || udtName === \"timetz\") return formattedType.replace(\"time\", \"timetz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"time without time zone\" || udtName === \"time\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (formattedType.startsWith(\"\\\"\") && formattedType.endsWith(\"\\\"\")) return formattedType.slice(1, -1);\n\treturn formattedType;\n}\nconst PG_REFERENTIAL_ACTION_MAP = {\n\t\"NO ACTION\": \"noAction\",\n\tRESTRICT: \"restrict\",\n\tCASCADE: \"cascade\",\n\t\"SET NULL\": \"setNull\",\n\t\"SET DEFAULT\": \"setDefault\"\n};\n/**\n* Maps a Postgres referential action rule to the canonical SqlReferentialAction.\n* Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.\n* Throws for unrecognized rules to prevent silent data loss.\n*/\nfunction mapReferentialAction(rule) {\n\tconst mapped = PG_REFERENTIAL_ACTION_MAP[rule];\n\tif (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: \"${rule}\". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);\n\tif (mapped === \"noAction\") return void 0;\n\treturn mapped;\n}\n/**\n* Groups an array of objects by a specified key.\n* Returns a Map for O(1) lookup by group key.\n*/\nfunction groupBy(items, key) {\n\tconst map = /* @__PURE__ */ new Map();\n\tfor (const item of items) {\n\t\tconst groupKey = item[key];\n\t\tlet group = map.get(groupKey);\n\t\tif (!group) {\n\t\t\tgroup = [];\n\t\t\tmap.set(groupKey, group);\n\t\t}\n\t\tgroup.push(item);\n\t}\n\treturn map;\n}\n\n//#endregion\n//#region src/core/control-mutation-defaults.ts\nfunction invalidArgumentDiagnostic(input) {\n\treturn {\n\t\tok: false,\n\t\tdiagnostic: {\n\t\t\tcode: \"PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT\",\n\t\t\tmessage: input.message,\n\t\t\tsourceId: input.context.sourceId,\n\t\t\tspan: input.span\n\t\t}\n\t};\n}\nfunction executionGenerator(id, params) {\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"execution\",\n\t\t\tgenerated: {\n\t\t\t\tkind: \"generator\",\n\t\t\t\tid,\n\t\t\t\t...params ? { params } : {}\n\t\t\t}\n\t\t}\n\t};\n}\nfunction expectNoArgs(input) {\n\tif (input.call.args.length === 0) return;\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: `Default function \"${input.call.name}\" does not accept arguments. Use ${input.usage}.`\n\t});\n}\nfunction parseIntegerArgument(raw) {\n\tconst trimmed = raw.trim();\n\tif (!/^-?\\d+$/.test(trimmed)) return;\n\tconst value = Number(trimmed);\n\tif (!Number.isInteger(value)) return;\n\treturn value;\n}\nfunction parseStringLiteral(raw) {\n\tconst match = raw.trim().match(/^(['\"])(.*)\\1$/s);\n\tif (!match) return;\n\treturn match[2] ?? \"\";\n}\nfunction lowerAutoincrement(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`autoincrement()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: \"autoincrement()\"\n\t\t\t}\n\t\t}\n\t};\n}\nfunction lowerNow(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`now()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: \"now()\"\n\t\t\t}\n\t\t}\n\t};\n}\nfunction lowerUuid(input) {\n\tif (input.call.args.length === 0) return executionGenerator(\"uuidv4\");\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"uuid\\\" accepts at most one version argument: `uuid()`, `uuid(4)`, or `uuid(7)`.\"\n\t});\n\tconst version = parseIntegerArgument(input.call.args[0]?.raw ?? \"\");\n\tif (version === 4) return executionGenerator(\"uuidv4\");\n\tif (version === 7) return executionGenerator(\"uuidv7\");\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"uuid\\\" supports only `uuid()`, `uuid(4)`, or `uuid(7)` in SQL PSL provider v1.\"\n\t});\n}\nfunction lowerCuid(input) {\n\tif (input.call.args.length === 0) return {\n\t\tok: false,\n\t\tdiagnostic: {\n\t\t\tcode: \"PSL_UNKNOWN_DEFAULT_FUNCTION\",\n\t\t\tmessage: \"Default function \\\"cuid()\\\" is not supported in SQL PSL provider v1. Use `cuid(2)` instead.\",\n\t\t\tsourceId: input.context.sourceId,\n\t\t\tspan: input.call.span\n\t\t}\n\t};\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"cuid\\\" accepts exactly one version argument: `cuid(2)`.\"\n\t});\n\tif (parseIntegerArgument(input.call.args[0]?.raw ?? \"\") === 2) return executionGenerator(\"cuid2\");\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"cuid\\\" supports only `cuid(2)` in SQL PSL provider v1.\"\n\t});\n}\nfunction lowerUlid(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`ulid()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn executionGenerator(\"ulid\");\n}\nfunction lowerNanoid(input) {\n\tif (input.call.args.length === 0) return executionGenerator(\"nanoid\");\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"nanoid\\\" accepts at most one size argument: `nanoid()` or `nanoid(<2-255>)`.\"\n\t});\n\tconst size = parseIntegerArgument(input.call.args[0]?.raw ?? \"\");\n\tif (size !== void 0 && size >= 2 && size <= 255) return executionGenerator(\"nanoid\", { size });\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"nanoid\\\" size argument must be an integer between 2 and 255.\"\n\t});\n}\nfunction lowerDbgenerated(input) {\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" requires exactly one string argument: `dbgenerated(\\\"...\\\")`.\"\n\t});\n\tconst rawExpression = parseStringLiteral(input.call.args[0]?.raw ?? \"\");\n\tif (rawExpression === void 0) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" argument must be a string literal.\"\n\t});\n\tif (rawExpression.trim().length === 0) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" argument cannot be empty.\"\n\t});\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: rawExpression\n\t\t\t}\n\t\t}\n\t};\n}\nconst postgresDefaultFunctionRegistryEntries = [\n\t[\"autoincrement\", {\n\t\tlower: lowerAutoincrement,\n\t\tusageSignatures: [\"autoincrement()\"]\n\t}],\n\t[\"now\", {\n\t\tlower: lowerNow,\n\t\tusageSignatures: [\"now()\"]\n\t}],\n\t[\"uuid\", {\n\t\tlower: lowerUuid,\n\t\tusageSignatures: [\n\t\t\t\"uuid()\",\n\t\t\t\"uuid(4)\",\n\t\t\t\"uuid(7)\"\n\t\t]\n\t}],\n\t[\"cuid\", {\n\t\tlower: lowerCuid,\n\t\tusageSignatures: [\"cuid(2)\"]\n\t}],\n\t[\"ulid\", {\n\t\tlower: lowerUlid,\n\t\tusageSignatures: [\"ulid()\"]\n\t}],\n\t[\"nanoid\", {\n\t\tlower: lowerNanoid,\n\t\tusageSignatures: [\"nanoid()\", \"nanoid(<2-255>)\"]\n\t}],\n\t[\"dbgenerated\", {\n\t\tlower: lowerDbgenerated,\n\t\tusageSignatures: [\"dbgenerated(\\\"...\\\")\"]\n\t}]\n];\nconst postgresScalarTypeDescriptors = new Map([\n\t[\"String\", \"pg/text@1\"],\n\t[\"Boolean\", \"pg/bool@1\"],\n\t[\"Int\", \"pg/int4@1\"],\n\t[\"BigInt\", \"pg/int8@1\"],\n\t[\"Float\", \"pg/float8@1\"],\n\t[\"Decimal\", \"pg/numeric@1\"],\n\t[\"DateTime\", \"pg/timestamptz@1\"],\n\t[\"Json\", \"pg/jsonb@1\"],\n\t[\"Bytes\", \"pg/bytea@1\"]\n]);\nfunction createPostgresDefaultFunctionRegistry() {\n\treturn new Map(postgresDefaultFunctionRegistryEntries);\n}\nfunction createPostgresMutationDefaultGeneratorDescriptors() {\n\treturn builtinGeneratorRegistryMetadata.map(({ id, applicableCodecIds }) => ({\n\t\tid,\n\t\tapplicableCodecIds,\n\t\tresolveGeneratedColumnDescriptor: ({ generated }) => {\n\t\t\tif (generated.kind !== \"generator\" || generated.id !== id) return;\n\t\t\tconst descriptor = resolveBuiltinGeneratedColumnDescriptor({\n\t\t\t\tid,\n\t\t\t\t...generated.params ? { params: generated.params } : {}\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tcodecId: descriptor.type.codecId,\n\t\t\t\tnativeType: descriptor.type.nativeType,\n\t\t\t\t...descriptor.type.typeRef ? { typeRef: descriptor.type.typeRef } : {},\n\t\t\t\t...descriptor.typeParams ? { typeParams: descriptor.typeParams } : {}\n\t\t\t};\n\t\t}\n\t}));\n}\nfunction createPostgresScalarTypeDescriptors() {\n\treturn new Map(postgresScalarTypeDescriptors);\n}\n\n//#endregion\n//#region src/exports/control.ts\nconst postgresAdapterDescriptor = {\n\t...postgresAdapterDescriptorMeta,\n\tscalarTypeDescriptors: createPostgresScalarTypeDescriptors(),\n\tcontrolMutationDefaults: {\n\t\tdefaultFunctionRegistry: createPostgresDefaultFunctionRegistry(),\n\t\tgeneratorDescriptors: createPostgresMutationDefaultGeneratorDescriptors()\n\t},\n\tcreate() {\n\t\treturn new PostgresControlAdapter();\n\t}\n};\nvar control_default = postgresAdapterDescriptor;\n\n//#endregion\nexport { SqlEscapeError, control_default as default, escapeLiteral, normalizeSchemaNativeType, parsePostgresDefault, qualifyName, quoteIdentifier };\n//# sourceMappingURL=control.mjs.map","/**\n * Migration strategies for the descriptor-based planner.\n *\n * Each strategy examines the issue list, consumes issues it handles,\n * and returns the ops to handle them. The planner chains strategies,\n * then handles whatever's left with default issue-to-descriptor mapping.\n *\n * Different strategy sets are used for different contexts:\n * - `migration plan`: data-safe strategies (dataTransform for NOT NULL, type changes, etc.)\n * - `db update`: dev-push strategies (temp defaults, destructive type changes, no data transforms)\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport {\n addColumn,\n addEnumValues,\n alterColumnType,\n createEnumType,\n dataTransform,\n dropEnumType,\n type PostgresMigrationOpDescriptor,\n renameType,\n setNotNull,\n TODO,\n} from './operation-descriptors';\n\n// ============================================================================\n// Strategy types\n// ============================================================================\n\n/** Context passed to each migration strategy — the from/to contracts for the migration. */\nexport interface StrategyContext {\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n}\n\n/**\n * A migration strategy examines schema issues, consumes the ones it handles,\n * and returns the descriptor ops to address them. Returns `'no_match'` if\n * none of the issues are relevant. The planner chains strategies in order —\n * earlier strategies consume issues before later ones see them.\n */\nexport type MigrationStrategy = (\n issues: readonly SchemaIssue[],\n context: StrategyContext,\n) =>\n | { kind: 'match'; issues: readonly SchemaIssue[]; ops: readonly PostgresMigrationOpDescriptor[] }\n | { kind: 'no_match' };\n\n// ============================================================================\n// Recipes\n// ============================================================================\n\nconst REBUILD_SUFFIX = '__prisma_next_new';\n\n/**\n * Produces the descriptor sequence for rebuilding a Postgres enum type:\n * createEnumType(temp, values) → alterColumnType(USING cast) per column → dropEnumType(old) → renameType(temp, old)\n *\n * Used by the enum change strategy for value removal and reorder scenarios.\n * Finds all columns referencing the enum via `typeRef` in the destination contract.\n */\nfunction enumRebuildRecipe(\n typeName: string,\n ctx: StrategyContext,\n): readonly PostgresMigrationOpDescriptor[] {\n const toType = ctx.toContract.storage.types?.[typeName];\n if (!toType) return [];\n const nativeType = toType.nativeType;\n const desiredValues = (toType.typeParams['values'] ?? []) as readonly string[];\n const tempName = `${nativeType}${REBUILD_SUFFIX}`;\n\n const columnRefs: { table: string; column: string }[] = [];\n for (const [tableName, table] of Object.entries(ctx.toContract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeRef === typeName) {\n columnRefs.push({ table: tableName, column: columnName });\n }\n }\n }\n\n return [\n createEnumType(tempName, desiredValues),\n ...columnRefs.map((ref) =>\n alterColumnType(ref.table, ref.column, {\n toType: tempName,\n using: `${ref.column}::text::${tempName}`,\n }),\n ),\n dropEnumType(nativeType),\n renameType(tempName, nativeType),\n ];\n}\n\n// ============================================================================\n// Data-safe strategies (for `migration plan`)\n// ============================================================================\n\n/**\n * NOT NULL backfill strategy.\n *\n * When a missing column is NOT NULL without a default, the planner can't just\n * add it — existing rows would violate the constraint. Instead, emit:\n * addColumn(nullable) → dataTransform (user fills in backfill) → setNotNull\n */\nexport const notNullBackfillStrategy: MigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const ops: PostgresMigrationOpDescriptor[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'missing_column' || !issue.table || !issue.column) continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column) continue;\n if (column.nullable === true || column.default !== undefined) continue;\n\n matched.push(issue);\n ops.push(\n addColumn(issue.table, issue.column, { nullable: true }),\n dataTransform(`backfill-${issue.table}-${issue.column}`, {\n check: TODO,\n run: TODO,\n }),\n setNotNull(issue.table, issue.column),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n ops,\n };\n};\n\n/**\n * Unsafe type change strategy.\n *\n * Safe widenings (int4 → int8) emit alterColumnType directly.\n * Unsafe changes emit dataTransform for user to handle conversion.\n */\nexport const typeChangeStrategy: MigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const ops: PostgresMigrationOpDescriptor[] = [];\n\n const SAFE_WIDENINGS = new Set(['int2→int4', 'int2→int8', 'int4→int8', 'float4→float8']);\n function isSafeWidening(fromType: string, toType: string): boolean {\n return SAFE_WIDENINGS.has(`${fromType}→${toType}`);\n }\n\n for (const issue of issues) {\n if (issue.kind !== 'type_mismatch') continue;\n if (!issue.table || !issue.column) continue;\n const fromColumn = ctx.fromContract?.storage.tables[issue.table]?.columns[issue.column];\n const toColumn = ctx.toContract?.storage.tables[issue.table]?.columns[issue.column];\n if (!fromColumn || !toColumn) continue;\n const fromType = fromColumn.nativeType;\n const toType = toColumn.nativeType;\n if (fromType === toType) continue;\n matched.push(issue);\n if (isSafeWidening(fromType, toType)) {\n ops.push(alterColumnType(issue.table, issue.column));\n } else {\n ops.push(\n dataTransform(`typechange-${issue.table}-${issue.column}`, {\n check: TODO,\n run: TODO,\n }),\n alterColumnType(issue.table, issue.column),\n );\n }\n }\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n ops,\n };\n};\n\n/**\n * Nullable → NOT NULL tightening strategy.\n *\n * When an existing column changes from nullable to NOT NULL, existing rows\n * may have NULLs that violate the constraint. Emit:\n * dataTransform (user fills in NULL handling) → setNotNull\n */\nexport const nullableTighteningStrategy: MigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const ops: PostgresMigrationOpDescriptor[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'nullability_mismatch' || !issue.table || !issue.column) continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column) continue;\n if (column.nullable === true) continue;\n\n matched.push(issue);\n ops.push(\n dataTransform(`handle-nulls-${issue.table}-${issue.column}`, {\n check: TODO,\n run: TODO,\n }),\n setNotNull(issue.table, issue.column),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n ops,\n };\n};\n\n/**\n * Enum value change strategy.\n *\n * When enum values change between contracts:\n * - Add only → addEnumValues\n * - Reorder (same values, different order) → rebuild recipe (no data transform)\n * - Removal → dataTransform (user migrates rows) + rebuild recipe\n */\nexport const enumChangeStrategy: MigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const ops: PostgresMigrationOpDescriptor[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'enum_values_changed') continue;\n matched.push(issue);\n\n if (issue.removedValues.length > 0) {\n ops.push(\n dataTransform(`migrate-${issue.typeName}-values`, { check: TODO, run: TODO }),\n ...enumRebuildRecipe(issue.typeName, ctx),\n );\n } else if (issue.addedValues.length === 0) {\n // Reorder only — rebuild without data transform\n ops.push(...enumRebuildRecipe(issue.typeName, ctx));\n } else {\n ops.push(addEnumValues(issue.typeName, issue.addedValues));\n }\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n ops,\n };\n};\n\n/** Default strategy set for `migration plan` — data-safe, requires user input for destructive changes. */\nexport const migrationPlanStrategies: readonly MigrationStrategy[] = [\n enumChangeStrategy,\n notNullBackfillStrategy,\n typeChangeStrategy,\n nullableTighteningStrategy,\n];\n","/**\n * Descriptor-based migration planner.\n *\n * Takes schema issues (from verifySqlSchema) and emits PostgresMigrationOpDescriptor[].\n * Migration strategies consume issues they recognize and produce specialized op\n * sequences (e.g., NOT NULL backfill → addColumn(nullable) + dataTransform + setNotNull).\n * Remaining issues get default descriptor mapping.\n *\n * This planner does NOT produce SqlMigrationPlanOperation — that's the resolver's job.\n * The separation means the same descriptors work for both planner-generated and\n * user-authored migrations.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { SqlPlannerConflict } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport {\n addColumn,\n addForeignKey,\n addPrimaryKey,\n addUnique,\n alterColumnType,\n createDependency,\n createEnumType,\n createIndex,\n createTable,\n dropColumn,\n dropConstraint,\n dropDefault,\n dropIndex,\n dropNotNull,\n dropTable,\n type PostgresMigrationOpDescriptor,\n setDefault,\n setNotNull,\n} from './operation-descriptors';\nimport {\n type MigrationStrategy,\n migrationPlanStrategies,\n type StrategyContext,\n} from './planner-strategies';\n\nexport type { MigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // Dependencies and types first\n dependency_missing: 1,\n type_missing: 2,\n type_values_mismatch: 3,\n enum_values_changed: 3,\n\n // Drops (reconciliation — clear the way for creates)\n // FKs dropped first (they depend on other constraints)\n extra_foreign_key: 10,\n extra_unique_constraint: 11,\n extra_primary_key: 12,\n extra_index: 13,\n extra_default: 14,\n extra_column: 15,\n extra_table: 16,\n\n // Tables before columns\n missing_table: 20,\n\n // Columns before constraints\n missing_column: 30,\n\n // Reconciliation alters (on existing objects)\n type_mismatch: 40,\n nullability_mismatch: 41,\n default_missing: 42,\n default_mismatch: 43,\n\n // Constraints after columns exist\n primary_key_mismatch: 50,\n unique_constraint_mismatch: 51,\n index_mismatch: 52,\n foreign_key_mismatch: 60,\n};\n\nfunction issueOrder(issue: SchemaIssue): number {\n return ISSUE_KIND_ORDER[issue.kind] ?? 99;\n}\n\n// ============================================================================\n// Conflict helpers\n// ============================================================================\n\nfunction issueConflict(\n kind: SqlPlannerConflict['kind'],\n summary: string,\n location?: SqlPlannerConflict['location'],\n): SqlPlannerConflict {\n return {\n kind,\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\n// ============================================================================\n// Default issue-to-descriptor mapping\n// ============================================================================\n\nfunction isMissing(issue: SchemaIssue): boolean {\n if (issue.kind === 'enum_values_changed') return false;\n return issue.actual === undefined;\n}\n\nfunction mapIssue(\n issue: SchemaIssue,\n ctx: StrategyContext,\n): Result<readonly PostgresMigrationOpDescriptor[], SqlPlannerConflict> {\n switch (issue.kind) {\n // Additive — missing structures\n case 'missing_table': {\n if (!issue.table)\n return notOk(\n issueConflict('unsupportedOperation', 'Missing table issue has no table name'),\n );\n const contractTable = ctx.toContract.storage.tables[issue.table];\n if (!contractTable) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Table \"${issue.table}\" reported missing but not found in destination contract`,\n ),\n );\n }\n const ops: PostgresMigrationOpDescriptor[] = [createTable(issue.table)];\n for (const index of contractTable.indexes) {\n ops.push(createIndex(issue.table, [...index.columns]));\n }\n const explicitIndexColumnSets = new Set(\n contractTable.indexes.map((idx) => idx.columns.join(',')),\n );\n for (const fk of contractTable.foreignKeys) {\n if (fk.constraint) {\n ops.push(addForeignKey(issue.table, [...fk.columns]));\n }\n if (fk.index && !explicitIndexColumnSets.has(fk.columns.join(','))) {\n ops.push(createIndex(issue.table, [...fk.columns]));\n }\n }\n for (const unique of contractTable.uniques) {\n ops.push(addUnique(issue.table, [...unique.columns]));\n }\n return ok(ops);\n }\n\n case 'missing_column':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Missing column issue has no table/column name'),\n );\n return ok([addColumn(issue.table, issue.column)]);\n\n case 'default_missing':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Default missing issue has no table/column name'),\n );\n return ok([setDefault(issue.table, issue.column)]);\n\n // Destructive — extra structures\n case 'extra_table':\n if (!issue.table)\n return notOk(issueConflict('unsupportedOperation', 'Extra table issue has no table name'));\n return ok([dropTable(issue.table)]);\n\n case 'extra_column':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra column issue has no table/column name'),\n );\n return ok([dropColumn(issue.table, issue.column)]);\n\n case 'extra_index':\n if (!issue.table || !issue.indexOrConstraint)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra index issue has no table/index name'),\n );\n return ok([dropIndex(issue.table, issue.indexOrConstraint)]);\n\n case 'extra_unique_constraint':\n case 'extra_foreign_key':\n case 'extra_primary_key':\n if (!issue.table || !issue.indexOrConstraint)\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n 'Extra constraint issue has no table/constraint name',\n ),\n );\n return ok([dropConstraint(issue.table, issue.indexOrConstraint)]);\n\n case 'extra_default':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra default issue has no table/column name'),\n );\n return ok([dropDefault(issue.table, issue.column)]);\n\n // Nullability changes\n case 'nullability_mismatch': {\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('nullabilityConflict', 'Nullability mismatch has no table/column name'),\n );\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column)\n return notOk(\n issueConflict(\n 'nullabilityConflict',\n `Column \"${issue.table}\".\"${issue.column}\" not found in destination contract`,\n ),\n );\n return ok(\n column.nullable\n ? [dropNotNull(issue.table, issue.column)]\n : [setNotNull(issue.table, issue.column)],\n );\n }\n\n // Type changes\n case 'type_mismatch':\n if (!issue.table || !issue.column)\n return notOk(issueConflict('typeMismatch', 'Type mismatch has no table/column name'));\n return ok([alterColumnType(issue.table, issue.column)]);\n\n // Default changes\n case 'default_mismatch':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Default mismatch has no table/column name'),\n );\n return ok([setDefault(issue.table, issue.column)]);\n\n // Constraints — missing (actual undefined) vs mismatched (actual defined)\n case 'primary_key_mismatch':\n if (!issue.table)\n return notOk(issueConflict('indexIncompatible', 'Primary key issue has no table name'));\n if (isMissing(issue)) return ok([addPrimaryKey(issue.table)]);\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Primary key on \"${issue.table}\" has different columns (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'unique_constraint_mismatch':\n if (!issue.table)\n return notOk(\n issueConflict('indexIncompatible', 'Unique constraint issue has no table name'),\n );\n if (isMissing(issue) && issue.expected) {\n const columns = issue.expected.split(', ');\n return ok([addUnique(issue.table, columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Unique constraint on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'index_mismatch':\n if (!issue.table)\n return notOk(issueConflict('indexIncompatible', 'Index issue has no table name'));\n if (isMissing(issue) && issue.expected) {\n const columns = issue.expected.split(', ');\n return ok([createIndex(issue.table, columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Index on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'foreign_key_mismatch':\n if (!issue.table)\n return notOk(issueConflict('foreignKeyConflict', 'Foreign key issue has no table name'));\n if (isMissing(issue) && issue.expected) {\n const arrowIdx = issue.expected.indexOf(' -> ');\n if (arrowIdx >= 0) {\n const columns = issue.expected.slice(0, arrowIdx).split(', ');\n return ok([addForeignKey(issue.table, columns)]);\n }\n }\n return notOk(\n issueConflict(\n 'foreignKeyConflict',\n `Foreign key on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n // Types\n case 'type_missing': {\n if (!issue.typeName)\n return notOk(issueConflict('unsupportedOperation', 'Type missing issue has no typeName'));\n const typeInstance = ctx.toContract.storage.types?.[issue.typeName];\n if (!typeInstance) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName}\" reported missing but not found in destination contract`,\n ),\n );\n }\n // TODO: codec-specific descriptor dispatch should be driven by a registry, not hardcoded prefix checks\n if (typeInstance.codecId.startsWith('pg/enum')) {\n return ok([createEnumType(issue.typeName)]);\n }\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName}\" uses codec \"${typeInstance.codecId}\" — only enum types are supported by the descriptor planner`,\n ),\n );\n }\n\n case 'type_values_mismatch':\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName ?? 'unknown'}\" values differ — type alteration not yet supported by descriptor planner`,\n ),\n );\n\n // Dependencies\n case 'dependency_missing':\n if (!issue.dependencyId)\n return notOk(\n issueConflict('unsupportedOperation', 'Dependency missing issue has no dependencyId'),\n );\n return ok([createDependency(issue.dependencyId)]);\n default:\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Unhandled issue kind: ${(issue as SchemaIssue).kind}`,\n ),\n );\n }\n}\n\n// ============================================================================\n// Planner entry point\n// ============================================================================\n\nexport interface DescriptorPlannerOptions {\n readonly issues: readonly SchemaIssue[];\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly strategies?: readonly MigrationStrategy[];\n}\n\nexport interface DescriptorPlannerValue {\n readonly descriptors: readonly PostgresMigrationOpDescriptor[];\n readonly needsDataMigration: boolean;\n}\n\nexport function planDescriptors(\n options: DescriptorPlannerOptions,\n): Result<DescriptorPlannerValue, readonly SqlPlannerConflict[]> {\n const context: StrategyContext = {\n toContract: options.toContract,\n fromContract: options.fromContract,\n };\n\n const strategies = options.strategies ?? migrationPlanStrategies;\n\n // Phase 1: Pattern matching — consume recognized issues\n let remaining = options.issues;\n const patternOps: PostgresMigrationOpDescriptor[] = [];\n\n for (const strategy of strategies) {\n const result = strategy(remaining, context);\n if (result.kind === 'match') {\n remaining = result.issues;\n patternOps.push(...result.ops);\n }\n }\n\n // Phase 2: Sort remaining issues by dependency order\n const sorted = [...remaining].sort((a, b) => issueOrder(a) - issueOrder(b));\n\n // Phase 3: Map remaining issues to descriptors, collecting conflicts\n const defaultOps: PostgresMigrationOpDescriptor[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n\n for (const issue of sorted) {\n const result = mapIssue(issue, context);\n if (result.ok) {\n defaultOps.push(...result.value);\n } else {\n conflicts.push(result.failure);\n }\n }\n\n if (conflicts.length > 0) {\n return notOk(conflicts);\n }\n\n // Phase 4: Order descriptors by operation kind\n const depOps = defaultOps.filter(\n (op) =>\n op.kind === 'createDependency' ||\n op.kind === 'createEnumType' ||\n op.kind === 'addEnumValues' ||\n op.kind === 'dropEnumType' ||\n op.kind === 'renameType',\n );\n const dropOps = defaultOps.filter(\n (op) =>\n op.kind === 'dropTable' ||\n op.kind === 'dropColumn' ||\n op.kind === 'dropConstraint' ||\n op.kind === 'dropIndex' ||\n op.kind === 'dropDefault',\n );\n const tableOps = defaultOps.filter((op) => op.kind === 'createTable');\n const columnOps = defaultOps.filter((op) => op.kind === 'addColumn');\n const alterOps = defaultOps.filter(\n (op) =>\n op.kind === 'alterColumnType' ||\n op.kind === 'setNotNull' ||\n op.kind === 'dropNotNull' ||\n op.kind === 'setDefault',\n );\n const constraintOps = defaultOps.filter(\n (op) =>\n op.kind === 'addPrimaryKey' ||\n op.kind === 'addUnique' ||\n op.kind === 'createIndex' ||\n op.kind === 'addForeignKey',\n );\n\n const descriptors: PostgresMigrationOpDescriptor[] = [\n ...depOps,\n ...dropOps,\n ...tableOps,\n ...columnOps,\n ...patternOps,\n ...alterOps,\n ...constraintOps,\n ];\n\n return ok({\n descriptors,\n needsDataMigration: descriptors.some((op) => op.kind === 'dataTransform'),\n });\n}\n","import { m as PG_JSON_CODEC_ID, p as PG_JSONB_CODEC_ID } from \"./codec-ids-BwjcIf74.mjs\";\nimport { t as codecDefinitions } from \"./codecs-C3wlpdV7.mjs\";\nimport { i as quoteIdentifier, n as escapeLiteral } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { LiteralExpr, createCodecRegistry } from \"@prisma-next/sql-relational-core/ast\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/core/adapter.ts\nconst VECTOR_CODEC_ID = \"pg/vector@1\";\nfunction getCodecParamCast(codecId) {\n\tif (codecId === VECTOR_CODEC_ID) return \"vector\";\n\tif (codecId === PG_JSON_CODEC_ID) return \"json\";\n\tif (codecId === PG_JSONB_CODEC_ID) return \"jsonb\";\n}\nfunction renderTypedParam(index, codecId) {\n\tconst cast = getCodecParamCast(codecId);\n\treturn cast ? `$${index}::${cast}` : `$${index}`;\n}\nconst defaultCapabilities = Object.freeze({\n\tpostgres: {\n\t\torderBy: true,\n\t\tlimit: true,\n\t\tlateral: true,\n\t\tjsonAgg: true,\n\t\treturning: true\n\t},\n\tsql: {\n\t\tenums: true,\n\t\treturning: true,\n\t\tdefaultInInsert: true\n\t}\n});\nconst parameterizedCodecs = Object.values(codecDefinitions).map((definition) => definition.codec).filter((codec$1) => codec$1.paramsSchema !== void 0).map((codec$1) => Object.freeze({\n\tcodecId: codec$1.id,\n\tparamsSchema: codec$1.paramsSchema,\n\t...ifDefined(\"init\", codec$1.init)\n}));\nvar PostgresAdapterImpl = class {\n\tfamilyId = \"sql\";\n\ttargetId = \"postgres\";\n\tprofile;\n\tcodecRegistry = (() => {\n\t\tconst registry = createCodecRegistry();\n\t\tfor (const definition of Object.values(codecDefinitions)) registry.register(definition.codec);\n\t\treturn registry;\n\t})();\n\tconstructor(options) {\n\t\tthis.profile = Object.freeze({\n\t\t\tid: options?.profileId ?? \"postgres/default@1\",\n\t\t\ttarget: \"postgres\",\n\t\t\tcapabilities: defaultCapabilities,\n\t\t\tcodecs: () => this.codecRegistry,\n\t\t\treadMarkerStatement: () => ({\n\t\t\t\tsql: \"select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1\",\n\t\t\t\tparams: [1]\n\t\t\t})\n\t\t});\n\t}\n\tparameterizedCodecs() {\n\t\treturn parameterizedCodecs;\n\t}\n\tlower(ast, context) {\n\t\tconst collectedParamRefs = ast.collectParamRefs();\n\t\tconst paramIndexMap = /* @__PURE__ */ new Map();\n\t\tconst params = [];\n\t\tfor (const ref of collectedParamRefs) {\n\t\t\tif (paramIndexMap.has(ref)) continue;\n\t\t\tparamIndexMap.set(ref, params.length + 1);\n\t\t\tparams.push(ref.value);\n\t\t}\n\t\tlet sql;\n\t\tconst node = ast;\n\t\tswitch (node.kind) {\n\t\t\tcase \"select\":\n\t\t\t\tsql = renderSelect(node, context.contract, paramIndexMap);\n\t\t\t\tbreak;\n\t\t\tcase \"insert\":\n\t\t\t\tsql = renderInsert(node, context.contract, paramIndexMap);\n\t\t\t\tbreak;\n\t\t\tcase \"update\":\n\t\t\t\tsql = renderUpdate(node, context.contract, paramIndexMap);\n\t\t\t\tbreak;\n\t\t\tcase \"delete\":\n\t\t\t\tsql = renderDelete(node, context.contract, paramIndexMap);\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unsupported AST node kind: ${node.kind}`);\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tprofileId: this.profile.id,\n\t\t\tbody: Object.freeze({\n\t\t\t\tsql,\n\t\t\t\tparams\n\t\t\t})\n\t\t});\n\t}\n};\nfunction renderSelect(ast, contract, pim) {\n\treturn [\n\t\t`SELECT ${renderDistinctPrefix(ast.distinct, ast.distinctOn, contract, pim)}${renderProjection(ast.projection, contract, pim)}`,\n\t\t`FROM ${renderSource(ast.from, contract, pim)}`,\n\t\tast.joins?.length ? ast.joins.map((join) => renderJoin(join, contract, pim)).join(\" \") : \"\",\n\t\tast.where ? `WHERE ${renderWhere(ast.where, contract, pim)}` : \"\",\n\t\tast.groupBy?.length ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract, pim)).join(\", \")}` : \"\",\n\t\tast.having ? `HAVING ${renderWhere(ast.having, contract, pim)}` : \"\",\n\t\tast.orderBy?.length ? `ORDER BY ${ast.orderBy.map((order) => {\n\t\t\treturn `${renderExpr(order.expr, contract, pim)} ${order.dir.toUpperCase()}`;\n\t\t}).join(\", \")}` : \"\",\n\t\ttypeof ast.limit === \"number\" ? `LIMIT ${ast.limit}` : \"\",\n\t\ttypeof ast.offset === \"number\" ? `OFFSET ${ast.offset}` : \"\"\n\t].filter((part) => part.length > 0).join(\" \").trim();\n}\nfunction renderProjection(projection, contract, pim) {\n\treturn projection.map((item) => {\n\t\tconst alias = quoteIdentifier(item.alias);\n\t\tif (item.expr.kind === \"literal\") return `${renderLiteral(item.expr)} AS ${alias}`;\n\t\treturn `${renderExpr(item.expr, contract, pim)} AS ${alias}`;\n\t}).join(\", \");\n}\nfunction renderDistinctPrefix(distinct, distinctOn, contract, pim) {\n\tif (distinctOn && distinctOn.length > 0) return `DISTINCT ON (${distinctOn.map((expr) => renderExpr(expr, contract, pim)).join(\", \")}) `;\n\tif (distinct) return \"DISTINCT \";\n\treturn \"\";\n}\nfunction renderSource(source, contract, pim) {\n\tconst node = source;\n\tswitch (node.kind) {\n\t\tcase \"table-source\": {\n\t\t\tconst table = quoteIdentifier(node.name);\n\t\t\tif (!node.alias) return table;\n\t\t\treturn `${table} AS ${quoteIdentifier(node.alias)}`;\n\t\t}\n\t\tcase \"derived-table-source\": return `(${renderSelect(node.query, contract, pim)}) AS ${quoteIdentifier(node.alias)}`;\n\t\tdefault: throw new Error(`Unsupported source node kind: ${node.kind}`);\n\t}\n}\nfunction assertScalarSubquery(query) {\n\tif (query.projection.length !== 1) throw new Error(\"Subquery expressions must project exactly one column\");\n}\nfunction renderSubqueryExpr(expr, contract, pim) {\n\tassertScalarSubquery(expr.query);\n\treturn `(${renderSelect(expr.query, contract, pim)})`;\n}\nfunction renderWhere(expr, contract, pim) {\n\treturn renderExpr(expr, contract, pim);\n}\nfunction renderNullCheck(expr, contract, pim) {\n\tconst rendered = renderExpr(expr.expr, contract, pim);\n\tconst renderedExpr = expr.expr.kind === \"operation\" || expr.expr.kind === \"subquery\" ? `(${rendered})` : rendered;\n\treturn expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;\n}\nfunction renderBinary(expr, contract, pim) {\n\tif (expr.right.kind === \"list\" && expr.right.values.length === 0) {\n\t\tif (expr.op === \"in\") return \"FALSE\";\n\t\tif (expr.op === \"notIn\") return \"TRUE\";\n\t}\n\tconst leftExpr = expr.left;\n\tconst left = renderExpr(leftExpr, contract, pim);\n\tconst leftRendered = leftExpr.kind === \"operation\" || leftExpr.kind === \"subquery\" ? `(${left})` : left;\n\tconst rightNode = expr.right;\n\tlet right;\n\tswitch (rightNode.kind) {\n\t\tcase \"list\":\n\t\t\tright = renderListLiteral(rightNode, pim);\n\t\t\tbreak;\n\t\tcase \"literal\":\n\t\t\tright = renderLiteral(rightNode);\n\t\t\tbreak;\n\t\tcase \"column-ref\":\n\t\t\tright = renderColumn(rightNode);\n\t\t\tbreak;\n\t\tcase \"param-ref\":\n\t\t\tright = renderParamRef(rightNode, pim);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tright = renderExpr(rightNode, contract, pim);\n\t\t\tbreak;\n\t}\n\treturn `${leftRendered} ${{\n\t\teq: \"=\",\n\t\tneq: \"!=\",\n\t\tgt: \">\",\n\t\tlt: \"<\",\n\t\tgte: \">=\",\n\t\tlte: \"<=\",\n\t\tlike: \"LIKE\",\n\t\tilike: \"ILIKE\",\n\t\tin: \"IN\",\n\t\tnotIn: \"NOT IN\"\n\t}[expr.op]} ${right}`;\n}\nfunction renderListLiteral(expr, pim) {\n\tif (expr.values.length === 0) return \"(NULL)\";\n\treturn `(${expr.values.map((v) => {\n\t\tif (v.kind === \"param-ref\") return renderParamRef(v, pim);\n\t\tif (v.kind === \"literal\") return renderLiteral(v);\n\t\treturn renderExpr(v, void 0, pim);\n\t}).join(\", \")})`;\n}\nfunction renderColumn(ref) {\n\tif (ref.table === \"excluded\") return `excluded.${quoteIdentifier(ref.column)}`;\n\treturn `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;\n}\nfunction renderAggregateExpr(expr, contract, pim) {\n\tconst fn = expr.fn.toUpperCase();\n\tif (!expr.expr) return `${fn}(*)`;\n\treturn `${fn}(${renderExpr(expr.expr, contract, pim)})`;\n}\nfunction renderJsonObjectExpr(expr, contract, pim) {\n\treturn `json_build_object(${expr.entries.flatMap((entry) => {\n\t\tconst key = `'${escapeLiteral(entry.key)}'`;\n\t\tif (entry.value.kind === \"literal\") return [key, renderLiteral(entry.value)];\n\t\treturn [key, renderExpr(entry.value, contract, pim)];\n\t}).join(\", \")})`;\n}\nfunction renderOrderByItems(items, contract, pim) {\n\treturn items.map((item) => `${renderExpr(item.expr, contract, pim)} ${item.dir.toUpperCase()}`).join(\", \");\n}\nfunction renderJsonArrayAggExpr(expr, contract, pim) {\n\tconst aggregateOrderBy = expr.orderBy && expr.orderBy.length > 0 ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}` : \"\";\n\tconst aggregated = `json_agg(${renderExpr(expr.expr, contract, pim)}${aggregateOrderBy})`;\n\tif (expr.onEmpty === \"emptyArray\") return `coalesce(${aggregated}, json_build_array())`;\n\treturn aggregated;\n}\nfunction renderExpr(expr, contract, pim) {\n\tconst node = expr;\n\tswitch (node.kind) {\n\t\tcase \"column-ref\": return renderColumn(node);\n\t\tcase \"identifier-ref\": return quoteIdentifier(node.name);\n\t\tcase \"operation\": return renderOperation(node, contract, pim);\n\t\tcase \"subquery\": return renderSubqueryExpr(node, contract, pim);\n\t\tcase \"aggregate\": return renderAggregateExpr(node, contract, pim);\n\t\tcase \"json-object\": return renderJsonObjectExpr(node, contract, pim);\n\t\tcase \"json-array-agg\": return renderJsonArrayAggExpr(node, contract, pim);\n\t\tcase \"binary\": return renderBinary(node, contract, pim);\n\t\tcase \"and\":\n\t\t\tif (node.exprs.length === 0) return \"TRUE\";\n\t\t\treturn `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(\" AND \")})`;\n\t\tcase \"or\":\n\t\t\tif (node.exprs.length === 0) return \"FALSE\";\n\t\t\treturn `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(\" OR \")})`;\n\t\tcase \"exists\": return `${node.notExists ? \"NOT \" : \"\"}EXISTS (${renderSelect(node.subquery, contract, pim)})`;\n\t\tcase \"null-check\": return renderNullCheck(node, contract, pim);\n\t\tcase \"not\": return `NOT (${renderExpr(node.expr, contract, pim)})`;\n\t\tcase \"param-ref\": return renderParamRef(node, pim);\n\t\tcase \"literal\": return renderLiteral(node);\n\t\tcase \"list\": return renderListLiteral(node, pim);\n\t\tdefault: throw new Error(`Unsupported expression node kind: ${node.kind}`);\n\t}\n}\nfunction renderParamRef(ref, pim) {\n\tconst index = pim?.get(ref);\n\tif (index === void 0) throw new Error(\"ParamRef not found in index map\");\n\treturn renderTypedParam(index, ref.codecId);\n}\nfunction renderLiteral(expr) {\n\tif (typeof expr.value === \"string\") return `'${escapeLiteral(expr.value)}'`;\n\tif (typeof expr.value === \"number\" || typeof expr.value === \"boolean\") return String(expr.value);\n\tif (typeof expr.value === \"bigint\") return String(expr.value);\n\tif (expr.value === null) return \"NULL\";\n\tif (expr.value === void 0) return \"NULL\";\n\tif (expr.value instanceof Date) return `'${escapeLiteral(expr.value.toISOString())}'`;\n\tif (Array.isArray(expr.value)) return `ARRAY[${expr.value.map((v) => renderLiteral(new LiteralExpr(v))).join(\", \")}]`;\n\tconst json = JSON.stringify(expr.value);\n\tif (json === void 0) return \"NULL\";\n\treturn `'${escapeLiteral(json)}'`;\n}\nfunction renderOperation(expr, contract, pim) {\n\tconst self = renderExpr(expr.self, contract, pim);\n\tconst args = expr.args.map((arg) => {\n\t\treturn renderExpr(arg, contract, pim);\n\t});\n\tlet result = expr.lowering.template;\n\tresult = result.replace(/\\{\\{self\\}\\}/g, self);\n\tfor (let i = 0; i < args.length; i++) result = result.replace(new RegExp(`\\\\{\\\\{arg${i}\\\\}\\\\}`, \"g\"), args[i] ?? \"\");\n\treturn result;\n}\nfunction renderJoin(join, contract, pim) {\n\treturn `${join.joinType.toUpperCase()} JOIN ${join.lateral ? \"LATERAL \" : \"\"}${renderSource(join.source, contract, pim)} ON ${renderJoinOn(join.on, contract, pim)}`;\n}\nfunction renderJoinOn(on, contract, pim) {\n\tif (on.kind === \"eq-col-join-on\") return `${renderColumn(on.left)} = ${renderColumn(on.right)}`;\n\treturn renderWhere(on, contract, pim);\n}\nfunction getInsertColumnOrder(rows, contract, tableName) {\n\tconst orderedColumns = [];\n\tconst seenColumns = /* @__PURE__ */ new Set();\n\tfor (const row of rows) for (const column of Object.keys(row)) {\n\t\tif (seenColumns.has(column)) continue;\n\t\tseenColumns.add(column);\n\t\torderedColumns.push(column);\n\t}\n\tif (orderedColumns.length > 0) return orderedColumns;\n\treturn Object.keys(contract.storage.tables[tableName]?.columns ?? {});\n}\nfunction renderInsertValue(value, pim) {\n\tif (!value || value.kind === \"default-value\") return \"DEFAULT\";\n\tswitch (value.kind) {\n\t\tcase \"param-ref\": return renderParamRef(value, pim);\n\t\tcase \"column-ref\": return renderColumn(value);\n\t\tdefault: throw new Error(`Unsupported value node in INSERT: ${value.kind}`);\n\t}\n}\nfunction renderInsert(ast, contract, pim) {\n\tconst table = quoteIdentifier(ast.table.name);\n\tconst rows = ast.rows;\n\tif (rows.length === 0) throw new Error(\"INSERT requires at least one row\");\n\tconst hasExplicitValues = rows.some((row) => Object.keys(row).length > 0);\n\treturn `${(() => {\n\t\tif (!hasExplicitValues) {\n\t\t\tif (rows.length === 1) return `INSERT INTO ${table} DEFAULT VALUES`;\n\t\t\tconst defaultColumns = getInsertColumnOrder(rows, contract, ast.table.name);\n\t\t\tif (defaultColumns.length === 0) return `INSERT INTO ${table} VALUES ${rows.map(() => \"()\").join(\", \")}`;\n\t\t\tconst quotedColumns = defaultColumns.map((column) => quoteIdentifier(column));\n\t\t\tconst defaultRow = `(${defaultColumns.map(() => \"DEFAULT\").join(\", \")})`;\n\t\t\treturn `INSERT INTO ${table} (${quotedColumns.join(\", \")}) VALUES ${rows.map(() => defaultRow).join(\", \")}`;\n\t\t}\n\t\tconst columnOrder = getInsertColumnOrder(rows, contract, ast.table.name);\n\t\tconst columns = columnOrder.map((column) => quoteIdentifier(column));\n\t\tconst values = rows.map((row) => {\n\t\t\treturn `(${columnOrder.map((column) => renderInsertValue(row[column], pim)).join(\", \")})`;\n\t\t}).join(\", \");\n\t\treturn `INSERT INTO ${table} (${columns.join(\", \")}) VALUES ${values}`;\n\t})()}${ast.onConflict ? (() => {\n\t\tconst conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));\n\t\tif (conflictColumns.length === 0) throw new Error(\"INSERT onConflict requires at least one conflict column\");\n\t\tconst action = ast.onConflict.action;\n\t\tswitch (action.kind) {\n\t\t\tcase \"do-nothing\": return ` ON CONFLICT (${conflictColumns.join(\", \")}) DO NOTHING`;\n\t\t\tcase \"do-update-set\": {\n\t\t\t\tconst updates = Object.entries(action.set).map(([colName, value]) => {\n\t\t\t\t\tconst target = quoteIdentifier(colName);\n\t\t\t\t\tif (value.kind === \"param-ref\") return `${target} = ${renderParamRef(value, pim)}`;\n\t\t\t\t\treturn `${target} = ${renderColumn(value)}`;\n\t\t\t\t});\n\t\t\t\treturn ` ON CONFLICT (${conflictColumns.join(\", \")}) DO UPDATE SET ${updates.join(\", \")}`;\n\t\t\t}\n\t\t\tdefault: throw new Error(`Unsupported onConflict action: ${action.kind}`);\n\t\t}\n\t})() : \"\"}${ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(\", \")}` : \"\"}`;\n}\nfunction renderUpdate(ast, contract, pim) {\n\tconst table = quoteIdentifier(ast.table.name);\n\tconst setClauses = Object.entries(ast.set).map(([col, val]) => {\n\t\tconst column = quoteIdentifier(col);\n\t\tlet value;\n\t\tswitch (val.kind) {\n\t\t\tcase \"param-ref\":\n\t\t\t\tvalue = renderParamRef(val, pim);\n\t\t\t\tbreak;\n\t\t\tcase \"column-ref\":\n\t\t\t\tvalue = renderColumn(val);\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unsupported value node in UPDATE: ${val.kind}`);\n\t\t}\n\t\treturn `${column} = ${value}`;\n\t});\n\tconst whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : \"\";\n\tconst returningClause = ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(\", \")}` : \"\";\n\treturn `UPDATE ${table} SET ${setClauses.join(\", \")}${whereClause}${returningClause}`;\n}\nfunction renderDelete(ast, contract, pim) {\n\treturn `DELETE FROM ${quoteIdentifier(ast.table.name)}${ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : \"\"}${ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(\", \")}` : \"\"}`;\n}\nfunction createPostgresAdapter(options) {\n\treturn Object.freeze(new PostgresAdapterImpl(options));\n}\n\n//#endregion\nexport { createPostgresAdapter as t };\n//# sourceMappingURL=adapter-7pXt8ej9.mjs.map","import type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\n\nexport type ResolvedColumnTypeMetadata = Pick<\n StorageColumn,\n 'nativeType' | 'codecId' | 'typeParams'\n>;\n\nexport function resolveColumnTypeMetadata(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance>,\n): ResolvedColumnTypeMetadata {\n if (!column.typeRef) {\n return column;\n }\n\n const referencedType = storageTypes[column.typeRef];\n if (!referencedType) {\n return column;\n }\n\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: referencedType.typeParams,\n };\n}\n","import { escapeLiteral, quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\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\n/**\n * When `table` is omitted the check matches by name + schema across all tables.\n * Pass `table` to scope the check to a single table (prevents false matches on\n * identically-named constraints in different tables).\n */\nexport function constraintExistsCheck({\n constraintName,\n schema,\n table,\n exists = true,\n}: {\n constraintName: string;\n schema: string;\n table?: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n const tableFilter = table\n ? `AND c.conrelid = to_regclass(${toRegclassLiteral(schema, table)})`\n : '';\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 ${tableFilter}\n)`;\n}\n\nexport function columnExistsCheck({\n schema,\n table,\n column,\n exists = true,\n}: {\n schema: string;\n table: string;\n column: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? '' : 'NOT ';\n return `SELECT ${existsClause}EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n)`;\n}\n\nexport function columnNullabilityCheck({\n schema,\n table,\n column,\n nullable,\n}: {\n schema: string;\n table: string;\n column: string;\n nullable: boolean;\n}): string {\n const expected = nullable ? 'YES' : 'NO';\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n AND is_nullable = '${expected}'\n)`;\n}\n\nexport function tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nexport function columnHasNoDefaultCheck(opts: {\n schema: string;\n table: string;\n column: string;\n}): string {\n return `SELECT NOT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(opts.schema)}'\n AND table_name = '${escapeLiteral(opts.table)}'\n AND column_name = '${escapeLiteral(opts.column)}'\n AND column_default IS NOT NULL\n)`;\n}\n\nconst FORMAT_TYPE_DISPLAY: ReadonlyMap<string, string> = new Map([\n ['int2', 'smallint'],\n ['int4', 'integer'],\n ['int8', 'bigint'],\n ['float4', 'real'],\n ['float8', 'double precision'],\n ['bool', 'boolean'],\n ['timestamp', 'timestamp without time zone'],\n ['timestamptz', 'timestamp with time zone'],\n ['time', 'time without time zone'],\n ['timetz', 'time with time zone'],\n]);\n\nconst UNQUOTED_POSTGRES_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/;\n\nconst POSTGRES_RESERVED_IDENTIFIER_WORDS = new Set([\n 'all',\n 'analyse',\n 'analyze',\n 'and',\n 'any',\n 'array',\n 'as',\n 'asc',\n 'asymmetric',\n 'authorization',\n 'between',\n 'binary',\n 'both',\n 'case',\n 'cast',\n 'check',\n 'collate',\n 'column',\n 'constraint',\n 'create',\n 'current_catalog',\n 'current_date',\n 'current_role',\n 'current_time',\n 'current_timestamp',\n 'current_user',\n 'default',\n 'deferrable',\n 'desc',\n 'distinct',\n 'do',\n 'else',\n 'end',\n 'except',\n 'false',\n 'fetch',\n 'for',\n 'foreign',\n 'freeze',\n 'from',\n 'full',\n 'grant',\n 'group',\n 'having',\n 'ilike',\n 'in',\n 'initially',\n 'inner',\n 'intersect',\n 'into',\n 'is',\n 'isnull',\n 'join',\n 'lateral',\n 'leading',\n 'left',\n 'like',\n 'limit',\n 'localtime',\n 'localtimestamp',\n 'natural',\n 'not',\n 'notnull',\n 'null',\n 'offset',\n 'on',\n 'only',\n 'or',\n 'order',\n 'outer',\n 'overlaps',\n 'placing',\n 'primary',\n 'references',\n 'right',\n 'select',\n 'session_user',\n 'similar',\n 'some',\n 'symmetric',\n 'table',\n 'then',\n 'to',\n 'trailing',\n 'true',\n 'union',\n 'unique',\n 'user',\n 'using',\n 'variadic',\n 'verbose',\n 'when',\n 'where',\n 'window',\n 'with',\n]);\n\nfunction formatUserDefinedTypeName(identifier: string): string {\n if (\n UNQUOTED_POSTGRES_IDENTIFIER_PATTERN.test(identifier) &&\n !POSTGRES_RESERVED_IDENTIFIER_WORDS.has(identifier)\n ) {\n return identifier;\n }\n\n return quoteIdentifier(identifier);\n}\n\nexport function buildExpectedFormatType(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (resolved.typeParams && resolved.codecId) {\n const hooks = codecHooks.get(resolved.codecId);\n if (hooks?.expandNativeType) {\n return hooks.expandNativeType({\n nativeType: resolved.nativeType,\n codecId: resolved.codecId,\n typeParams: resolved.typeParams,\n });\n }\n }\n\n if (column.typeRef) {\n return formatUserDefinedTypeName(resolved.nativeType);\n }\n\n return FORMAT_TYPE_DISPLAY.get(resolved.nativeType) ?? resolved.nativeType;\n}\n\nexport function columnTypeCheck({\n schema,\n table,\n column,\n expectedType,\n}: {\n schema: string;\n table: string;\n column: string;\n expectedType: string;\n}): string {\n return `SELECT EXISTS (\n SELECT 1\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = '${escapeLiteral(schema)}'\n AND c.relname = '${escapeLiteral(table)}'\n AND a.attname = '${escapeLiteral(column)}'\n AND format_type(a.atttypid, a.atttypmod) = '${escapeLiteral(expectedType)}'\n AND NOT a.attisdropped\n)`;\n}\n\nexport function columnDefaultExistsCheck({\n schema,\n table,\n column,\n exists = true,\n}: {\n schema: string;\n table: string;\n column: string;\n exists?: boolean;\n}): string {\n const nullCheck = exists ? 'IS NOT NULL' : 'IS NULL';\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n AND column_default ${nullCheck}\n)`;\n}\n\nexport function 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","import { escapeLiteral, quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type {\n ForeignKey,\n ReferentialAction,\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport type { PostgresColumnDefault } from '../types';\nimport { qualifyTableName } from './planner-sql-checks';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\n\nexport function buildCreateTableSql(\n qualifiedTableName: string,\n table: StorageTable,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column, codecHooks, storageTypes),\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 * Renders the SQL type for a column in DDL context.\n *\n * @param allowPseudoTypes - When true (default), autoincrement integer columns\n * produce SERIAL/BIGSERIAL/SMALLSERIAL pseudo-types. Set to false for contexts\n * like ALTER COLUMN TYPE where pseudo-types are invalid.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n allowPseudoTypes = true,\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (allowPseudoTypes) {\n const columnDefault = column.default;\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (resolved.nativeType === 'int4' || resolved.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (resolved.nativeType === 'int8' || resolved.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (resolved.nativeType === 'int2' || resolved.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n }\n\n const expanded = expandParameterizedTypeSql(resolved, codecHooks);\n if (expanded !== null) {\n return expanded;\n }\n\n if (column.typeRef) {\n return quoteIdentifier(resolved.nativeType);\n }\n\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType;\n}\n\nfunction expandParameterizedTypeSql(\n column: Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>,\n codecHooks: Map<string, CodecControlHooks>,\n): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n if (!column.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(column.codecId);\n if (!hooks?.expandNativeType) {\n if (hooks?.planTypeOperations) {\n return null;\n }\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${column.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n\n const expanded = hooks.expandNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/** Autoincrement columns use SERIAL types, so this returns empty for them. */\nexport function buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n return `DEFAULT nextval('${escapeLiteral(quoteIdentifier(columnDefault.name))}'::regclass)`;\n }\n}\n\nexport function renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (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 buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n temporaryDefault?: string | null,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const typeSql = buildColumnTypeSql(column, codecHooks, storageTypes);\n const defaultSql =\n buildColumnDefaultSql(column.default, column) ||\n (temporaryDefault ? `DEFAULT ${temporaryDefault}` : '');\n const parts = [\n `ALTER TABLE ${qualifiedTableName}`,\n `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,\n defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\nexport function buildForeignKeySql(\n schemaName: string,\n tableName: string,\n fkName: string,\n foreignKey: ForeignKey,\n): string {\n let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`;\n\n if (foreignKey.onDelete !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];\n if (!action) {\n throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);\n }\n sql += `\\nON DELETE ${action}`;\n }\n if (foreignKey.onUpdate !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];\n if (!action) {\n throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);\n }\n sql += `\\nON UPDATE ${action}`;\n }\n\n return sql;\n}\n","/**\n * Resolves thin operation descriptors into SqlMigrationPlanOperation objects\n * by looking up contract types and calling existing planner SQL helpers.\n *\n * This is the bridge between the ergonomic builder API (descriptors) and\n * the planner's SQL generation pipeline. It runs at verification time.\n */\n\nimport { createPostgresAdapter } from '@prisma-next/adapter-postgres/adapter';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n ComponentDatabaseDependency,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport type {\n DataTransformOperation,\n SerializedQueryPlan,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn, StorageTable } from '@prisma-next/sql-contract/types';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { lowerSqlPlan } from '@prisma-next/sql-runtime';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type {\n AddColumnDescriptor,\n AddEnumValuesDescriptor,\n AddForeignKeyDescriptor,\n AddPrimaryKeyDescriptor,\n AddUniqueDescriptor,\n AlterColumnTypeDescriptor,\n CreateDependencyDescriptor,\n CreateEnumTypeDescriptor,\n CreateIndexDescriptor,\n CreateTableDescriptor,\n DataTransformDescriptor,\n DropColumnDescriptor,\n DropConstraintDescriptor,\n DropDefaultDescriptor,\n DropEnumTypeDescriptor,\n DropIndexDescriptor,\n DropNotNullDescriptor,\n DropTableDescriptor,\n PostgresMigrationOpDescriptor,\n RenameTypeDescriptor,\n SetDefaultDescriptor,\n SetNotNullDescriptor,\n} from './operation-descriptors';\nimport {\n buildAddColumnSql,\n buildColumnDefaultSql,\n buildCreateTableSql,\n buildForeignKeySql,\n} from './planner-ddl-builders';\nimport {\n buildExpectedFormatType,\n columnExistsCheck,\n columnNullabilityCheck,\n columnTypeCheck,\n constraintExistsCheck,\n qualifyTableName,\n toRegclassLiteral,\n} from './planner-sql-checks';\nimport type { OperationClass, PostgresPlanTargetDetails } from './planner-target-details';\n\nexport interface OperationResolverContext {\n readonly toContract: Contract<SqlStorage>;\n readonly schemaName: string;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly dependencies?: readonly ComponentDatabaseDependency<unknown>[];\n readonly db?: unknown;\n}\n\ntype ResolvedOp = SqlMigrationPlanOperation<PostgresPlanTargetDetails>;\n\nfunction getTable(contract: Contract<SqlStorage>, tableName: string): StorageTable | undefined {\n return contract.storage.tables[tableName];\n}\n\nfunction getColumn(\n contract: Contract<SqlStorage>,\n tableName: string,\n columnName: string,\n): StorageColumn | undefined {\n return getTable(contract, tableName)?.columns[columnName];\n}\n\nfunction targetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n): { readonly id: 'postgres'; readonly details: PostgresPlanTargetDetails } {\n return {\n id: 'postgres',\n details: { schema, objectType, name, ...ifDefined('table', table) },\n };\n}\n\nfunction step(description: string, sql: string) {\n return { description, sql };\n}\n\nfunction resolveCreateTable(\n desc: CreateTableDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n if (!table) throw new Error(`Table \"${desc.table}\" not found in destination contract`);\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `table.${desc.table}`,\n label: `Create table \"${desc.table}\"`,\n summary: `Creates table \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('table', desc.table, ctx.schemaName),\n precheck: [\n step(\n `ensure table \"${desc.table}\" does not exist`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.table)}) IS NULL`,\n ),\n ],\n execute: [\n step(`create table \"${desc.table}\"`, buildCreateTableSql(qualified, table, ctx.codecHooks)),\n ],\n postcheck: [\n step(\n `verify table \"${desc.table}\" exists`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.table)}) IS NOT NULL`,\n ),\n ],\n };\n}\n\nfunction resolveDropTable(desc: DropTableDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `dropTable.${desc.table}`,\n label: `Drop table \"${desc.table}\"`,\n operationClass: 'destructive',\n target: targetDetails('table', desc.table, ctx.schemaName),\n precheck: [\n step(\n `ensure table \"${desc.table}\" exists`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.table)}) IS NOT NULL`,\n ),\n ],\n execute: [step(`drop table \"${desc.table}\"`, `DROP TABLE ${qualified}`)],\n postcheck: [\n step(\n `verify table \"${desc.table}\" does not exist`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.table)}) IS NULL`,\n ),\n ],\n };\n}\n\nfunction resolveAddColumn(desc: AddColumnDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const contractColumn = getColumn(ctx.toContract, desc.table, desc.column);\n if (!contractColumn)\n throw new Error(`Column \"${desc.table}\".\"${desc.column}\" not found in destination contract`);\n // Apply overrides — e.g., nullable: true for the add-nullable → backfill → setNotNull pattern\n const column: StorageColumn = {\n ...contractColumn,\n nullable:\n desc.overrides?.nullable !== undefined ? desc.overrides.nullable : contractColumn.nullable,\n };\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `column.${desc.table}.${desc.column}`,\n label: `Add column \"${desc.column}\" to \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" is missing`,\n columnExistsCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n exists: false,\n }),\n ),\n ],\n execute: [\n step(\n `add column \"${desc.column}\"`,\n buildAddColumnSql(qualified, desc.column, column, ctx.codecHooks),\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n };\n}\n\nfunction resolveDropColumn(desc: DropColumnDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `dropColumn.${desc.table}.${desc.column}`,\n label: `Drop column \"${desc.column}\" from \"${desc.table}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `drop column \"${desc.column}\"`,\n `ALTER TABLE ${qualified} DROP COLUMN ${quoteId(desc.column)}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" does not exist`,\n columnExistsCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n exists: false,\n }),\n ),\n ],\n };\n}\n\nfunction resolveAlterColumnType(\n desc: AlterColumnTypeDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const column = getColumn(ctx.toContract, desc.table, desc.column);\n if (!column)\n throw new Error(`Column \"${desc.table}\".\"${desc.column}\" not found in destination contract`);\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n const qualifiedTargetType = desc.toType\n ? qualifyName(ctx.schemaName, desc.toType)\n : buildExpectedFormatType(column, ctx.codecHooks);\n // format_type() returns unqualified names for types in search_path\n const formatTypeExpected = desc.toType ?? buildExpectedFormatType(column, ctx.codecHooks);\n return {\n id: `alterType.${desc.table}.${desc.column}`,\n label: `Alter type of \"${desc.table}\".\"${desc.column}\" to ${desc.toType ?? column.nativeType}`,\n operationClass: 'destructive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `alter type of \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} TYPE ${qualifiedTargetType}${desc.using ? ` USING ${desc.using}` : ` USING ${quoteId(desc.column)}::${qualifiedTargetType}`}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" has type \"${formatTypeExpected}\"`,\n columnTypeCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n expectedType: formatTypeExpected,\n }),\n ),\n ],\n meta: { warning: 'TABLE_REWRITE' },\n };\n}\n\nfunction resolveSetNotNull(desc: SetNotNullDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `alterNullability.${desc.table}.${desc.column}`,\n label: `Set NOT NULL on \"${desc.table}\".\"${desc.column}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n step(\n `ensure no NULL values in \"${desc.column}\"`,\n `SELECT NOT EXISTS (SELECT 1 FROM ${qualified} WHERE ${quoteId(desc.column)} IS NULL)`,\n ),\n ],\n execute: [\n step(\n `set NOT NULL on \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} SET NOT NULL`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" is NOT NULL`,\n columnNullabilityCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n nullable: false,\n }),\n ),\n ],\n };\n}\n\nfunction resolveDropNotNull(\n desc: DropNotNullDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `alterNullability.${desc.table}.${desc.column}`,\n label: `Drop NOT NULL on \"${desc.table}\".\"${desc.column}\"`,\n operationClass: 'widening',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `drop NOT NULL on \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} DROP NOT NULL`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" is nullable`,\n columnNullabilityCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n nullable: true,\n }),\n ),\n ],\n };\n}\n\nfunction resolveSetDefault(desc: SetDefaultDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const column = getColumn(ctx.toContract, desc.table, desc.column);\n if (!column)\n throw new Error(`Column \"${desc.table}\".\"${desc.column}\" not found in destination contract`);\n const defaultSql = buildColumnDefaultSql(column.default, column);\n if (!defaultSql)\n throw new Error(\n `Column \"${desc.table}\".\"${desc.column}\" has no default in destination contract`,\n );\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `setDefault.${desc.table}.${desc.column}`,\n label: `Set default on \"${desc.table}\".\"${desc.column}\"`,\n operationClass: 'additive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `set default on \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} ${defaultSql}`,\n ),\n ],\n postcheck: [],\n };\n}\n\nfunction resolveDropDefault(\n desc: DropDefaultDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `dropDefault.${desc.table}.${desc.column}`,\n label: `Drop default on \"${desc.table}\".\"${desc.column}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `drop default on \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} DROP DEFAULT`,\n ),\n ],\n postcheck: [],\n };\n}\n\nfunction resolveAddPrimaryKey(\n desc: AddPrimaryKeyDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n if (!table?.primaryKey)\n throw new Error(`Table \"${desc.table}\" has no primary key in destination contract`);\n const constraintName = table.primaryKey.name ?? `${desc.table}_pkey`;\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n const columnList = table.primaryKey.columns.map(quoteId).join(', ');\n return {\n id: `primaryKey.${desc.table}.${constraintName}`,\n label: `Add primary key on \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('primaryKey', constraintName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure primary key \"${constraintName}\" does not exist`,\n constraintExistsCheck({\n constraintName,\n schema: ctx.schemaName,\n table: desc.table,\n exists: false,\n }),\n ),\n ],\n execute: [\n step(\n `add primary key \"${constraintName}\"`,\n `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteId(constraintName)} PRIMARY KEY (${columnList})`,\n ),\n ],\n postcheck: [\n step(\n `verify primary key \"${constraintName}\" exists`,\n constraintExistsCheck({ constraintName, schema: ctx.schemaName, table: desc.table }),\n ),\n ],\n };\n}\n\nfunction resolveAddUnique(desc: AddUniqueDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n const unique = table?.uniques?.find((u) => u.columns.join(',') === desc.columns.join(','));\n const constraintName = unique?.name ?? `${desc.table}_${desc.columns.join('_')}_key`;\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n const columnList = desc.columns.map(quoteId).join(', ');\n return {\n id: `unique.${desc.table}.${constraintName}`,\n label: `Add unique constraint on \"${desc.table}\" (${desc.columns.join(', ')})`,\n operationClass: 'additive',\n target: targetDetails('unique', constraintName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure constraint \"${constraintName}\" does not exist`,\n constraintExistsCheck({\n constraintName,\n schema: ctx.schemaName,\n table: desc.table,\n exists: false,\n }),\n ),\n ],\n execute: [\n step(\n `add unique constraint \"${constraintName}\"`,\n `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteId(constraintName)} UNIQUE (${columnList})`,\n ),\n ],\n postcheck: [\n step(\n `verify constraint \"${constraintName}\" exists`,\n constraintExistsCheck({ constraintName, schema: ctx.schemaName, table: desc.table }),\n ),\n ],\n };\n}\n\nfunction resolveAddForeignKey(\n desc: AddForeignKeyDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n const fk = table?.foreignKeys?.find((f) => f.columns.join(',') === desc.columns.join(','));\n\n if (!fk) {\n throw new Error(\n `Foreign key on \"${desc.table}\" (${desc.columns.join(', ')}) not found in destination contract. ` +\n 'Ensure the FK is declared in the contract before authoring a migration that adds it.',\n );\n }\n\n const fkName = fk.name ?? `${desc.table}_${desc.columns.join('_')}_fkey`;\n\n return {\n id: `foreignKey.${desc.table}.${fkName}`,\n label: `Add foreign key \"${fkName}\" on \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('foreignKey', fkName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure FK \"${fkName}\" does not exist`,\n constraintExistsCheck({\n constraintName: fkName,\n schema: ctx.schemaName,\n table: desc.table,\n exists: false,\n }),\n ),\n ],\n execute: [\n step(`add FK \"${fkName}\"`, buildForeignKeySql(ctx.schemaName, desc.table, fkName, fk)),\n ],\n postcheck: [\n step(\n `verify FK \"${fkName}\" exists`,\n constraintExistsCheck({\n constraintName: fkName,\n schema: ctx.schemaName,\n table: desc.table,\n }),\n ),\n ],\n };\n}\n\nfunction resolveDropConstraint(\n desc: DropConstraintDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `dropConstraint.${desc.table}.${desc.constraintName}`,\n label: `Drop constraint \"${desc.constraintName}\" on \"${desc.table}\"`,\n operationClass: 'destructive',\n target: targetDetails('unique', desc.constraintName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure constraint \"${desc.constraintName}\" exists`,\n constraintExistsCheck({\n constraintName: desc.constraintName,\n schema: ctx.schemaName,\n table: desc.table,\n }),\n ),\n ],\n execute: [\n step(\n `drop constraint \"${desc.constraintName}\"`,\n `ALTER TABLE ${qualified} DROP CONSTRAINT ${quoteId(desc.constraintName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify constraint \"${desc.constraintName}\" does not exist`,\n constraintExistsCheck({\n constraintName: desc.constraintName,\n schema: ctx.schemaName,\n table: desc.table,\n exists: false,\n }),\n ),\n ],\n };\n}\n\nfunction resolveCreateIndex(\n desc: CreateIndexDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n const index = table?.indexes?.find((i) => i.columns.join(',') === desc.columns.join(','));\n const indexName = index?.name ?? `${desc.table}_${desc.columns.join('_')}_idx`;\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n const columnList = desc.columns.map(quoteId).join(', ');\n return {\n id: `index.${desc.table}.${indexName}`,\n label: `Create index \"${indexName}\" on \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('index', indexName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure index \"${indexName}\" does not exist`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, indexName)}) IS NULL`,\n ),\n ],\n execute: [\n step(\n `create index \"${indexName}\"`,\n `CREATE INDEX ${quoteId(indexName)} ON ${qualified} (${columnList})`,\n ),\n ],\n postcheck: [\n step(\n `verify index \"${indexName}\" exists`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, indexName)}) IS NOT NULL`,\n ),\n ],\n };\n}\n\nfunction resolveDropIndex(desc: DropIndexDescriptor, ctx: OperationResolverContext): ResolvedOp {\n return {\n id: `dropIndex.${desc.table}.${desc.indexName}`,\n label: `Drop index \"${desc.indexName}\"`,\n operationClass: 'destructive',\n target: targetDetails('index', desc.indexName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure index \"${desc.indexName}\" exists`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.indexName)}) IS NOT NULL`,\n ),\n ],\n execute: [\n step(\n `drop index \"${desc.indexName}\"`,\n `DROP INDEX ${qualifyTableName(ctx.schemaName, desc.indexName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify index \"${desc.indexName}\" does not exist`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.indexName)}) IS NULL`,\n ),\n ],\n };\n}\n\nfunction enumTypeExistsCheck(schemaName: string, nativeType: string, exists = true): string {\n const clause = exists ? 'EXISTS' : 'NOT EXISTS';\n return `SELECT ${clause} (\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(nativeType)}'\n)`;\n}\n\nfunction resolveCreateEnumType(\n desc: CreateEnumTypeDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n // When explicit values are provided (e.g., temp type in rebuild recipe), use them directly.\n // The typeName may be a temp name not in the contract.\n const nativeType = desc.typeName;\n let values: readonly string[];\n if (desc.values) {\n values = desc.values;\n } else {\n const typeInstance = ctx.toContract.storage.types?.[desc.typeName];\n if (!typeInstance) {\n throw new Error(`Type \"${desc.typeName}\" not found in destination contract storage.types`);\n }\n const typeValues = typeInstance.typeParams?.['values'];\n if (\n !Array.isArray(typeValues) ||\n !typeValues.every((v): v is string => typeof v === 'string')\n ) {\n throw new Error(`Type \"${desc.typeName}\" has no valid enum values in typeParams`);\n }\n values = typeValues;\n }\n const qualifiedType = qualifyName(ctx.schemaName, nativeType);\n const literalValues = values.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n return {\n id: `type.${nativeType}`,\n label: `Create enum type \"${nativeType}\"`,\n operationClass: 'additive',\n target: targetDetails('type', nativeType, ctx.schemaName),\n precheck: [\n step(\n `ensure type \"${nativeType}\" does not exist`,\n enumTypeExistsCheck(ctx.schemaName, nativeType, false),\n ),\n ],\n execute: [\n step(\n `create enum type \"${nativeType}\"`,\n `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`,\n ),\n ],\n postcheck: [\n step(`verify type \"${nativeType}\" exists`, enumTypeExistsCheck(ctx.schemaName, nativeType)),\n ],\n };\n}\n\nfunction resolveAddEnumValues(\n desc: AddEnumValuesDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const typeInstance = ctx.toContract.storage.types?.[desc.typeName];\n if (!typeInstance) {\n throw new Error(`Type \"${desc.typeName}\" not found in destination contract storage.types`);\n }\n const qualifiedType = qualifyName(ctx.schemaName, typeInstance.nativeType);\n return {\n id: `type.${desc.typeName}.addValues`,\n label: `Add values to enum type \"${desc.typeName}\": ${desc.values.join(', ')}`,\n operationClass: 'additive',\n target: targetDetails('type', desc.typeName, ctx.schemaName),\n precheck: [\n step(\n `ensure type \"${typeInstance.nativeType}\" exists`,\n enumTypeExistsCheck(ctx.schemaName, typeInstance.nativeType),\n ),\n ],\n execute: desc.values.map((value) =>\n step(\n `add value '${value}' to enum \"${typeInstance.nativeType}\"`,\n `ALTER TYPE ${qualifiedType} ADD VALUE '${escapeLiteral(value)}'`,\n ),\n ),\n postcheck: [\n step(\n `verify type \"${typeInstance.nativeType}\" exists`,\n enumTypeExistsCheck(ctx.schemaName, typeInstance.nativeType),\n ),\n ],\n };\n}\n\nfunction resolveDropEnumType(\n desc: DropEnumTypeDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const qualified = qualifyName(ctx.schemaName, desc.typeName);\n return {\n id: `type.${desc.typeName}.drop`,\n label: `Drop enum type \"${desc.typeName}\"`,\n operationClass: 'destructive',\n target: targetDetails('type', desc.typeName, ctx.schemaName),\n precheck: [\n step(\n `ensure type \"${desc.typeName}\" exists`,\n enumTypeExistsCheck(ctx.schemaName, desc.typeName),\n ),\n ],\n execute: [step(`drop enum type \"${desc.typeName}\"`, `DROP TYPE ${qualified}`)],\n postcheck: [\n step(\n `verify type \"${desc.typeName}\" removed`,\n enumTypeExistsCheck(ctx.schemaName, desc.typeName, false),\n ),\n ],\n };\n}\n\nfunction resolveRenameType(desc: RenameTypeDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const qualifiedFrom = qualifyName(ctx.schemaName, desc.fromName);\n return {\n id: `type.${desc.fromName}.rename`,\n label: `Rename type \"${desc.fromName}\" to \"${desc.toName}\"`,\n operationClass: 'destructive',\n target: targetDetails('type', desc.fromName, ctx.schemaName),\n precheck: [\n step(\n `ensure type \"${desc.fromName}\" exists`,\n enumTypeExistsCheck(ctx.schemaName, desc.fromName),\n ),\n ],\n execute: [\n step(\n `rename type \"${desc.fromName}\" to \"${desc.toName}\"`,\n `ALTER TYPE ${qualifiedFrom} RENAME TO ${quoteId(desc.toName)}`,\n ),\n ],\n postcheck: [\n step(`verify type \"${desc.toName}\" exists`, enumTypeExistsCheck(ctx.schemaName, desc.toName)),\n ],\n };\n}\n\nfunction resolveCreateDependency(\n desc: CreateDependencyDescriptor,\n ctx: OperationResolverContext,\n): readonly ResolvedOp[] {\n const dep = ctx.dependencies?.find((d) => d.id === desc.dependencyId);\n if (!dep) {\n throw new Error(\n `Dependency \"${desc.dependencyId}\" not found in resolver context. ` +\n 'Ensure frameworkComponents are passed to resolveDescriptors.',\n );\n }\n return dep.install as readonly ResolvedOp[];\n}\n\nconst postgresAdapter = createPostgresAdapter();\n\nfunction lowerToSql(plan: SqlQueryPlan, contract: Contract<SqlStorage>): SerializedQueryPlan {\n const lowered = lowerSqlPlan(postgresAdapter, contract, plan);\n return { sql: lowered.sql, params: lowered.params };\n}\n\nfunction resolveBuildable(input: unknown, contract: Contract<SqlStorage>): SerializedQueryPlan {\n if (\n typeof input === 'object' &&\n input !== null &&\n 'build' in input &&\n typeof (input as { build: unknown }).build === 'function'\n ) {\n return lowerToSql((input as { build(): unknown }).build() as SqlQueryPlan, contract);\n }\n return lowerToSql(input as SqlQueryPlan, contract);\n}\n\n/** Resolves a single QueryPlanInput to one or more lowered SQL statements. */\nfunction resolvePlanInput(\n input: symbol | object | ((...args: never[]) => unknown),\n db: unknown,\n contract: Contract<SqlStorage>,\n): readonly SerializedQueryPlan[] {\n if (typeof input === 'symbol') {\n throw new Error(\n 'Data transform contains an unimplemented TODO placeholder. ' +\n 'Fill in the check/run queries in migration.ts before running verify.',\n );\n }\n if (typeof input === 'function') {\n const result = input(db as never);\n if (Array.isArray(result)) {\n return result.map((item) => resolveBuildable(item, contract));\n }\n return [resolveBuildable(result, contract)];\n }\n return [resolveBuildable(input, contract)];\n}\n\nfunction resolveCheck(\n check: DataTransformDescriptor['check'],\n db: unknown,\n contract: Contract<SqlStorage>,\n): SerializedQueryPlan | boolean | null {\n if (typeof check === 'boolean') return check;\n const resolved = resolvePlanInput(check, db, contract);\n const first = resolved[0];\n if (!first) return null;\n return first;\n}\n\nfunction resolveDataTransform(\n desc: DataTransformDescriptor,\n ctx: OperationResolverContext,\n): DataTransformOperation {\n const { db, toContract } = ctx;\n return {\n id: `data_migration.${desc.name}`,\n label: `Data transform: ${desc.name}`,\n operationClass: 'data',\n name: desc.name,\n source: desc.source,\n check: resolveCheck(desc.check, db, toContract),\n run: desc.run.flatMap((input) => resolvePlanInput(input, db, toContract)),\n };\n}\n\nimport {\n escapeLiteral,\n qualifyName,\n quoteIdentifier as quoteId,\n} from '@prisma-next/adapter-postgres/control';\n\n/**\n * Resolves an array of operation descriptors into SqlMigrationPlanOperation objects.\n * Most descriptors resolve 1:1, but createType and createDependency may expand to multiple ops.\n */\nexport function resolveOperations(\n descriptors: readonly PostgresMigrationOpDescriptor[],\n context: OperationResolverContext,\n): readonly (ResolvedOp | DataTransformOperation)[] {\n return descriptors.flatMap((desc) => resolveOperation(desc, context));\n}\n\nfunction resolveOperation(\n desc: PostgresMigrationOpDescriptor,\n ctx: OperationResolverContext,\n): readonly (ResolvedOp | DataTransformOperation)[] {\n switch (desc.kind) {\n case 'createTable':\n return [resolveCreateTable(desc, ctx)];\n case 'dropTable':\n return [resolveDropTable(desc, ctx)];\n case 'addColumn':\n return [resolveAddColumn(desc, ctx)];\n case 'dropColumn':\n return [resolveDropColumn(desc, ctx)];\n case 'alterColumnType':\n return [resolveAlterColumnType(desc, ctx)];\n case 'setNotNull':\n return [resolveSetNotNull(desc, ctx)];\n case 'dropNotNull':\n return [resolveDropNotNull(desc, ctx)];\n case 'setDefault':\n return [resolveSetDefault(desc, ctx)];\n case 'dropDefault':\n return [resolveDropDefault(desc, ctx)];\n case 'addPrimaryKey':\n return [resolveAddPrimaryKey(desc, ctx)];\n case 'addUnique':\n return [resolveAddUnique(desc, ctx)];\n case 'addForeignKey':\n return [resolveAddForeignKey(desc, ctx)];\n case 'dropConstraint':\n return [resolveDropConstraint(desc, ctx)];\n case 'createIndex':\n return [resolveCreateIndex(desc, ctx)];\n case 'dropIndex':\n return [resolveDropIndex(desc, ctx)];\n case 'createEnumType':\n return [resolveCreateEnumType(desc, ctx)];\n case 'addEnumValues':\n return [resolveAddEnumValues(desc, ctx)];\n case 'dropEnumType':\n return [resolveDropEnumType(desc, ctx)];\n case 'renameType':\n return [resolveRenameType(desc, ctx)];\n case 'createDependency':\n return resolveCreateDependency(desc, ctx);\n case 'dataTransform':\n return [resolveDataTransform(desc, ctx)];\n }\n}\n","import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\n/**\n * Resolves the identity value (monoid neutral element) as a SQL literal for a column's type.\n * Checks codec hooks first (extensions can provide type-specific identity values),\n * then falls back to the built-in map.\n */\nexport function resolveIdentityValue(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string | null {\n const referencedType = column.typeRef ? storageTypes[column.typeRef] : undefined;\n const codecId = referencedType?.codecId ?? column.codecId;\n const nativeType = referencedType?.nativeType ?? column.nativeType;\n const typeParams = referencedType?.typeParams ?? column.typeParams;\n\n if (codecId) {\n const hookDefault = codecHooks.get(codecId)?.resolveIdentityValue?.({\n nativeType,\n codecId,\n ...ifDefined('typeParams', typeParams),\n });\n if (hookDefault !== undefined) {\n return hookDefault;\n }\n }\n\n return buildBuiltinIdentityValue(nativeType, typeParams);\n}\n\n/**\n * Returns the built-in identity value (monoid neutral element) as a SQL literal for the given\n * PostgreSQL native type — e.g. 0 for integers, '' for text, false for booleans.\n *\n * This is the planner's fallback when no codec hook provides a type-specific identity value.\n *\n * Returns null for unrecognized types (for example enums and extension-owned types without a\n * hook), which causes the planner to fall back to the empty-table precheck.\n *\n * @internal Exported for testing only.\n */\nexport function buildBuiltinIdentityValue(\n nativeType: string,\n typeParams?: Record<string, unknown>,\n): string | null {\n const normalizedNativeType = normalizeIdentityValueNativeType(nativeType);\n\n if (normalizedNativeType.endsWith('[]')) {\n return \"'{}'\";\n }\n\n switch (normalizedNativeType) {\n case 'text':\n case 'character':\n case 'bpchar':\n case 'character varying':\n case 'varchar':\n return \"''\";\n\n case 'int2':\n case 'int4':\n case 'int8':\n case 'integer':\n case 'bigint':\n case 'smallint':\n case 'float4':\n case 'float8':\n case 'real':\n case 'double precision':\n case 'numeric':\n case 'decimal':\n return '0';\n\n case 'bool':\n case 'boolean':\n return 'false';\n\n case 'uuid':\n return \"'00000000-0000-0000-0000-000000000000'\";\n\n case 'json':\n return \"'{}'::json\";\n case 'jsonb':\n return \"'{}'::jsonb\";\n\n case 'date':\n case 'timestamp':\n case 'timestamptz':\n case 'timestamp with time zone':\n case 'timestamp without time zone':\n return \"'epoch'\";\n\n case 'time':\n case 'time without time zone':\n return \"'00:00:00'\";\n case 'timetz':\n case 'time with time zone':\n return \"'00:00:00+00'\";\n\n case 'interval':\n return \"'0'\";\n\n case 'bytea':\n return \"''::bytea\";\n case 'tsvector':\n return \"''::tsvector\";\n\n case 'bit':\n return buildBitIdentityValue(typeParams);\n case 'bit varying':\n case 'varbit':\n return \"B''\";\n\n default:\n return null;\n }\n}\n\nfunction normalizeIdentityValueNativeType(nativeType: string): string {\n return nativeType.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nfunction buildBitIdentityValue(typeParams?: Record<string, unknown>): string | null {\n const length = typeParams?.['length'];\n if (length === undefined) {\n return \"B'0'\";\n }\n if (typeof length !== 'number' || !Number.isInteger(length) || length <= 0) {\n return null;\n }\n return `B'${'0'.repeat(length)}'`;\n}\n","import { ifDefined } from '@prisma-next/utils/defined';\n\nexport type OperationClass =\n | 'dependency'\n | 'type'\n | 'table'\n | 'column'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey';\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\nexport interface PlanningMode {\n readonly includeExtraObjects: boolean;\n readonly allowWidening: boolean;\n readonly allowDestructive: boolean;\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","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { buildAddColumnSql } from './planner-ddl-builders';\nimport {\n columnExistsCheck,\n columnHasNoDefaultCheck,\n columnNullabilityCheck,\n qualifyTableName,\n} from './planner-sql-checks';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\nexport function buildAddColumnOperationIdentity(\n schema: string,\n tableName: string,\n columnName: string,\n): Pick<\n SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n 'id' | 'label' | 'summary' | 'target'\n> {\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schema),\n },\n };\n}\n\nexport function buildAddNotNullColumnWithTemporaryDefaultOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n readonly temporaryDefault: string;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const { schema, tableName, columnName, column, codecHooks, storageTypes, temporaryDefault } =\n options;\n const qualified = qualifyTableName(schema, tableName);\n\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(\n qualified,\n columnName,\n column,\n codecHooks,\n temporaryDefault,\n storageTypes,\n ),\n },\n {\n description: `drop temporary default from column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n {\n description: `verify column \"${columnName}\" has no default after temporary default removal`,\n sql: columnHasNoDefaultCheck({ schema, table: tableName, column: columnName }),\n },\n ],\n };\n}\n","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n SqlStorage,\n StorageColumn,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { invariant } from '@prisma-next/utils/assertions';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';\nimport {\n buildExpectedFormatType,\n columnDefaultExistsCheck,\n columnExistsCheck,\n columnNullabilityCheck,\n columnTypeCheck,\n constraintExistsCheck,\n qualifyTableName,\n toRegclassLiteral,\n} from './planner-sql-checks';\nimport {\n buildTargetDetails,\n type PlanningMode,\n type PostgresPlanTargetDetails,\n} from './planner-target-details';\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nexport function buildReconciliationPlan(options: {\n readonly contract: Contract<SqlStorage>;\n readonly issues: readonly SchemaIssue[];\n readonly schemaName: string;\n readonly mode: PlanningMode;\n readonly policy: MigrationOperationPolicy;\n readonly codecHooks: Map<string, CodecControlHooks>;\n}): {\n readonly operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly conflicts: readonly SqlPlannerConflict[];\n} {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n const { mode } = options;\n const seenOperationIds = new Set<string>();\n\n for (const issue of sortSchemaIssues(options.issues)) {\n if (isAdditiveIssue(issue)) {\n continue;\n }\n\n const operation = buildReconciliationOperationFromIssue({\n issue,\n contract: options.contract,\n schemaName: options.schemaName,\n mode,\n codecHooks: options.codecHooks,\n });\n\n if (operation) {\n // Skip duplicates: different schema issues may produce the same operation id\n // (e.g., extra_unique_constraint and extra_index on the same object).\n if (!seenOperationIds.has(operation.id)) {\n seenOperationIds.add(operation.id);\n if (options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n operations.push(operation);\n } else {\n const conflict = convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n } else {\n const conflict = convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n\n return {\n operations,\n conflicts: conflicts.sort(conflictComparator),\n };\n}\n\n// ============================================================================\n// Issue Classification\n// ============================================================================\n\nfunction isAdditiveIssue(issue: SchemaIssue): boolean {\n switch (issue.kind) {\n case 'type_missing':\n case 'type_values_mismatch':\n case 'enum_values_changed':\n case 'missing_table':\n case 'missing_column':\n case 'dependency_missing':\n return true;\n case 'primary_key_mismatch':\n return issue.actual === undefined;\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'foreign_key_mismatch':\n return issue.indexOrConstraint === undefined;\n default:\n return false;\n }\n}\n\n// ============================================================================\n// Operation Builders\n// ============================================================================\n\nfunction buildReconciliationOperationFromIssue(options: {\n readonly issue: SchemaIssue;\n readonly contract: Contract<SqlStorage>;\n readonly schemaName: string;\n readonly mode: PlanningMode;\n readonly codecHooks: Map<string, CodecControlHooks>;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const { issue, contract, schemaName, mode, codecHooks } = options;\n const storageTypes = contract.storage.types ?? {};\n switch (issue.kind) {\n case 'extra_table':\n if (!mode.allowDestructive || !issue.table) {\n return null;\n }\n return buildDropTableOperation(schemaName, issue.table);\n\n case 'extra_column':\n if (!mode.allowDestructive || !issue.table || !issue.column) {\n return null;\n }\n return buildDropColumnOperation(schemaName, issue.table, issue.column);\n\n case 'extra_index':\n if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) {\n return null;\n }\n return buildDropIndexOperation(schemaName, issue.table, issue.indexOrConstraint);\n\n case 'extra_foreign_key':\n case 'extra_unique_constraint': {\n if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) {\n return null;\n }\n const constraintKind = issue.kind === 'extra_foreign_key' ? 'foreignKey' : 'unique';\n return buildDropConstraintOperation(\n schemaName,\n issue.table,\n issue.indexOrConstraint,\n constraintKind,\n );\n }\n\n case 'extra_primary_key': {\n if (!mode.allowDestructive || !issue.table) {\n return null;\n }\n const constraintName = issue.indexOrConstraint ?? `${issue.table}_pkey`;\n return buildDropConstraintOperation(schemaName, issue.table, constraintName, 'primaryKey');\n }\n\n case 'nullability_mismatch': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (issue.expected === 'true') {\n // Contract wants nullable, DB has NOT NULL → widening\n return mode.allowWidening\n ? buildDropNotNullOperation(schemaName, issue.table, issue.column)\n : null;\n }\n // Contract wants NOT NULL, DB has nullable → destructive\n return mode.allowDestructive\n ? buildSetNotNullOperation(schemaName, issue.table, issue.column)\n : null;\n }\n\n case 'type_mismatch': {\n if (!mode.allowDestructive || !issue.table || !issue.column) {\n return null;\n }\n const contractColumn = getContractColumn(contract, issue.table, issue.column);\n if (!contractColumn) {\n return null;\n }\n return buildAlterColumnTypeOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColumn,\n codecHooks,\n storageTypes,\n );\n }\n\n case 'default_missing': {\n if (!issue.table || !issue.column) {\n return null;\n }\n const contractColMissing = getContractColumn(contract, issue.table, issue.column);\n if (!contractColMissing) {\n return null;\n }\n // NOTE: Being in the `default_missing` case means the verifier found the contract expects a default, so it should exist here. We must still narrow.\n invariant(\n contractColMissing.default !== undefined,\n `default_missing issue for \"${issue.table}\".\"${issue.column}\" but contract column has no default`,\n );\n return buildDefaultOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColMissing,\n contractColMissing.default,\n 'additive',\n 'Set',\n );\n }\n\n case 'default_mismatch': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (!mode.allowWidening) {\n return null;\n }\n const contractColMismatch = getContractColumn(contract, issue.table, issue.column);\n if (!contractColMismatch) {\n return null;\n }\n // NOTE: Being in the `default_mismatch` case means the verifier found the contract expects a different default, so it should exist here. We must still narrow.\n invariant(\n contractColMismatch.default !== undefined,\n `default_mismatch issue for \"${issue.table}\".\"${issue.column}\" but contract column has no default`,\n );\n return buildDefaultOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColMismatch,\n contractColMismatch.default,\n 'widening',\n 'Change',\n );\n }\n\n case 'extra_default': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (!mode.allowDestructive) {\n return null;\n }\n return buildDropDefaultOperation(schemaName, issue.table, issue.column);\n }\n\n // Remaining issue kinds (primary_key_mismatch, unique_constraint_mismatch,\n // index_mismatch, foreign_key_mismatch) do not yet have reconciliation operation\n // builders. They fall through to the caller, which converts them to conflicts via\n // convertIssueToConflict. When a new SchemaIssue kind is added, add a case here if\n // the planner can emit an operation for it; otherwise it becomes a conflict.\n default:\n return null;\n }\n}\n\nfunction getContractColumn(\n contract: Contract<SqlStorage>,\n tableName: string,\n columnName: string,\n): StorageColumn | null {\n const table = contract.storage.tables[tableName];\n if (!table) {\n return null;\n }\n return table.columns[columnName] ?? null;\n}\n\nfunction buildDropTableOperation(\n schemaName: string,\n tableName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops extra table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n execute: [\n {\n description: `drop table \"${tableName}\"`,\n sql: `DROP TABLE ${qualifyTableName(schemaName, tableName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" is removed`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n };\n}\n\nfunction buildDropColumnOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} from ${tableName}`,\n summary: `Drops extra column ${columnName} from table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" is removed`,\n sql: columnExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: false,\n }),\n },\n ],\n };\n}\n\nfunction buildDropIndexOperation(\n schemaName: string,\n tableName: string,\n indexName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops extra index ${indexName} on table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n execute: [\n {\n description: `drop index \"${indexName}\"`,\n sql: `DROP INDEX ${qualifyTableName(schemaName, indexName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" is removed`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n };\n}\n\nfunction buildDropConstraintOperation(\n schemaName: string,\n tableName: string,\n constraintName: string,\n constraintKind: 'foreignKey' | 'unique' | 'primaryKey',\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropConstraint.${tableName}.${constraintName}`,\n label: `Drop constraint ${constraintName} on ${tableName}`,\n summary: `Drops extra constraint ${constraintName} on table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails(constraintKind, constraintName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName, table: tableName }),\n },\n ],\n execute: [\n {\n description: `drop constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nDROP CONSTRAINT ${quoteIdentifier(constraintName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify constraint \"${constraintName}\" is removed`,\n sql: constraintExistsCheck({\n constraintName,\n schema: schemaName,\n table: tableName,\n exists: false,\n }),\n },\n ],\n };\n}\n\nfunction buildDropNotNullOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `alterNullability.${tableName}.${columnName}`,\n label: `Relax nullability for ${columnName} on ${tableName}`,\n summary: `Drops NOT NULL constraint for ${columnName} on table ${tableName}`,\n operationClass: 'widening',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop NOT NULL from \"${columnName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nALTER COLUMN ${quoteIdentifier(columnName)} DROP NOT NULL`,\n },\n ],\n postcheck: [\n {\n description: `verify \"${columnName}\" is nullable`,\n sql: columnNullabilityCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: true,\n }),\n },\n ],\n };\n}\n\nfunction buildSetNotNullOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n return {\n id: `alterNullability.${tableName}.${columnName}`,\n label: `Enforce NOT NULL for ${columnName} on ${tableName}`,\n summary: `Sets NOT NULL on ${columnName} for table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n {\n description: `ensure \"${columnName}\" has no NULL values`,\n sql: `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualified}\n WHERE ${quoteIdentifier(columnName)} IS NULL\n LIMIT 1\n)`,\n },\n ],\n execute: [\n {\n description: `set NOT NULL on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\nALTER COLUMN ${quoteIdentifier(columnName)} SET NOT NULL`,\n },\n ],\n postcheck: [\n {\n description: `verify \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ],\n };\n}\n\nfunction buildAlterColumnTypeOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance>,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n const expectedType = buildColumnTypeSql(column, codecHooks, storageTypes, false);\n return {\n id: `alterType.${tableName}.${columnName}`,\n label: `Alter type for ${columnName} on ${tableName}`,\n summary: `Changes type of ${columnName} to ${expectedType}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n meta: {\n warning: 'TABLE_REWRITE',\n detail:\n 'ALTER COLUMN TYPE requires a full table rewrite and acquires an ACCESS EXCLUSIVE lock. On large tables, this can cause significant downtime.',\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `alter type of \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\nALTER COLUMN ${quoteIdentifier(columnName)}\nTYPE ${expectedType}\nUSING ${quoteIdentifier(columnName)}::${expectedType}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has type ${expectedType}`,\n sql: columnTypeCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n expectedType: buildExpectedFormatType(column, codecHooks, storageTypes),\n }),\n },\n ],\n };\n}\n\nfunction buildDefaultOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n column: Omit<StorageColumn, 'default'>,\n columnDefault: NonNullable<StorageColumn['default']>,\n operationClass: 'additive' | 'widening',\n verb: 'Set' | 'Change',\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const qualified = qualifyTableName(schemaName, tableName);\n const defaultClause = buildColumnDefaultSql(columnDefault, column);\n // autoincrement defaults are handled by SERIAL types — buildColumnDefaultSql returns ''\n // for them. Until the IR is enriched to distinguish autoincrement (TML-2107), skip.\n if (!defaultClause) return null;\n const verbLower = verb.toLowerCase();\n return {\n id: `setDefault.${tableName}.${columnName}`,\n label: `${verb} default for ${columnName} on ${tableName}`,\n summary: `${verb}s default on column ${columnName} of table ${tableName}`,\n operationClass,\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `${verbLower} default on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\\nALTER COLUMN ${quoteIdentifier(columnName)} SET ${defaultClause}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has a default`,\n sql: columnDefaultExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: true,\n }),\n },\n ],\n };\n}\n\nfunction buildDropDefaultOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n return {\n id: `dropDefault.${tableName}.${columnName}`,\n label: `Drop default for ${columnName} on ${tableName}`,\n summary: `Drops default on column ${columnName} of table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop default on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\\nALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has no default`,\n sql: columnDefaultExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: false,\n }),\n },\n ],\n };\n}\n\n// ============================================================================\n// Conflict Conversion\n// ============================================================================\n\nfunction convertIssueToConflict(issue: SchemaIssue): SqlPlannerConflict | null {\n switch (issue.kind) {\n case 'type_mismatch':\n return buildConflict('typeMismatch', issue);\n case 'nullability_mismatch':\n return buildConflict('nullabilityConflict', issue);\n case 'default_missing':\n case 'default_mismatch':\n case 'extra_default':\n case 'extra_table':\n case 'extra_column':\n case 'extra_primary_key':\n case 'extra_foreign_key':\n case 'extra_unique_constraint':\n case 'extra_index':\n return buildConflict('missingButNonAdditive', issue);\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n return buildConflict('indexIncompatible', issue);\n case 'foreign_key_mismatch':\n return buildConflict('foreignKeyConflict', issue);\n // Additive issue kinds (missing_table, missing_column, type_missing, type_values_mismatch,\n // dependency_missing) are filtered by isAdditiveIssue before reaching this method.\n // If a new SchemaIssue kind is introduced, add a mapping here so it becomes a conflict\n // rather than being silently ignored.\n default:\n return null;\n }\n}\n\nfunction buildConflict(kind: SqlPlannerConflict['kind'], issue: SchemaIssue): SqlPlannerConflict {\n const location = buildConflictLocation(issue);\n const base = issue.kind !== 'enum_values_changed' ? issue : undefined;\n const meta =\n base?.expected || base?.actual\n ? Object.freeze({\n ...ifDefined('expected', base.expected),\n ...ifDefined('actual', base.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 aBase = a.kind !== 'enum_values_changed' ? a : undefined;\n const bBase = b.kind !== 'enum_values_changed' ? b : undefined;\n const tableCompare = compareStrings(aBase?.table, bBase?.table);\n if (tableCompare !== 0) {\n return tableCompare;\n }\n const columnCompare = compareStrings(aBase?.column, bBase?.column);\n if (columnCompare !== 0) {\n return columnCompare;\n }\n return compareStrings(aBase?.indexOrConstraint, bBase?.indexOrConstraint);\n });\n}\n\nfunction buildConflictLocation(issue: SchemaIssue) {\n if (issue.kind === 'enum_values_changed') {\n return { type: issue.typeName };\n }\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 type { ForeignKey } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\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 */\nexport interface SchemaTableLookup {\n readonly uniqueKeys: Set<string>;\n readonly indexKeys: Set<string>;\n readonly uniqueIndexKeys: Set<string>;\n readonly fkKeys: Set<string>;\n}\n\nexport function 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\nexport function hasUniqueConstraint(\n lookup: SchemaTableLookup,\n columns: readonly string[],\n): boolean {\n const key = columns.join(',');\n return lookup.uniqueKeys.has(key) || lookup.uniqueIndexKeys.has(key);\n}\n\nexport function hasIndex(lookup: SchemaTableLookup, columns: readonly string[]): boolean {\n const key = columns.join(',');\n return lookup.indexKeys.has(key) || lookup.uniqueKeys.has(key);\n}\n\nexport function hasForeignKey(lookup: SchemaTableLookup, fk: ForeignKey): boolean {\n return lookup.fkKeys.has(\n `${fk.columns.join(',')}|${fk.references.table}|${fk.references.columns.join(',')}`,\n );\n}\n","import {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n quoteIdentifier,\n} from '@prisma-next/adapter-postgres/control';\nimport type {\n CodecControlHooks,\n ComponentDatabaseDependency,\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport {\n collectInitDependencies,\n createMigrationPlan,\n extractCodecControlHooks,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { buildAddColumnSql, buildCreateTableSql, buildForeignKeySql } from './planner-ddl-builders';\nimport { resolveIdentityValue } from './planner-identity-values';\nimport {\n buildAddColumnOperationIdentity,\n buildAddNotNullColumnWithTemporaryDefaultOperation,\n} from './planner-recipes';\nimport { buildReconciliationPlan } from './planner-reconciliation';\nimport {\n buildSchemaLookupMap,\n hasForeignKey,\n hasIndex,\n hasUniqueConstraint,\n type SchemaTableLookup,\n} from './planner-schema-lookup';\nimport {\n columnExistsCheck,\n columnNullabilityCheck,\n constraintExistsCheck,\n qualifyTableName,\n tableHasPrimaryKeyCheck,\n tableIsEmptyCheck,\n toRegclassLiteral,\n} from './planner-sql-checks';\nimport {\n buildTargetDetails,\n type OperationClass,\n type PlanningMode,\n type PostgresPlanTargetDetails,\n} from './planner-target-details';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype PlannerDatabaseDependency = {\n readonly id: string;\n readonly label: string;\n readonly install: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n};\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): SqlMigrationPlanner<PostgresPlanTargetDetails> {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\nclass PostgresMigrationPlanner implements SqlMigrationPlanner<PostgresPlanTargetDetails> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: SqlMigrationPlannerPlanOptions) {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const 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 const storageTypes = options.contract.storage.types ?? {};\n\n const reconciliationPlan = buildReconciliationPlan({\n contract: options.contract,\n issues: schemaIssues,\n schemaName,\n mode: planningMode,\n policy: options.policy,\n codecHooks,\n });\n if (reconciliationPlan.conflicts.length > 0) {\n return plannerFailure(reconciliationPlan.conflicts);\n }\n\n const storageTypePlan = this.buildStorageTypeOperations(options, schemaName, codecHooks);\n if (storageTypePlan.conflicts.length > 0) {\n return plannerFailure(storageTypePlan.conflicts);\n }\n\n // Sort table entries once for reuse across all additive operation builders.\n const sortedTables = sortedEntries(options.contract.storage.tables);\n\n // Pre-compute constraint lookups once per schema table for O(1) checks across all builders.\n const schemaLookups = buildSchemaLookupMap(options.schema);\n\n // Build extension operations from component-owned database dependencies\n operations.push(\n ...this.buildDatabaseDependencyOperations(options),\n ...storageTypePlan.operations,\n ...reconciliationPlan.operations,\n ...this.buildTableOperations(\n sortedTables,\n options.schema,\n schemaName,\n codecHooks,\n storageTypes,\n ),\n ...this.buildColumnOperations(\n sortedTables,\n options.schema,\n schemaLookups,\n schemaName,\n codecHooks,\n storageTypes,\n ),\n ...this.buildPrimaryKeyOperations(sortedTables, options.schema, schemaName),\n ...this.buildUniqueOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildIndexOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildFkBackingIndexOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildForeignKeyOperations(sortedTables, schemaLookups, schemaName),\n );\n\n const plan = createMigrationPlan<PostgresPlanTargetDetails>({\n targetId: 'postgres',\n origin: null,\n destination: {\n storageHash: options.contract.storage.storageHash,\n ...ifDefined('profileHash', options.contract.profileHash),\n },\n operations,\n });\n\n return plannerSuccess(plan);\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n /**\n * Builds migration operations from component-owned database dependencies.\n * These operations install database-side persistence structures declared by components.\n */\n private buildDatabaseDependencyOperations(\n options: PlannerOptionsWithComponents,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const dependencies = this.collectDependencies(options);\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const seenDependencyIds = new Set<string>();\n const seenOperationIds = new Set<string>();\n\n const installedIds = new Set(options.schema.dependencies.map((d) => d.id));\n\n for (const dependency of dependencies) {\n if (seenDependencyIds.has(dependency.id)) {\n continue;\n }\n seenDependencyIds.add(dependency.id);\n\n if (installedIds.has(dependency.id)) {\n continue;\n }\n\n for (const installOp of dependency.install) {\n if (seenOperationIds.has(installOp.id)) {\n continue;\n }\n seenOperationIds.add(installOp.id);\n operations.push(installOp as SqlMigrationPlanOperation<PostgresPlanTargetDetails>);\n }\n }\n\n return operations;\n }\n\n private buildStorageTypeOperations(\n options: PlannerOptionsWithComponents,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): {\n readonly operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly conflicts: readonly SqlPlannerConflict[];\n } {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n const storageTypes = options.contract.storage.types ?? {};\n\n for (const [typeName, typeInstance] of sortedEntries(storageTypes)) {\n const hook = codecHooks.get(typeInstance.codecId);\n const planResult = hook?.planTypeOperations?.({\n typeName,\n typeInstance,\n contract: options.contract,\n schema: options.schema,\n schemaName,\n policy: options.policy,\n });\n if (!planResult) {\n continue;\n }\n for (const operation of planResult.operations) {\n if (!options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n conflicts.push({\n kind: 'missingButNonAdditive',\n summary: `Storage type \"${typeName}\" requires \"${operation.operationClass}\" operation \"${operation.id}\"`,\n location: {\n type: typeName,\n },\n });\n continue;\n }\n operations.push({\n ...operation,\n target: {\n id: operation.target.id,\n details: this.buildTargetDetails('type', typeName, schemaName),\n },\n });\n }\n }\n\n return { operations, conflicts };\n }\n private collectDependencies(\n options: PlannerOptionsWithComponents,\n ): ReadonlyArray<PlannerDatabaseDependency> {\n const dependencies = collectInitDependencies(options.frameworkComponents);\n return sortDependencies(dependencies.filter(isPostgresPlannerDependency));\n }\n\n private buildTableOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance>,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n if (schema.tables[tableName]) {\n continue;\n }\n const qualified = qualifyTableName(schemaName, tableName);\n operations.push({\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" does not exist`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: buildCreateTableSql(qualified, table, codecHooks, storageTypes),\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n });\n }\n return operations;\n }\n\n private buildColumnOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance>,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const schemaTable = schema.tables[tableName];\n if (!schemaTable) {\n continue;\n }\n const schemaLookup = schemaLookups.get(tableName);\n for (const [columnName, column] of sortedEntries(table.columns)) {\n if (schemaTable.columns[columnName]) {\n continue;\n }\n operations.push(\n this.buildAddColumnOperation({\n schema: schemaName,\n tableName,\n table,\n schemaTable,\n schemaLookup,\n columnName,\n column,\n codecHooks,\n storageTypes,\n }),\n );\n }\n }\n return operations;\n }\n\n private buildAddColumnOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: SchemaTableLookup | undefined;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n }): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const {\n schema,\n tableName,\n table,\n schemaTable,\n schemaLookup,\n columnName,\n column,\n codecHooks,\n storageTypes,\n } = options;\n const notNull = !column.nullable;\n const hasDefault = column.default !== undefined;\n // Planner logic decides whether this column needs the coordinated multi-step\n // strategy. The strategy recipe itself is built by a dedicated helper.\n const needsTemporaryDefault = notNull && !hasDefault;\n const temporaryDefault = needsTemporaryDefault\n ? resolveIdentityValue(column, codecHooks, storageTypes)\n : null;\n const canUseSharedTemporaryDefault =\n needsTemporaryDefault &&\n temporaryDefault !== null &&\n canUseSharedTemporaryDefaultStrategy({\n table,\n schemaTable,\n schemaLookup,\n columnName,\n });\n\n if (canUseSharedTemporaryDefault) {\n return buildAddNotNullColumnWithTemporaryDefaultOperation({\n schema,\n tableName,\n columnName,\n column,\n codecHooks,\n storageTypes,\n temporaryDefault,\n });\n }\n\n const qualified = qualifyTableName(schema, tableName);\n const requiresEmptyTableCheck = needsTemporaryDefault && !canUseSharedTemporaryDefault;\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ...(requiresEmptyTableCheck\n ? [\n {\n description: `ensure table \"${tableName}\" is empty before adding NOT NULL column without default`,\n sql: tableIsEmptyCheck(qualified),\n },\n ]\n : []),\n ],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(\n qualified,\n columnName,\n column,\n codecHooks,\n undefined,\n storageTypes,\n ),\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n ...(notNull\n ? [\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ]\n : []),\n ],\n };\n }\n\n private buildPrimaryKeyOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n if (!table.primaryKey) {\n continue;\n }\n const schemaTable = schema.tables[tableName];\n if (!schemaTable || schemaTable.primaryKey) {\n continue;\n }\n const constraintName = table.primaryKey.name ?? `${tableName}_pkey`;\n operations.push({\n id: `primaryKey.${tableName}.${constraintName}`,\n label: `Add primary key ${constraintName} on ${tableName}`,\n summary: `Adds primary key ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure primary key does not exist on \"${tableName}\"`,\n sql: tableHasPrimaryKeyCheck(schemaName, tableName, false),\n },\n ],\n execute: [\n {\n description: `add primary key \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nPRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify primary key \"${constraintName}\" exists`,\n sql: tableHasPrimaryKeyCheck(schemaName, tableName, true, constraintName),\n },\n ],\n });\n }\n return operations;\n }\n\n private buildUniqueOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const unique of table.uniques) {\n if (lookup && hasUniqueConstraint(lookup, unique.columns)) {\n continue;\n }\n const constraintName = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n operations.push({\n id: `unique.${tableName}.${constraintName}`,\n label: `Add unique constraint ${constraintName} on ${tableName}`,\n summary: `Adds unique constraint ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('unique', constraintName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure unique constraint \"${constraintName}\" is missing`,\n sql: constraintExistsCheck({\n constraintName,\n schema: schemaName,\n table: tableName,\n exists: false,\n }),\n },\n ],\n execute: [\n {\n description: `add unique constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nUNIQUE (${unique.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify unique constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName, table: tableName }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildIndexOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const index of table.indexes) {\n if (lookup && hasIndex(lookup, index.columns)) {\n continue;\n }\n const indexName = index.name ?? defaultIndexName(tableName, index.columns);\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${index.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n /**\n * Generates FK-backing index operations for FKs with `index: true`,\n * but only when no matching user-declared index exists in `contractTable.indexes`.\n */\n private buildFkBackingIndexOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n // Collect column sets of user-declared indexes to avoid duplicates\n const declaredIndexColumns = new Set(table.indexes.map((idx) => idx.columns.join(',')));\n\n for (const fk of table.foreignKeys) {\n if (fk.index === false) continue;\n // Skip if user already declared an index with these columns\n if (declaredIndexColumns.has(fk.columns.join(','))) continue;\n // Skip if the index already exists in the database\n if (lookup && hasIndex(lookup, fk.columns)) continue;\n\n const indexName = defaultIndexName(tableName, fk.columns);\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create FK-backing index ${indexName} on ${tableName}`,\n summary: `Creates FK-backing index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create FK-backing index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${fk.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildForeignKeyOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false) continue;\n if (lookup && hasForeignKey(lookup, foreignKey)) {\n continue;\n }\n const fkName = foreignKey.name ?? `${tableName}_${foreignKey.columns.join('_')}_fkey`;\n operations.push({\n id: `foreignKey.${tableName}.${fkName}`,\n label: `Add foreign key ${fkName} on ${tableName}`,\n summary: `Adds foreign key ${fkName} referencing ${foreignKey.references.table}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('foreignKey', fkName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure foreign key \"${fkName}\" is missing`,\n sql: constraintExistsCheck({\n constraintName: fkName,\n schema: schemaName,\n table: tableName,\n exists: false,\n }),\n },\n ],\n execute: [\n {\n description: `add foreign key \"${fkName}\"`,\n sql: buildForeignKeySql(schemaName, tableName, fkName, foreignKey),\n },\n ],\n postcheck: [\n {\n description: `verify foreign key \"${fkName}\" exists`,\n sql: constraintExistsCheck({\n constraintName: fkName,\n schema: schemaName,\n table: tableName,\n }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n ): PostgresPlanTargetDetails {\n return buildTargetDetails(objectType, name, schema, table);\n }\n\n private resolvePlanningMode(policy: MigrationOperationPolicy): PlanningMode {\n const allowWidening = policy.allowedOperationClasses.includes('widening');\n const allowDestructive = policy.allowedOperationClasses.includes('destructive');\n // `db init` uses additive-only policy and intentionally ignores extras.\n // Any reconciliation-capable policy should inspect extras to reconcile strict equality.\n const includeExtraObjects = allowWidening || allowDestructive;\n return { includeExtraObjects, allowWidening, allowDestructive };\n }\n\n private collectSchemaIssues(\n options: PlannerOptionsWithComponents,\n strict: boolean,\n ): readonly SchemaIssue[] {\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n\nfunction canUseSharedTemporaryDefaultStrategy(options: {\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: SchemaTableLookup | undefined;\n readonly columnName: string;\n}): boolean {\n const { table, schemaTable, schemaLookup, columnName } = options;\n\n // Shared placeholders are only safe when later plan steps do not require\n // row-specific values for this newly added column.\n if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) {\n return false;\n }\n\n for (const unique of table.uniques) {\n if (!unique.columns.includes(columnName)) {\n continue;\n }\n if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) {\n return false;\n }\n }\n\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false || !foreignKey.columns.includes(columnName)) {\n continue;\n }\n if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction isPostgresPlannerDependency(\n dependency: ComponentDatabaseDependency<unknown>,\n): dependency is PlannerDatabaseDependency {\n return dependency.install.every((operation) => operation.target.id === 'postgres');\n}\n\nfunction sortedEntries<V>(record: Readonly<Record<string, V>>): Array<[string, V]> {\n return Object.entries(record).sort(([a], [b]) => a.localeCompare(b)) as Array<[string, V]>;\n}\n","export 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);\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 type { DataTransformOperation } from '@prisma-next/framework-components/control';\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-target-details';\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\nfunction isDataTransformOperation(op: unknown): op is DataTransformOperation {\n return (\n typeof op === 'object' &&\n op !== null &&\n 'operationClass' in op &&\n (op as { operationClass: string }).operationClass === 'data' &&\n 'name' in op &&\n 'check' in op &&\n 'run' in op\n );\n}\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await readMarker(driver);\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // db update (origin: null) always applies; migration-apply (origin set) skips if marker matches.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const skipOperations = markerAtDestination && options.plan.origin != null;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contract: 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 // Data transform operations have a different execution lifecycle\n if (operation.operationClass === 'data' && isDataTransformOperation(operation)) {\n const dtResult = await this.executeDataTransform(driver, operation, {\n runIdempotency,\n });\n if (!dtResult.ok) {\n return dtResult;\n }\n executedOperations.push(operation);\n operationsExecuted += 1;\n continue;\n }\n\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 /**\n * Executes a data transform operation with the check → (skip or run) → check lifecycle.\n *\n * 1. If check is a query AST: render to SQL, execute. Empty result = already applied (skip).\n * 2. If check is `true`: always skip. If `false`: always run.\n * 3. Execute run ASTs (rendered to SQL) sequentially.\n * 4. Re-execute check as post-run validation. If violations remain, fail.\n */\n private async executeDataTransform(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n op: DataTransformOperation,\n options: { runIdempotency: boolean },\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n // Step 1: Check (skip guard)\n if (op.check === true) {\n // Always skip, regardless of idempotency setting\n return okVoid();\n }\n if (options.runIdempotency && op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length === 0) {\n // No violations — already applied, skip\n return okVoid();\n }\n }\n\n // Step 2: Execute run steps\n if (op.run) {\n for (const plan of op.run) {\n try {\n await driver.query(plan.sql, plan.params);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Data transform \"${op.name}\" failed: ${error.message}`,\n {\n why: error.message,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n sql: plan.sql,\n sqlState: error.sqlState,\n },\n },\n );\n }\n throw error;\n }\n }\n }\n\n // Step 3: Post-run validation (check again)\n if (op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length > 0) {\n return runnerFailure(\n 'POSTCHECK_FAILED',\n `Data transform \"${op.name}\" did not resolve all violations (${checkResult.rows.length} remaining)`,\n {\n why: `After executing the data transform, the check query still returns ${checkResult.rows.length} violation(s).`,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n remainingViolations: checkResult.rows.length,\n },\n },\n );\n }\n }\n\n return okVoid();\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.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.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 {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n} from '@prisma-next/adapter-postgres/control';\nimport type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport {\n collectInitDependencies,\n contractToSchemaIR,\n extractCodecControlHooks,\n} from '@prisma-next/family-sql/control';\nimport { MigrationDescriptorArraySchema } from '@prisma-next/family-sql/operation-descriptors';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationPlanner,\n MigrationRunner,\n OperationDescriptor,\n} from '@prisma-next/framework-components/control';\nimport { sql } from '@prisma-next/sql-builder/runtime';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type } from 'arktype';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { planDescriptors } from '../core/migrations/descriptor-planner';\nimport { resolveOperations } from '../core/migrations/operation-resolver';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction parseDescriptors(descriptors: readonly OperationDescriptor[]) {\n const result = MigrationDescriptorArraySchema([...descriptors]);\n if (result instanceof type.errors) {\n throw new Error(`Invalid migration descriptors:\\n${result.summary}`);\n }\n return result;\n}\n\nfunction collectQueryOperationTypes(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n): Readonly<Record<string, SqlOperationEntry>> {\n const entries: Record<string, SqlOperationEntry> = {};\n if (!frameworkComponents) return entries;\n for (const component of frameworkComponents) {\n const ops = (\n component as {\n queryOperations?: () => ReadonlyArray<{ method: string } & SqlOperationEntry>;\n }\n ).queryOperations?.();\n if (!ops) continue;\n for (const { method, ...entry } of ops) {\n entries[method] = entry;\n }\n }\n return entries;\n}\n\n/**\n * Creates a SQL DSL client for migration authoring.\n * Only the fields used by the builder are populated — operations, codecs,\n * and types are unused by sql() and stubbed to satisfy the ExecutionContext type.\n */\nfunction createMigrationClient(\n toContract: Contract<SqlStorage>,\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n const queryOperationTypes = collectQueryOperationTypes(frameworkComponents);\n // sql() only reads contract, queryOperations.entries(), and applyMutationDefaults\n // from the context. The other fields are for runtime execution, not query building.\n return sql({\n context: {\n contract: toContract,\n queryOperations: { entries: () => queryOperationTypes },\n applyMutationDefaults: () => [],\n } as never,\n });\n}\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n\n if (!input.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${input.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) {\n throw new Error(\n `Column declares typeParams for nativeType \"${input.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${input.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner() as MigrationPlanner<'sql', 'postgres'>;\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n planWithDescriptors(context) {\n const toContract = context.toContract as Contract<SqlStorage>;\n const fromContract = context.fromContract as Contract<SqlStorage> | null;\n\n // Synthesize schema IR from the fromContract (same as contractToSchema flow)\n const expander = buildNativeTypeExpander(context.frameworkComponents);\n const fromSchemaIR = contractToSchemaIR(fromContract, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: context.frameworkComponents ?? [],\n });\n\n // Collect schema issues via verifier\n const verifyResult = verifySqlSchema({\n contract: toContract,\n schema: fromSchemaIR,\n strict: true,\n typeMetadataRegistry: new Map(),\n frameworkComponents: context.frameworkComponents ?? [],\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n\n // Run descriptor planner\n const planResult = planDescriptors({\n issues: verifyResult.schema.issues,\n toContract,\n fromContract,\n });\n if (!planResult.ok) {\n return { ok: false as const, conflicts: planResult.failure };\n }\n\n return {\n ok: true as const,\n descriptors: planResult.value.descriptors,\n needsDataMigration: planResult.value.needsDataMigration,\n };\n },\n\n resolveDescriptors(descriptors, context) {\n const validated = parseDescriptors(descriptors);\n const codecHooks = context.frameworkComponents\n ? extractCodecControlHooks(context.frameworkComponents)\n : new Map();\n const dependencies = context.frameworkComponents\n ? collectInitDependencies(context.frameworkComponents)\n : [];\n const toContract = context.toContract as Contract<SqlStorage>;\n const db = createMigrationClient(toContract, context.frameworkComponents);\n return resolveOperations(validated, {\n toContract,\n schemaName: context.schemaName ?? 'public',\n codecHooks,\n dependencies,\n db,\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;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QACA,YAMS;CACT,MAAM,WAAW,WAAW,QAAQ;AACpC,QAAO;;;0BAGiB,cAAc,OAAO,CAAC;wBACxB,cAAc,MAAM,CAAC;yBACpB,cAAc,OAAO,CAAC;yBACtB,SAAS;;;AAIlC,SAAgB,kBAAkB,oBAAoC;AACpE,QAAO,oCAAoC,mBAAmB;;AAGhE,SAAgB,wBAAwB,MAI7B;AACT,QAAO;;;0BAGiB,cAAc,KAAK,OAAO,CAAC;wBAC7B,cAAc,KAAK,MAAM,CAAC;yBACzB,cAAc,KAAK,OAAO,CAAC;;;;AAKpD,MAAMC,sBAAmD,IAAI,IAAI;CAC/D,CAAC,QAAQ,WAAW;CACpB,CAAC,QAAQ,UAAU;CACnB,CAAC,QAAQ,SAAS;CAClB,CAAC,UAAU,OAAO;CAClB,CAAC,UAAU,mBAAmB;CAC9B,CAAC,QAAQ,UAAU;CACnB,CAAC,aAAa,8BAA8B;CAC5C,CAAC,eAAe,2BAA2B;CAC3C,CAAC,QAAQ,yBAAyB;CAClC,CAAC,UAAU,sBAAsB;CAClC,CAAC;AAEF,MAAM,uCAAuC;AAE7C,MAAM,qCAAqC,IAAI,IAAI;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAS,0BAA0B,YAA4B;AAC7D,KACE,qCAAq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AM,aAAa,QAAQ,sBACvB,yBAAyB,QAAQ,oBAAoB,mBACrD,IAAI,KAAK;GACb,MAAM,eAAe,QAAQ,sBACzB,wBAAwB,QAAQ,oBAAoB,GACpD,EAAE;GACN,MAAM,aAAa,QAAQ;GAC3B,MAAM,KAAK,sBAAsB,YAAY,QAAQ,oBAAoB;AACzE,UAAO,kBAAkB,WAAW;IAClC;IACA,YAAY,QAAQ,cAAc;IAClC;IACA;IACA;IACD,CAAC;;EAEL;CACD,SAAmD;AACjD,SAAO;GACL,UAAU;GACV,UAAU;GACX;;CAMH,cAAc,SAAmC;AAC/C,SAAO,gCAAgC;;CAMzC,aAAa,QAAQ;AACnB,SAAO,8BAA8B,OAAO;;CAE/C;AAEH,sBAAe"}
|
|
1
|
+
{"version":3,"file":"control.mjs","names":["MAX_IDENTIFIER_LENGTH","renderLiteral","enumTypeExistsCheck","columnTypeCheck","REBUILD_SUFFIX","control_default","columnRefs: { table: string; column: string }[]","notNullBackfillStrategy: MigrationStrategy","matched: SchemaIssue[]","ops: PostgresMigrationOpDescriptor[]","TODO","typeChangeStrategy: MigrationStrategy","nullableTighteningStrategy: MigrationStrategy","enumChangeStrategy: MigrationStrategy","migrationPlanStrategies: readonly MigrationStrategy[]","ISSUE_KIND_ORDER: Record<string, number>","ops: PostgresMigrationOpDescriptor[]","context: StrategyContext","patternOps: PostgresMigrationOpDescriptor[]","defaultOps: PostgresMigrationOpDescriptor[]","conflicts: SqlPlannerConflict[]","sql","FORMAT_TYPE_DISPLAY: ReadonlyMap<string, string>","constraintDefinitions: string[]","REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string>","sql","column: StorageColumn","quoteId","values: readonly string[]","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig","operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[]","conflicts: SqlPlannerConflict[]","ensurePrismaContractSchemaStatement: SqlStatement","ensureMarkerTableStatement: SqlStatement","ensureLedgerTableStatement: SqlStatement","params: readonly unknown[]","DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","step","entries: Record<string, SqlOperationEntry>","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../../../6-adapters/postgres/dist/sql-utils-CSfAGEwF.mjs","../../../6-adapters/postgres/dist/codec-ids-BwjcIf74.mjs","../../../6-adapters/postgres/dist/codecs-C3wlpdV7.mjs","../../../6-adapters/postgres/dist/descriptor-meta-DemWrTfB.mjs","../../../../1-framework/2-authoring/ids/dist/index.mjs","../../../6-adapters/postgres/dist/control.mjs","../src/core/migrations/planner-strategies.ts","../src/core/migrations/descriptor-planner.ts","../../../6-adapters/postgres/dist/adapter-7pXt8ej9.mjs","../src/core/migrations/planner-type-resolution.ts","../src/core/migrations/planner-sql-checks.ts","../src/core/migrations/planner-ddl-builders.ts","../src/core/migrations/operation-resolver.ts","../src/core/migrations/planner-identity-values.ts","../src/core/migrations/planner-target-details.ts","../src/core/migrations/planner-recipes.ts","../src/core/migrations/planner-reconciliation.ts","../src/core/migrations/planner-schema-lookup.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_TEXT_CODEC_ID, SQL_TIMESTAMP_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_TIMESTAMP_CODEC_ID as D, SQL_TEXT_CODEC_ID as E, SQL_VARCHAR_CODEC_ID as O, 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-BwjcIf74.mjs.map","import { S as PG_VARCHAR_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, x as PG_VARBIT_CODEC_ID, y as PG_TIMETZ_CODEC_ID } from \"./codec-ids-BwjcIf74.mjs\";\nimport { codec, defineCodecs, sqlCodecDefinitions } from \"@prisma-next/sql-relational-core/ast\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\nimport { type } from \"arktype\";\n\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/codecs.ts\nconst lengthParamsSchema = type({ length: \"number.integer > 0\" });\nconst numericParamsSchema = type({\n\tprecision: \"number.integer > 0 & number.integer <= 1000\",\n\t\"scale?\": \"number.integer >= 0\"\n});\nconst precisionParamsSchema = type({ \"precision?\": \"number.integer >= 0 & number.integer <= 6\" });\nfunction renderLength(typeName, typeParams) {\n\tconst length = typeParams[\"length\"];\n\tif (length === void 0) return;\n\tif (typeof length !== \"number\" || !Number.isFinite(length) || !Number.isInteger(length)) throw new Error(`renderOutputType: expected integer \"length\" in typeParams for ${typeName}, got ${String(length)}`);\n\treturn `${typeName}<${length}>`;\n}\nfunction renderPrecision(typeName, typeParams) {\n\tconst precision = typeParams[\"precision\"];\n\tif (precision === void 0) return typeName;\n\tif (typeof precision !== \"number\" || !Number.isFinite(precision) || !Number.isInteger(precision)) throw new Error(`renderOutputType: expected integer \"precision\" in typeParams for ${typeName}, got ${String(precision)}`);\n\treturn `${typeName}<${precision}>`;\n}\nfunction renderJsonOutputType(typeParams) {\n\tconst typeName = typeParams[\"type\"];\n\tif (typeof typeName === \"string\" && typeName.trim().length > 0) return typeName.trim();\n\tconst schema = typeParams[\"schemaJson\"];\n\tif (schema && typeof schema === \"object\") return renderTypeScriptTypeFromJsonSchema(schema);\n\tthrow new Error(`renderOutputType: JSON codec typeParams must contain \"type\" (string) or \"schemaJson\" (object), got keys: ${Object.keys(typeParams).join(\", \")}`);\n}\nfunction aliasCodec(base, options) {\n\treturn {\n\t\tid: options.typeId,\n\t\ttargetTypes: options.targetTypes,\n\t\t...ifDefined(\"meta\", options.meta),\n\t\t...ifDefined(\"paramsSchema\", base.paramsSchema),\n\t\t...ifDefined(\"init\", base.init),\n\t\t...ifDefined(\"encode\", base.encode),\n\t\t...ifDefined(\"traits\", base.traits),\n\t\t...ifDefined(\"renderOutputType\", base.renderOutputType),\n\t\tdecode: base.decode,\n\t\tencodeJson: base.encodeJson,\n\t\tdecodeJson: base.decodeJson\n\t};\n}\nconst sqlCharCodec = sqlCodecDefinitions.char.codec;\nconst sqlVarcharCodec = sqlCodecDefinitions.varchar.codec;\nconst sqlIntCodec = sqlCodecDefinitions.int.codec;\nconst sqlFloatCodec = sqlCodecDefinitions.float.codec;\nconst sqlTextCodec = sqlCodecDefinitions.text.codec;\nconst sqlTimestampCodec = sqlCodecDefinitions.timestamp.codec;\nconst pgTextCodec = codec({\n\ttypeId: PG_TEXT_CODEC_ID,\n\ttargetTypes: [\"text\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"textual\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"text\" } } } }\n});\nconst pgCharCodec = aliasCodec(sqlCharCodec, {\n\ttypeId: PG_CHAR_CODEC_ID,\n\ttargetTypes: [\"character\"],\n\tmeta: { db: { sql: { postgres: { nativeType: \"character\" } } } }\n});\nconst pgVarcharCodec = aliasCodec(sqlVarcharCodec, {\n\ttypeId: PG_VARCHAR_CODEC_ID,\n\ttargetTypes: [\"character varying\"],\n\tmeta: { db: { sql: { postgres: { nativeType: \"character varying\" } } } }\n});\nconst pgIntCodec = aliasCodec(sqlIntCodec, {\n\ttypeId: PG_INT_CODEC_ID,\n\ttargetTypes: [\"int4\"],\n\tmeta: { db: { sql: { postgres: { nativeType: \"integer\" } } } }\n});\nconst pgFloatCodec = aliasCodec(sqlFloatCodec, {\n\ttypeId: PG_FLOAT_CODEC_ID,\n\ttargetTypes: [\"float8\"],\n\tmeta: { db: { sql: { postgres: { nativeType: \"double precision\" } } } }\n});\nconst pgInt4Codec = codec({\n\ttypeId: PG_INT4_CODEC_ID,\n\ttargetTypes: [\"int4\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"integer\" } } } }\n});\nconst pgNumericCodec = codec({\n\ttypeId: PG_NUMERIC_CODEC_ID,\n\ttargetTypes: [\"numeric\", \"decimal\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => {\n\t\tif (typeof wire === \"number\") return String(wire);\n\t\treturn wire;\n\t},\n\tparamsSchema: numericParamsSchema,\n\trenderOutputType: (typeParams) => {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (precision === void 0) return void 0;\n\t\tif (typeof precision !== \"number\" || !Number.isFinite(precision) || !Number.isInteger(precision)) throw new Error(`renderOutputType: expected integer \"precision\" in typeParams for Numeric, got ${String(precision)}`);\n\t\tconst scale = typeParams[\"scale\"];\n\t\treturn typeof scale === \"number\" ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;\n\t},\n\tmeta: { db: { sql: { postgres: { nativeType: \"numeric\" } } } }\n});\nconst pgInt2Codec = codec({\n\ttypeId: PG_INT2_CODEC_ID,\n\ttargetTypes: [\"int2\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"smallint\" } } } }\n});\nconst pgInt8Codec = codec({\n\ttypeId: PG_INT8_CODEC_ID,\n\ttargetTypes: [\"int8\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"bigint\" } } } }\n});\nconst pgFloat4Codec = codec({\n\ttypeId: PG_FLOAT4_CODEC_ID,\n\ttargetTypes: [\"float4\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"real\" } } } }\n});\nconst pgFloat8Codec = codec({\n\ttypeId: PG_FLOAT8_CODEC_ID,\n\ttargetTypes: [\"float8\"],\n\ttraits: [\n\t\t\"equality\",\n\t\t\"order\",\n\t\t\"numeric\"\n\t],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"double precision\" } } } }\n});\nconst pgTimestampCodec = codec({\n\ttypeId: PG_TIMESTAMP_CODEC_ID,\n\ttargetTypes: [\"timestamp\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => {\n\t\tif (value instanceof Date) return value.toISOString();\n\t\tif (typeof value === \"string\") return value;\n\t\treturn String(value);\n\t},\n\tdecode: (wire) => {\n\t\tif (wire instanceof Date) return wire.toISOString();\n\t\treturn wire;\n\t},\n\tencodeJson: (value) => value instanceof Date ? value.toISOString() : value,\n\tdecodeJson: (json) => {\n\t\tif (typeof json !== \"string\") throw new Error(`Expected ISO date string for pg/timestamp@1, got ${typeof json}`);\n\t\tconst date = new Date(json);\n\t\tif (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date string for pg/timestamp@1: ${json}`);\n\t\treturn date;\n\t},\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Timestamp\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"timestamp without time zone\" } } } }\n});\nconst pgTimestamptzCodec = codec({\n\ttypeId: PG_TIMESTAMPTZ_CODEC_ID,\n\ttargetTypes: [\"timestamptz\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => {\n\t\tif (value instanceof Date) return value.toISOString();\n\t\tif (typeof value === \"string\") return value;\n\t\treturn String(value);\n\t},\n\tdecode: (wire) => {\n\t\tif (wire instanceof Date) return wire.toISOString();\n\t\treturn wire;\n\t},\n\tencodeJson: (value) => value instanceof Date ? value.toISOString() : value,\n\tdecodeJson: (json) => {\n\t\tif (typeof json !== \"string\") throw new Error(`Expected ISO date string for pg/timestamptz@1, got ${typeof json}`);\n\t\tconst date = new Date(json);\n\t\tif (Number.isNaN(date.getTime())) throw new Error(`Invalid ISO date string for pg/timestamptz@1: ${json}`);\n\t\treturn date;\n\t},\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Timestamptz\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"timestamp with time zone\" } } } }\n});\nconst pgTimeCodec = codec({\n\ttypeId: PG_TIME_CODEC_ID,\n\ttargetTypes: [\"time\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Time\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"time\" } } } }\n});\nconst pgTimetzCodec = codec({\n\ttypeId: PG_TIMETZ_CODEC_ID,\n\ttargetTypes: [\"timetz\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Timetz\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"timetz\" } } } }\n});\nconst pgBoolCodec = codec({\n\ttypeId: PG_BOOL_CODEC_ID,\n\ttargetTypes: [\"bool\"],\n\ttraits: [\"equality\", \"boolean\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tmeta: { db: { sql: { postgres: { nativeType: \"boolean\" } } } }\n});\nconst pgBitCodec = codec({\n\ttypeId: PG_BIT_CODEC_ID,\n\ttargetTypes: [\"bit\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tparamsSchema: lengthParamsSchema,\n\trenderOutputType: (typeParams) => renderLength(\"Bit\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"bit\" } } } }\n});\nconst pgVarbitCodec = codec({\n\ttypeId: PG_VARBIT_CODEC_ID,\n\ttargetTypes: [\"bit varying\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\tparamsSchema: lengthParamsSchema,\n\trenderOutputType: (typeParams) => renderLength(\"VarBit\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"bit varying\" } } } }\n});\nconst pgEnumCodec = codec({\n\ttypeId: PG_ENUM_CODEC_ID,\n\ttargetTypes: [\"enum\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => wire,\n\trenderOutputType: (typeParams) => {\n\t\tconst values = typeParams[\"values\"];\n\t\tif (!Array.isArray(values)) throw new Error(`renderOutputType: expected array \"values\" in typeParams for enum, got ${typeof values}`);\n\t\treturn values.map((value) => `'${String(value).replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"\\\\'\")}'`).join(\" | \");\n\t}\n});\nconst pgIntervalCodec = codec({\n\ttypeId: PG_INTERVAL_CODEC_ID,\n\ttargetTypes: [\"interval\"],\n\ttraits: [\"equality\", \"order\"],\n\tencode: (value) => value,\n\tdecode: (wire) => {\n\t\tif (typeof wire === \"string\") return wire;\n\t\treturn JSON.stringify(wire);\n\t},\n\tparamsSchema: precisionParamsSchema,\n\trenderOutputType: (typeParams) => renderPrecision(\"Interval\", typeParams),\n\tmeta: { db: { sql: { postgres: { nativeType: \"interval\" } } } }\n});\nconst pgJsonCodec = codec({\n\ttypeId: PG_JSON_CODEC_ID,\n\ttargetTypes: [\"json\"],\n\ttraits: [],\n\tencode: (value) => JSON.stringify(value),\n\tdecode: (wire) => typeof wire === \"string\" ? JSON.parse(wire) : wire,\n\trenderOutputType: renderJsonOutputType,\n\tmeta: { db: { sql: { postgres: { nativeType: \"json\" } } } }\n});\nconst pgJsonbCodec = codec({\n\ttypeId: PG_JSONB_CODEC_ID,\n\ttargetTypes: [\"jsonb\"],\n\ttraits: [\"equality\"],\n\tencode: (value) => JSON.stringify(value),\n\tdecode: (wire) => typeof wire === \"string\" ? JSON.parse(wire) : wire,\n\trenderOutputType: renderJsonOutputType,\n\tmeta: { db: { sql: { postgres: { nativeType: \"jsonb\" } } } }\n});\nconst codecs = defineCodecs().add(\"char\", sqlCharCodec).add(\"varchar\", sqlVarcharCodec).add(\"int\", sqlIntCodec).add(\"float\", sqlFloatCodec).add(\"sql-text\", sqlTextCodec).add(\"sql-timestamp\", sqlTimestampCodec).add(\"text\", pgTextCodec).add(\"character\", pgCharCodec).add(\"character varying\", pgVarcharCodec).add(\"integer\", pgIntCodec).add(\"double precision\", pgFloatCodec).add(\"int4\", pgInt4Codec).add(\"int2\", pgInt2Codec).add(\"int8\", pgInt8Codec).add(\"float4\", pgFloat4Codec).add(\"float8\", pgFloat8Codec).add(\"numeric\", pgNumericCodec).add(\"timestamp\", pgTimestampCodec).add(\"timestamptz\", pgTimestamptzCodec).add(\"time\", pgTimeCodec).add(\"timetz\", pgTimetzCodec).add(\"bool\", pgBoolCodec).add(\"bit\", pgBitCodec).add(\"bit varying\", pgVarbitCodec).add(\"interval\", pgIntervalCodec).add(\"enum\", pgEnumCodec).add(\"json\", pgJsonCodec).add(\"jsonb\", pgJsonbCodec);\nconst codecDefinitions = codecs.codecDefinitions;\nconst dataTypes = codecs.dataTypes;\n\n//#endregion\nexport { dataTypes as n, codecDefinitions as t };\n//# sourceMappingURL=codecs-C3wlpdV7.mjs.map","import { C as SQL_CHAR_CODEC_ID, D as SQL_TIMESTAMP_CODEC_ID, E as SQL_TEXT_CODEC_ID, O 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-BwjcIf74.mjs\";\nimport { t as codecDefinitions } from \"./codecs-C3wlpdV7.mjs\";\nimport { a as validateEnumValueLength, i as quoteIdentifier, n as escapeLiteral, r as qualifyName } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { arraysEqual } from \"@prisma-next/family-sql/schema-verify\";\n\n//#region src/core/enum-control-hooks.ts\nconst ENUM_INTROSPECT_QUERY = `\n SELECT\n n.nspname AS schema_name,\n t.typname AS type_name,\n array_agg(e.enumlabel ORDER BY e.enumsortorder) AS values\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n JOIN pg_enum e ON t.oid = e.enumtypid\n WHERE n.nspname = $1\n GROUP BY n.nspname, t.typname\n ORDER BY n.nspname, t.typname\n`;\n/**\n* Type guard for string arrays. Used for runtime validation of introspected data.\n*/\nfunction isStringArray(value) {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n/**\n* Parses a PostgreSQL array value into a JavaScript string array.\n*\n* PostgreSQL's `pg` library may return `array_agg` results either as:\n* - A JavaScript array (when type parsers are configured)\n* - A string in PostgreSQL array literal format: `{value1,value2,...}`\n*\n* Handles PostgreSQL's quoting rules for array elements:\n* - Elements containing commas, double quotes, backslashes, or whitespace are double-quoted\n* - Inside quoted elements, `\\\"` represents `\"` and `\\\\` represents `\\`\n*\n* @param value - The value to parse (array or PostgreSQL array string)\n* @returns A string array, or null if the value cannot be parsed\n*/\nfunction parsePostgresArray(value) {\n\tif (isStringArray(value)) return value;\n\tif (typeof value === \"string\" && value.startsWith(\"{\") && value.endsWith(\"}\")) {\n\t\tconst inner = value.slice(1, -1);\n\t\tif (inner === \"\") return [];\n\t\treturn parseArrayElements(inner);\n\t}\n\treturn null;\n}\nfunction parseArrayElements(input) {\n\tconst result = [];\n\tlet i = 0;\n\twhile (i < input.length) {\n\t\tif (input[i] === \",\") {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (input[i] === \"\\\"\") {\n\t\t\ti++;\n\t\t\tlet element = \"\";\n\t\t\twhile (i < input.length && input[i] !== \"\\\"\") {\n\t\t\t\tif (input[i] === \"\\\\\" && i + 1 < input.length) {\n\t\t\t\t\ti++;\n\t\t\t\t\telement += input[i];\n\t\t\t\t} else element += input[i];\n\t\t\t\ti++;\n\t\t\t}\n\t\t\ti++;\n\t\t\tresult.push(element);\n\t\t} else {\n\t\t\tconst nextComma = input.indexOf(\",\", i);\n\t\t\tif (nextComma === -1) {\n\t\t\t\tresult.push(input.slice(i).trim());\n\t\t\t\ti = input.length;\n\t\t\t} else {\n\t\t\t\tresult.push(input.slice(i, nextComma).trim());\n\t\t\t\ti = nextComma;\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n/**\n* Extracts enum values from a StorageTypeInstance.\n* Returns null if values are missing or invalid.\n*/\nfunction getEnumValues(typeInstance) {\n\tconst values = typeInstance.typeParams?.[\"values\"];\n\treturn isStringArray(values) ? values : null;\n}\n/**\n* Reads existing enum values from the schema IR for a given native type.\n* Uses optional chaining to simplify navigation through the annotations structure.\n*/\nfunction readExistingEnumValues(schema, nativeType) {\n\tconst existing = ((schema.annotations?.[\"pg\"])?.[\"storageTypes\"])?.[nativeType];\n\tif (!existing || existing.codecId !== PG_ENUM_CODEC_ID) return null;\n\treturn getEnumValues(existing);\n}\n/**\n* Determines what changes are needed to transform existing enum values to desired values.\n*\n* Returns one of:\n* - `unchanged`: No changes needed, values match exactly\n* - `add_values`: New values can be safely appended (PostgreSQL supports this)\n* - `rebuild`: Full enum rebuild required (value removal, reordering, or both)\n*\n* Note: PostgreSQL enums can only have values added (not removed or reordered) without\n* a full type rebuild involving temp type creation and column migration.\n*\n* @param existing - Current enum values in the database\n* @param desired - Target enum values from the contract\n* @returns The type of change required\n*/\nfunction determineEnumDiff(existing, desired) {\n\tif (arraysEqual(existing, desired)) return { kind: \"unchanged\" };\n\tconst existingSet = new Set(existing);\n\tconst desiredSet = new Set(desired);\n\tconst missingValues = desired.filter((value) => !existingSet.has(value));\n\tconst removedValues = existing.filter((value) => !desiredSet.has(value));\n\tconst orderMismatch = missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);\n\tif (removedValues.length > 0 || orderMismatch) return {\n\t\tkind: \"rebuild\",\n\t\tremovedValues\n\t};\n\treturn {\n\t\tkind: \"add_values\",\n\t\tvalues: missingValues\n\t};\n}\nfunction enumTypeExistsCheck(schemaName, typeName, exists = true) {\n\treturn `SELECT ${exists ? \"EXISTS\" : \"NOT EXISTS\"} (\n SELECT 1\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname = '${escapeLiteral(schemaName)}'\n AND t.typname = '${escapeLiteral(typeName)}'\n)`;\n}\nfunction buildCreateEnumOperation(typeName, nativeType, schemaName, values) {\n\tfor (const value of values) validateEnumValueLength(value, typeName);\n\tconst literalValues = values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst qualifiedType = qualifyName(schemaName, nativeType);\n\treturn {\n\t\tid: `type.${typeName}`,\n\t\tlabel: `Create type ${typeName}`,\n\t\tsummary: `Creates enum type ${typeName}`,\n\t\toperationClass: \"additive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${nativeType}\" does not exist`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType, false)\n\t\t}],\n\t\texecute: [{\n\t\t\tdescription: `create type \"${nativeType}\"`,\n\t\t\tsql: `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`\n\t\t}],\n\t\tpostcheck: [{\n\t\t\tdescription: `verify type \"${nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(schemaName, nativeType)\n\t\t}]\n\t};\n}\n/**\n* Computes the optimal position for inserting a new enum value to maintain\n* the desired order relative to existing values.\n*\n* PostgreSQL's `ALTER TYPE ADD VALUE` supports BEFORE/AFTER positioning.\n* This function finds the best reference value by:\n* 1. Looking for the nearest preceding value that already exists\n* 2. Falling back to the nearest following value if no preceding exists\n* 3. Defaulting to end-of-list if no reference is found\n*\n* @param options.desired - The target ordered list of all enum values\n* @param options.desiredIndex - Index of the value being inserted in the desired list\n* @param options.current - Current list of enum values (being built up incrementally)\n* @returns SQL clause (e.g., \" AFTER 'x'\") and insert position for tracking\n*/\nfunction computeInsertPosition(options) {\n\tconst { desired, desiredIndex, current } = options;\n\tconst currentSet = new Set(current);\n\tconst previous = desired.slice(0, desiredIndex).reverse().find((candidate) => currentSet.has(candidate));\n\tconst next = desired.slice(desiredIndex + 1).find((candidate) => currentSet.has(candidate));\n\treturn {\n\t\tclause: previous ? ` AFTER '${escapeLiteral(previous)}'` : next ? ` BEFORE '${escapeLiteral(next)}'` : \"\",\n\t\tinsertAt: previous ? current.indexOf(previous) + 1 : next ? current.indexOf(next) : current.length\n\t};\n}\n/**\n* Builds operations to add new enum values to an existing PostgreSQL enum type.\n*\n* Each new value is added with `ALTER TYPE ... ADD VALUE IF NOT EXISTS` for idempotency.\n* Values are inserted in the correct order using BEFORE/AFTER positioning to match\n* the desired final order.\n*\n* This is a safe, non-destructive operation - existing data is not affected.\n*\n* @param options.typeName - Contract-level type name (e.g., 'Role')\n* @param options.nativeType - PostgreSQL type name (e.g., 'role')\n* @param options.schemaName - PostgreSQL schema (e.g., 'public')\n* @param options.desired - Target ordered list of all enum values\n* @param options.existing - Current enum values in the database\n* @returns Array of migration operations to add each missing value\n*/\nfunction buildAddValueOperations(options) {\n\tconst { typeName, nativeType, schemaName } = options;\n\tconst current = [...options.existing];\n\tconst currentSet = new Set(current);\n\tconst operations = [];\n\tfor (let index = 0; index < options.desired.length; index += 1) {\n\t\tconst value = options.desired[index];\n\t\tif (value === void 0) continue;\n\t\tif (currentSet.has(value)) continue;\n\t\tvalidateEnumValueLength(value, typeName);\n\t\tconst { clause, insertAt } = computeInsertPosition({\n\t\t\tdesired: options.desired,\n\t\t\tdesiredIndex: index,\n\t\t\tcurrent\n\t\t});\n\t\toperations.push({\n\t\t\tid: `type.${typeName}.value.${value}`,\n\t\t\tlabel: `Add value ${value} to ${typeName}`,\n\t\t\tsummary: `Adds enum value ${value} to ${typeName}`,\n\t\t\toperationClass: \"widening\",\n\t\t\ttarget: { id: \"postgres\" },\n\t\t\tprecheck: [],\n\t\t\texecute: [{\n\t\t\t\tdescription: `add value \"${value}\" if not exists`,\n\t\t\t\tsql: `ALTER TYPE ${qualifyName(schemaName, nativeType)} ADD VALUE IF NOT EXISTS '${escapeLiteral(value)}'${clause}`\n\t\t\t}],\n\t\t\tpostcheck: []\n\t\t});\n\t\tcurrent.splice(insertAt, 0, value);\n\t\tcurrentSet.add(value);\n\t}\n\treturn operations;\n}\n/**\n* Collects columns using the enum type from the contract (desired state).\n* Used for type-safe reference tracking.\n*/\nfunction collectEnumColumnsFromContract(contract, typeName, nativeType) {\n\tconst columns = [];\n\tfor (const [tableName, table] of Object.entries(contract.storage.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.typeRef === typeName || column.nativeType === nativeType && column.codecId === PG_ENUM_CODEC_ID) columns.push({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects columns using the enum type from the schema IR (live database state).\n* This ensures we find ALL dependent columns, including those added outside the contract\n* (e.g., manual DDL), which is critical for safe enum rebuild operations.\n*/\nfunction collectEnumColumnsFromSchema(schema, nativeType) {\n\tconst columns = [];\n\tfor (const [tableName, table] of Object.entries(schema.tables)) for (const [columnName, column] of Object.entries(table.columns)) if (column.nativeType === nativeType) columns.push({\n\t\ttable: tableName,\n\t\tcolumn: columnName\n\t});\n\treturn columns;\n}\n/**\n* Collects all columns using the enum type from both contract AND live database.\n* Merges and deduplicates to ensure we migrate ALL dependent columns during rebuild.\n*\n* This is critical for data integrity: if a column exists in the database using\n* this enum but is not in the contract (e.g., added via manual DDL), we must\n* still migrate it to avoid DROP TYPE failures.\n*/\nfunction collectAllEnumColumns(contract, schema, typeName, nativeType) {\n\tconst contractColumns = collectEnumColumnsFromContract(contract, typeName, nativeType);\n\tconst schemaColumns = collectEnumColumnsFromSchema(schema, nativeType);\n\tconst seen = /* @__PURE__ */ new Set();\n\tconst result = [];\n\tfor (const col of [...contractColumns, ...schemaColumns]) {\n\t\tconst key = `${col.table}.${col.column}`;\n\t\tif (!seen.has(key)) {\n\t\t\tseen.add(key);\n\t\t\tresult.push(col);\n\t\t}\n\t}\n\treturn result.sort((a, b) => {\n\t\tconst tableCompare = a.table.localeCompare(b.table);\n\t\treturn tableCompare !== 0 ? tableCompare : a.column.localeCompare(b.column);\n\t});\n}\n/**\n* Builds a SQL check to verify a column's type matches an expected type.\n*/\nfunction columnTypeCheck(options) {\n\treturn `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(options.schemaName)}'\n AND table_name = '${escapeLiteral(options.tableName)}'\n AND column_name = '${escapeLiteral(options.columnName)}'\n AND udt_name = '${escapeLiteral(options.expectedType)}'\n)`;\n}\n/** PostgreSQL maximum identifier length (NAMEDATALEN - 1) */\nconst MAX_IDENTIFIER_LENGTH = 63;\n/** Suffix added to enum type names during rebuild operations */\nconst REBUILD_SUFFIX = \"__pn_rebuild\";\n/**\n* Builds an SQL check to verify no rows contain any of the removed enum values.\n* This prevents data loss during enum rebuild operations.\n*\n* @param schemaName - PostgreSQL schema name\n* @param tableName - Table containing the enum column\n* @param columnName - Column using the enum type\n* @param removedValues - Array of enum values being removed\n* @returns SQL query that returns true if no rows contain removed values\n*/\nfunction noRemovedValuesExistCheck(schemaName, tableName, columnName, removedValues) {\n\tif (removedValues.length === 0) return \"SELECT true\";\n\tconst valuesList = removedValues.map((v) => `'${escapeLiteral(v)}'`).join(\", \");\n\treturn `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualifyName(schemaName, tableName)}\n WHERE ${quoteIdentifier(columnName)}::text IN (${valuesList})\n LIMIT 1\n)`;\n}\n/**\n* Builds a migration operation to recreate a PostgreSQL enum type with updated values.\n*\n* This is required when:\n* - Enum values are removed (PostgreSQL doesn't support direct removal)\n* - Enum values are reordered (PostgreSQL doesn't support reordering)\n*\n* The operation:\n* 1. Creates a new enum type with the desired values (temp name)\n* 2. Migrates all columns to use the new type via text cast\n* 3. Drops the original type\n* 4. Renames the temp type to the original name\n*\n* IMPORTANT: If values are being removed and data exists using those values,\n* the operation will fail at the precheck stage with a clear error message.\n* This prevents silent data loss.\n*\n* @param options.typeName - Contract-level type name\n* @param options.nativeType - PostgreSQL type name\n* @param options.schemaName - PostgreSQL schema\n* @param options.values - Desired final enum values\n* @param options.removedValues - Values being removed (for data loss checks)\n* @param options.contract - Full contract for column discovery\n* @param options.schema - Current schema IR for column discovery\n* @returns Migration operation for full enum rebuild\n*/\nfunction buildRecreateEnumOperation(options) {\n\tconst tempTypeName = `${options.nativeType}${REBUILD_SUFFIX}`;\n\tif (tempTypeName.length > MAX_IDENTIFIER_LENGTH) {\n\t\tconst maxBaseLength = MAX_IDENTIFIER_LENGTH - 12;\n\t\tthrow new Error(`Enum type name \"${options.nativeType}\" is too long for rebuild operation. Maximum length is ${maxBaseLength} characters (type name + \"${REBUILD_SUFFIX}\" suffix must fit within PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character identifier limit).`);\n\t}\n\tconst qualifiedOriginal = qualifyName(options.schemaName, options.nativeType);\n\tconst qualifiedTemp = qualifyName(options.schemaName, tempTypeName);\n\tconst literalValues = options.values.map((value) => `'${escapeLiteral(value)}'`).join(\", \");\n\tconst columnRefs = collectAllEnumColumns(options.contract, options.schema, options.typeName, options.nativeType);\n\tconst alterColumns = columnRefs.map((ref) => ({\n\t\tdescription: `alter ${ref.table}.${ref.column} to ${tempTypeName}`,\n\t\tsql: `ALTER TABLE ${qualifyName(options.schemaName, ref.table)}\nALTER COLUMN ${quoteIdentifier(ref.column)}\nTYPE ${qualifiedTemp}\nUSING ${quoteIdentifier(ref.column)}::text::${qualifiedTemp}`\n\t}));\n\tconst postchecks = [\n\t\t{\n\t\t\tdescription: `verify type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t},\n\t\t{\n\t\t\tdescription: `verify temp type \"${tempTypeName}\" was removed`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, tempTypeName, false)\n\t\t},\n\t\t...columnRefs.map((ref) => ({\n\t\t\tdescription: `verify ${ref.table}.${ref.column} uses type \"${options.nativeType}\"`,\n\t\t\tsql: columnTypeCheck({\n\t\t\t\tschemaName: options.schemaName,\n\t\t\t\ttableName: ref.table,\n\t\t\t\tcolumnName: ref.column,\n\t\t\t\texpectedType: options.nativeType\n\t\t\t})\n\t\t}))\n\t];\n\treturn {\n\t\tid: `type.${options.typeName}.rebuild`,\n\t\tlabel: `Rebuild type ${options.typeName}`,\n\t\tsummary: `Recreates enum type ${options.typeName} with updated values`,\n\t\toperationClass: \"destructive\",\n\t\ttarget: { id: \"postgres\" },\n\t\tprecheck: [{\n\t\t\tdescription: `ensure type \"${options.nativeType}\" exists`,\n\t\t\tsql: enumTypeExistsCheck(options.schemaName, options.nativeType)\n\t\t}, ...options.removedValues.length > 0 ? columnRefs.map((ref) => ({\n\t\t\tdescription: `ensure no rows in ${ref.table}.${ref.column} contain removed values (${options.removedValues.join(\", \")})`,\n\t\t\tsql: noRemovedValuesExistCheck(options.schemaName, ref.table, ref.column, options.removedValues)\n\t\t})) : []],\n\t\texecute: [\n\t\t\t{\n\t\t\t\tdescription: `drop orphaned temp type \"${tempTypeName}\" if exists`,\n\t\t\t\tsql: `DROP TYPE IF EXISTS ${qualifiedTemp}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `create temp type \"${tempTypeName}\"`,\n\t\t\t\tsql: `CREATE TYPE ${qualifiedTemp} AS ENUM (${literalValues})`\n\t\t\t},\n\t\t\t...alterColumns,\n\t\t\t{\n\t\t\t\tdescription: `drop type \"${options.nativeType}\"`,\n\t\t\t\tsql: `DROP TYPE ${qualifiedOriginal}`\n\t\t\t},\n\t\t\t{\n\t\t\t\tdescription: `rename type \"${tempTypeName}\" to \"${options.nativeType}\"`,\n\t\t\t\tsql: `ALTER TYPE ${qualifiedTemp} RENAME TO ${quoteIdentifier(options.nativeType)}`\n\t\t\t}\n\t\t],\n\t\tpostcheck: postchecks\n\t};\n}\n/**\n* Postgres enum hooks for planning, verifying, and introspecting `storage.types`.\n*/\nconst pgEnumControlHooks = {\n\tplanTypeOperations: ({ typeName, typeInstance, contract, schema, schemaName }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired || desired.length === 0) return { operations: [] };\n\t\tconst schemaNamespace = schemaName ?? \"public\";\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return { operations: [buildCreateEnumOperation(typeName, typeInstance.nativeType, schemaNamespace, desired)] };\n\t\tconst diff = determineEnumDiff(existing, desired);\n\t\tif (diff.kind === \"unchanged\") return { operations: [] };\n\t\tif (diff.kind === \"rebuild\") return { operations: [buildRecreateEnumOperation({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tvalues: desired,\n\t\t\tremovedValues: diff.removedValues,\n\t\t\tcontract,\n\t\t\tschema\n\t\t})] };\n\t\treturn { operations: buildAddValueOperations({\n\t\t\ttypeName,\n\t\t\tnativeType: typeInstance.nativeType,\n\t\t\tschemaName: schemaNamespace,\n\t\t\tdesired,\n\t\t\texisting\n\t\t}) };\n\t},\n\tverifyType: ({ typeName, typeInstance, schema }) => {\n\t\tconst desired = getEnumValues(typeInstance);\n\t\tif (!desired) return [];\n\t\tconst existing = readExistingEnumValues(schema, typeInstance.nativeType);\n\t\tif (!existing) return [{\n\t\t\tkind: \"type_missing\",\n\t\t\ttypeName,\n\t\t\tmessage: `Type \"${typeName}\" is missing from database`\n\t\t}];\n\t\tconst diff = determineEnumDiff(existing, desired);\n\t\tif (diff.kind === \"unchanged\") return [];\n\t\tconst existingSet = new Set(existing);\n\t\tconst desiredSet = new Set(desired);\n\t\tconst addedValues = desired.filter((v) => !existingSet.has(v));\n\t\tconst removedValues = existing.filter((v) => !desiredSet.has(v));\n\t\treturn [{\n\t\t\tkind: \"enum_values_changed\",\n\t\t\ttypeName,\n\t\t\taddedValues,\n\t\t\tremovedValues,\n\t\t\tmessage: diff.kind === \"add_values\" ? `Enum type \"${typeName}\" needs new values: ${addedValues.join(\", \")}` : `Enum type \"${typeName}\" values changed (requires rebuild): +[${addedValues.join(\", \")}] -[${removedValues.join(\", \")}]`\n\t\t}];\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/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});\nfunction isPositiveInteger(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value > 0;\n}\nfunction isNonNegativeInteger(value) {\n\treturn typeof value === \"number\" && Number.isFinite(value) && Number.isInteger(value) && value >= 0;\n}\nfunction expandLength({ nativeType, typeParams }) {\n\tif (!typeParams || !(\"length\" in typeParams)) return nativeType;\n\tconst length = typeParams[\"length\"];\n\tif (!isPositiveInteger(length)) throw new Error(`Invalid \"length\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(length)}`);\n\treturn `${nativeType}(${length})`;\n}\nfunction expandPrecision({ nativeType, typeParams }) {\n\tif (!typeParams || !(\"precision\" in typeParams)) return nativeType;\n\tconst precision = typeParams[\"precision\"];\n\tif (!isPositiveInteger(precision)) throw new Error(`Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`);\n\treturn `${nativeType}(${precision})`;\n}\nfunction expandNumeric({ nativeType, typeParams }) {\n\tconst hasPrecision = typeParams && \"precision\" in typeParams;\n\tconst hasScale = typeParams && \"scale\" in typeParams;\n\tif (!hasPrecision && !hasScale) return nativeType;\n\tif (!hasPrecision && hasScale) throw new Error(`Invalid type parameters for \"${nativeType}\": \"scale\" requires \"precision\" to be specified`);\n\tif (hasPrecision) {\n\t\tconst precision = typeParams[\"precision\"];\n\t\tif (!isPositiveInteger(precision)) throw new Error(`Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`);\n\t\tif (hasScale) {\n\t\t\tconst scale = typeParams[\"scale\"];\n\t\t\tif (!isNonNegativeInteger(scale)) throw new Error(`Invalid \"scale\" type parameter for \"${nativeType}\": expected a non-negative integer, got ${JSON.stringify(scale)}`);\n\t\t\treturn `${nativeType}(${precision},${scale})`;\n\t\t}\n\t\treturn `${nativeType}(${precision})`;\n\t}\n\treturn nativeType;\n}\nconst lengthHooks = { expandNativeType: expandLength };\nconst precisionHooks = { expandNativeType: expandPrecision };\nconst numericHooks = { expandNativeType: expandNumeric };\nconst identityHooks = { expandNativeType: ({ nativeType }) => nativeType };\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: {\n\t\t\tenums: true,\n\t\t\treturning: true,\n\t\t\tdefaultInInsert: true\n\t\t}\n\t},\n\ttypes: {\n\t\tcodecTypes: {\n\t\t\tcodecInstances: Object.values(codecDefinitions).map((def) => def.codec),\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\ttypeImports: [\n\t\t\t\t{\n\t\t\t\t\tpackage: \"@prisma-next/adapter-postgres/codec-types\",\n\t\t\t\t\tnamed: \"JsonValue\",\n\t\t\t\t\talias: \"JsonValue\"\n\t\t\t\t},\n\t\t\t\tcodecTypeImport(\"Char\"),\n\t\t\t\tcodecTypeImport(\"Varchar\"),\n\t\t\t\tcodecTypeImport(\"Numeric\"),\n\t\t\t\tcodecTypeImport(\"Bit\"),\n\t\t\t\tcodecTypeImport(\"VarBit\"),\n\t\t\t\tcodecTypeImport(\"Timestamp\"),\n\t\t\t\tcodecTypeImport(\"Timestamptz\"),\n\t\t\t\tcodecTypeImport(\"Time\"),\n\t\t\t\tcodecTypeImport(\"Timetz\"),\n\t\t\t\tcodecTypeImport(\"Interval\")\n\t\t\t],\n\t\t\tcontrolPlaneHooks: {\n\t\t\t\t[SQL_CHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[SQL_VARCHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[SQL_TIMESTAMP_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_CHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_VARCHAR_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_NUMERIC_CODEC_ID]: numericHooks,\n\t\t\t\t[PG_BIT_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_VARBIT_CODEC_ID]: lengthHooks,\n\t\t\t\t[PG_TIMESTAMP_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIMESTAMPTZ_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIME_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_TIMETZ_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_INTERVAL_CODEC_ID]: precisionHooks,\n\t\t\t\t[PG_ENUM_CODEC_ID]: pgEnumControlHooks,\n\t\t\t\t[PG_JSON_CODEC_ID]: identityHooks,\n\t\t\t\t[PG_JSONB_CODEC_ID]: identityHooks\n\t\t\t}\n\t\t},\n\t\tstorage: [\n\t\t\t{\n\t\t\t\ttypeId: PG_TEXT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"text\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: SQL_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: SQL_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_CHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARCHAR_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"character varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT2_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int2\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"int8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT4_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float4\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_FLOAT8_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"float8\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_NUMERIC_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"numeric\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMP_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamp\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMESTAMPTZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timestamptz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIME_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"time\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_TIMETZ_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"timetz\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BOOL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bool\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_BIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_VARBIT_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"bit varying\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_INTERVAL_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"interval\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSON_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"json\"\n\t\t\t},\n\t\t\t{\n\t\t\t\ttypeId: PG_JSONB_CODEC_ID,\n\t\t\t\tfamilyId: \"sql\",\n\t\t\t\ttargetId: \"postgres\",\n\t\t\t\tnativeType: \"jsonb\"\n\t\t\t}\n\t\t]\n\t}\n};\n\n//#endregion\nexport { pgEnumControlHooks as n, postgresAdapterDescriptorMeta as t };\n//# sourceMappingURL=descriptor-meta-DemWrTfB.mjs.map","import { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/generator-ids.ts\nconst builtinGeneratorIds = [\n\t\"ulid\",\n\t\"nanoid\",\n\t\"uuidv7\",\n\t\"uuidv4\",\n\t\"cuid2\",\n\t\"ksuid\"\n];\n\n//#endregion\n//#region src/index.ts\nfunction resolveNanoidColumnDescriptor(params) {\n\tconst rawSize = params?.[\"size\"];\n\tif (rawSize === void 0) return {\n\t\ttype: {\n\t\t\tcodecId: \"sql/char@1\",\n\t\t\tnativeType: \"character\"\n\t\t},\n\t\ttypeParams: { length: 21 }\n\t};\n\tif (typeof rawSize !== \"number\" || !Number.isInteger(rawSize) || rawSize < 2 || rawSize > 255) throw new Error(\"nanoid size must be an integer between 2 and 255\");\n\treturn {\n\t\ttype: {\n\t\t\tcodecId: \"sql/char@1\",\n\t\t\tnativeType: \"character\"\n\t\t},\n\t\ttypeParams: { length: rawSize }\n\t};\n}\nconst builtinGeneratorMetadataById = {\n\tulid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 26 }\n\t\t}\n\t},\n\tnanoid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 21 }\n\t\t},\n\t\tresolveGeneratedColumnDescriptor: resolveNanoidColumnDescriptor\n\t},\n\tuuidv7: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 36 }\n\t\t}\n\t},\n\tuuidv4: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 36 }\n\t\t}\n\t},\n\tcuid2: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 24 }\n\t\t}\n\t},\n\tksuid: {\n\t\tapplicableCodecIds: [\"pg/text@1\", \"sql/char@1\"],\n\t\tgeneratedColumnDescriptor: {\n\t\t\ttype: {\n\t\t\t\tcodecId: \"sql/char@1\",\n\t\t\t\tnativeType: \"character\"\n\t\t\t},\n\t\t\ttypeParams: { length: 27 }\n\t\t}\n\t}\n};\nconst builtinGeneratorRegistryMetadata = builtinGeneratorIds.map((id) => ({\n\tid,\n\tapplicableCodecIds: builtinGeneratorMetadataById[id].applicableCodecIds\n}));\nfunction resolveBuiltinGeneratedColumnDescriptor(input) {\n\tconst metadata = builtinGeneratorMetadataById[input.id];\n\tif (metadata.resolveGeneratedColumnDescriptor) return metadata.resolveGeneratedColumnDescriptor(input.params);\n\treturn metadata.generatedColumnDescriptor;\n}\nfunction createGeneratedSpec(id, options) {\n\tconst params = options;\n\tconst resolvedDescriptor = resolveBuiltinGeneratedColumnDescriptor({\n\t\tid,\n\t\t...ifDefined(\"params\", params)\n\t});\n\treturn {\n\t\ttype: resolvedDescriptor.type,\n\t\tnullable: false,\n\t\t...ifDefined(\"typeParams\", resolvedDescriptor.typeParams),\n\t\tgenerated: {\n\t\t\tkind: \"generator\",\n\t\t\tid,\n\t\t\t...ifDefined(\"params\", params)\n\t\t}\n\t};\n}\nconst ulid = (options) => createGeneratedSpec(\"ulid\", options);\nconst nanoid = (options) => createGeneratedSpec(\"nanoid\", options);\nconst uuidv7 = (options) => createGeneratedSpec(\"uuidv7\", options);\nconst uuidv4 = (options) => createGeneratedSpec(\"uuidv4\", options);\nconst cuid2 = (options) => createGeneratedSpec(\"cuid2\", options);\nconst ksuid = (options) => createGeneratedSpec(\"ksuid\", options);\n\n//#endregion\nexport { builtinGeneratorIds, builtinGeneratorRegistryMetadata, cuid2, ksuid, nanoid, resolveBuiltinGeneratedColumnDescriptor, ulid, uuidv4, uuidv7 };\n//# sourceMappingURL=index.mjs.map","import { i as quoteIdentifier, n as escapeLiteral, r as qualifyName, t as SqlEscapeError } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { n as pgEnumControlHooks, t as postgresAdapterDescriptorMeta } from \"./descriptor-meta-DemWrTfB.mjs\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\nimport { builtinGeneratorRegistryMetadata, resolveBuiltinGeneratedColumnDescriptor } from \"@prisma-next/ids\";\n\n//#region src/core/default-normalizer.ts\n/**\n* Pre-compiled regex patterns for performance.\n* These are compiled once at module load time rather than on each function call.\n*/\nconst NEXTVAL_PATTERN = /^nextval\\s*\\(/i;\nconst NOW_FUNCTION_PATTERN = /^(now\\s*\\(\\s*\\)|CURRENT_TIMESTAMP)$/i;\nconst CLOCK_TIMESTAMP_PATTERN = /^clock_timestamp\\s*\\(\\s*\\)$/i;\nconst TIMESTAMP_CAST_SUFFIX = /::timestamp(?:tz|\\s+(?:with|without)\\s+time\\s+zone)?$/i;\nconst TEXT_CAST_SUFFIX = /::text$/i;\nconst NOW_LITERAL_PATTERN = /^'now'$/i;\nconst UUID_PATTERN = /^gen_random_uuid\\s*\\(\\s*\\)$/i;\nconst UUID_OSSP_PATTERN = /^uuid_generate_v4\\s*\\(\\s*\\)$/i;\nconst NULL_PATTERN = /^NULL(?:::.+)?$/i;\nconst TRUE_PATTERN = /^true$/i;\nconst FALSE_PATTERN = /^false$/i;\nconst NUMERIC_PATTERN = /^-?\\d+(\\.\\d+)?$/;\nconst STRING_LITERAL_PATTERN = /^'((?:[^']|'')*)'(?:::(?:\"[^\"]+\"|[\\w\\s]+)(?:\\(\\d+\\))?)?$/;\n/**\n* Returns the canonical expression for a timestamp default function, or undefined\n* if the expression is not a recognized timestamp default.\n*\n* Keeps now()/CURRENT_TIMESTAMP and clock_timestamp() distinct:\n* - now(), CURRENT_TIMESTAMP, ('now'::text)::timestamp... → 'now()'\n* - clock_timestamp(), clock_timestamp()::timestamptz → 'clock_timestamp()'\n*\n* These are semantically different in Postgres: now() returns the transaction\n* start time (constant within a transaction), while clock_timestamp() returns\n* the actual wall-clock time (can differ across rows in a single INSERT).\n*/\nfunction canonicalizeTimestampDefault(expr) {\n\tif (NOW_FUNCTION_PATTERN.test(expr)) return \"now()\";\n\tif (CLOCK_TIMESTAMP_PATTERN.test(expr)) return \"clock_timestamp()\";\n\tif (!TIMESTAMP_CAST_SUFFIX.test(expr)) return void 0;\n\tlet inner = expr.replace(TIMESTAMP_CAST_SUFFIX, \"\").trim();\n\tif (inner.startsWith(\"(\") && inner.endsWith(\")\")) inner = inner.slice(1, -1).trim();\n\tif (NOW_FUNCTION_PATTERN.test(inner)) return \"now()\";\n\tif (CLOCK_TIMESTAMP_PATTERN.test(inner)) return \"clock_timestamp()\";\n\tinner = inner.replace(TEXT_CAST_SUFFIX, \"\").trim();\n\tif (NOW_LITERAL_PATTERN.test(inner)) return \"now()\";\n}\n/**\n* Parses a raw Postgres column default expression into a normalized ColumnDefault.\n* This enables semantic comparison between contract defaults and introspected schema defaults.\n*\n* Used by the migration diff layer to normalize raw database defaults during comparison,\n* keeping the introspection layer focused on faithful data capture.\n*\n* @param rawDefault - Raw default expression from information_schema.columns.column_default\n* @param nativeType - Native column type, used for type-aware parsing (bigint tagging, JSON detection)\n* @returns Normalized ColumnDefault or undefined if the expression cannot be parsed\n*/\nfunction parsePostgresDefault(rawDefault, nativeType) {\n\tconst trimmed = rawDefault.trim();\n\tconst normalizedType = nativeType?.toLowerCase();\n\tconst isBigInt = normalizedType === \"bigint\" || normalizedType === \"int8\";\n\tif (NEXTVAL_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"autoincrement()\"\n\t};\n\tconst canonicalTimestamp = canonicalizeTimestampDefault(trimmed);\n\tif (canonicalTimestamp) return {\n\t\tkind: \"function\",\n\t\texpression: canonicalTimestamp\n\t};\n\tif (UUID_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (UUID_OSSP_PATTERN.test(trimmed)) return {\n\t\tkind: \"function\",\n\t\texpression: \"gen_random_uuid()\"\n\t};\n\tif (NULL_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: null\n\t};\n\tif (TRUE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: true\n\t};\n\tif (FALSE_PATTERN.test(trimmed)) return {\n\t\tkind: \"literal\",\n\t\tvalue: false\n\t};\n\tif (NUMERIC_PATTERN.test(trimmed)) {\n\t\tconst num = Number(trimmed);\n\t\tif (!Number.isFinite(num)) return void 0;\n\t\tif (isBigInt && !Number.isSafeInteger(num)) return {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: trimmed\n\t\t};\n\t\treturn {\n\t\t\tkind: \"literal\",\n\t\t\tvalue: num\n\t\t};\n\t}\n\tconst stringMatch = trimmed.match(STRING_LITERAL_PATTERN);\n\tif (stringMatch?.[1] !== void 0) {\n\t\tconst unescaped = stringMatch[1].replace(/''/g, \"'\");\n\t\tif (normalizedType === \"json\" || normalizedType === \"jsonb\") try {\n\t\t\treturn {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: JSON.parse(unescaped)\n\t\t\t};\n\t\t} catch {}\n\t\tif (isBigInt && NUMERIC_PATTERN.test(unescaped)) {\n\t\t\tconst num = Number(unescaped);\n\t\t\tif (Number.isSafeInteger(num)) return {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: num\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tkind: \"literal\",\n\t\t\t\tvalue: unescaped\n\t\t\t};\n\t\t}\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* 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 contract - Optional contract 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, _contract, schema = \"public\") {\n\t\tconst [tablesResult, columnsResult, pkResult, fkResult, uniqueResult, indexResult, extensionsResult] = await Promise.all([\n\t\t\tdriver.query(`SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`, [schema]),\n\t\t\tdriver.query(`SELECT\n c.table_name,\n column_name,\n data_type,\n udt_name,\n is_nullable,\n character_maximum_length,\n numeric_precision,\n numeric_scale,\n column_default,\n format_type(a.atttypid, a.atttypmod) AS formatted_type\n FROM information_schema.columns c\n JOIN pg_catalog.pg_class cl\n ON cl.relname = c.table_name\n JOIN pg_catalog.pg_namespace ns\n ON ns.nspname = c.table_schema\n AND ns.oid = cl.relnamespace\n JOIN pg_catalog.pg_attribute a\n ON a.attrelid = cl.oid\n AND a.attname = c.column_name\n AND a.attnum > 0\n AND NOT a.attisdropped\n WHERE c.table_schema = $1\n ORDER BY c.table_name, c.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'PRIMARY KEY'\n ORDER BY tc.table_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position,\n ref_ns.nspname AS referenced_table_schema,\n ref_cl.relname AS referenced_table_name,\n ref_att.attname AS referenced_column_name,\n rc.delete_rule,\n rc.update_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n JOIN pg_catalog.pg_constraint pgc\n ON pgc.conname = tc.constraint_name\n AND pgc.connamespace = (\n SELECT oid FROM pg_catalog.pg_namespace WHERE nspname = tc.table_schema\n )\n JOIN pg_catalog.pg_class ref_cl\n ON ref_cl.oid = pgc.confrelid\n JOIN pg_catalog.pg_namespace ref_ns\n ON ref_ns.oid = ref_cl.relnamespace\n JOIN pg_catalog.pg_attribute ref_att\n ON ref_att.attrelid = pgc.confrelid\n AND ref_att.attnum = pgc.confkey[kcu.ordinal_position]\n JOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n AND tc.table_name = kcu.table_name\n WHERE tc.table_schema = $1\n AND tc.constraint_type = 'UNIQUE'\n ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position`, [schema]),\n\t\t\tdriver.query(`SELECT\n i.tablename,\n i.indexname,\n ix.indisunique,\n a.attname,\n a.attnum\n FROM pg_indexes i\n JOIN pg_class ic ON ic.relname = i.indexname\n JOIN pg_namespace ins ON ins.oid = ic.relnamespace AND ins.nspname = $1\n JOIN pg_index ix ON ix.indexrelid = ic.oid\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace tn ON tn.oid = t.relnamespace AND tn.nspname = $1\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND a.attnum > 0\n WHERE i.schemaname = $1\n AND NOT EXISTS (\n SELECT 1\n FROM information_schema.table_constraints tc\n WHERE tc.table_schema = $1\n AND tc.table_name = i.tablename\n AND tc.constraint_name = i.indexname\n )\n ORDER BY i.tablename, i.indexname, a.attnum`, [schema]),\n\t\t\tdriver.query(`SELECT extname\n FROM pg_extension\n ORDER BY extname`, [])\n\t\t]);\n\t\tconst columnsByTable = groupBy(columnsResult.rows, \"table_name\");\n\t\tconst pksByTable = groupBy(pkResult.rows, \"table_name\");\n\t\tconst fksByTable = groupBy(fkResult.rows, \"table_name\");\n\t\tconst uniquesByTable = groupBy(uniqueResult.rows, \"table_name\");\n\t\tconst indexesByTable = groupBy(indexResult.rows, \"tablename\");\n\t\tconst pkConstraintsByTable = /* @__PURE__ */ new Map();\n\t\tfor (const row of pkResult.rows) {\n\t\t\tlet constraints = pkConstraintsByTable.get(row.table_name);\n\t\t\tif (!constraints) {\n\t\t\t\tconstraints = /* @__PURE__ */ new Set();\n\t\t\t\tpkConstraintsByTable.set(row.table_name, constraints);\n\t\t\t}\n\t\t\tconstraints.add(row.constraint_name);\n\t\t}\n\t\tconst tables = {};\n\t\tfor (const tableRow of tablesResult.rows) {\n\t\t\tconst tableName = tableRow.table_name;\n\t\t\tconst columns = {};\n\t\t\tfor (const colRow of columnsByTable.get(tableName) ?? []) {\n\t\t\t\tlet nativeType = colRow.udt_name;\n\t\t\t\tconst formattedType = colRow.formatted_type ? normalizeFormattedType(colRow.formatted_type, colRow.data_type, colRow.udt_name) : null;\n\t\t\t\tif (formattedType) nativeType = formattedType;\n\t\t\t\telse if (colRow.data_type === \"character varying\" || colRow.data_type === \"character\") if (colRow.character_maximum_length) nativeType = `${colRow.data_type}(${colRow.character_maximum_length})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse if (colRow.data_type === \"numeric\" || colRow.data_type === \"decimal\") if (colRow.numeric_precision && colRow.numeric_scale !== null) nativeType = `${colRow.data_type}(${colRow.numeric_precision},${colRow.numeric_scale})`;\n\t\t\t\telse if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;\n\t\t\t\telse nativeType = colRow.data_type;\n\t\t\t\telse nativeType = colRow.udt_name || colRow.data_type;\n\t\t\t\tcolumns[colRow.column_name] = {\n\t\t\t\t\tname: colRow.column_name,\n\t\t\t\t\tnativeType,\n\t\t\t\t\tnullable: colRow.is_nullable === \"YES\",\n\t\t\t\t\t...ifDefined(\"default\", colRow.column_default ?? void 0)\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst pkRows = [...pksByTable.get(tableName) ?? []];\n\t\t\tconst primaryKeyColumns = pkRows.sort((a, b) => a.ordinal_position - b.ordinal_position).map((row) => row.column_name);\n\t\t\tconst primaryKey = primaryKeyColumns.length > 0 ? {\n\t\t\t\tcolumns: primaryKeyColumns,\n\t\t\t\t...pkRows[0]?.constraint_name ? { name: pkRows[0].constraint_name } : {}\n\t\t\t} : void 0;\n\t\t\tconst foreignKeysMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const fkRow of fksByTable.get(tableName) ?? []) {\n\t\t\t\tconst existing = foreignKeysMap.get(fkRow.constraint_name);\n\t\t\t\tif (existing) {\n\t\t\t\t\texisting.columns.push(fkRow.column_name);\n\t\t\t\t\texisting.referencedColumns.push(fkRow.referenced_column_name);\n\t\t\t\t} else foreignKeysMap.set(fkRow.constraint_name, {\n\t\t\t\t\tcolumns: [fkRow.column_name],\n\t\t\t\t\treferencedTable: fkRow.referenced_table_name,\n\t\t\t\t\treferencedColumns: [fkRow.referenced_column_name],\n\t\t\t\t\tname: fkRow.constraint_name,\n\t\t\t\t\tdeleteRule: fkRow.delete_rule,\n\t\t\t\t\tupdateRule: fkRow.update_rule\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst foreignKeys = Array.from(foreignKeysMap.values()).map((fk) => ({\n\t\t\t\tcolumns: Object.freeze([...fk.columns]),\n\t\t\t\treferencedTable: fk.referencedTable,\n\t\t\t\treferencedColumns: Object.freeze([...fk.referencedColumns]),\n\t\t\t\tname: fk.name,\n\t\t\t\t...ifDefined(\"onDelete\", mapReferentialAction(fk.deleteRule)),\n\t\t\t\t...ifDefined(\"onUpdate\", mapReferentialAction(fk.updateRule))\n\t\t\t}));\n\t\t\tconst pkConstraints = pkConstraintsByTable.get(tableName) ?? /* @__PURE__ */ new Set();\n\t\t\tconst uniquesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const uniqueRow of uniquesByTable.get(tableName) ?? []) {\n\t\t\t\tif (pkConstraints.has(uniqueRow.constraint_name)) continue;\n\t\t\t\tconst existing = uniquesMap.get(uniqueRow.constraint_name);\n\t\t\t\tif (existing) existing.columns.push(uniqueRow.column_name);\n\t\t\t\telse uniquesMap.set(uniqueRow.constraint_name, {\n\t\t\t\t\tcolumns: [uniqueRow.column_name],\n\t\t\t\t\tname: uniqueRow.constraint_name\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst uniques = Array.from(uniquesMap.values()).map((uq) => ({\n\t\t\t\tcolumns: Object.freeze([...uq.columns]),\n\t\t\t\tname: uq.name\n\t\t\t}));\n\t\t\tconst indexesMap = /* @__PURE__ */ new Map();\n\t\t\tfor (const idxRow of indexesByTable.get(tableName) ?? []) {\n\t\t\t\tif (!idxRow.attname) continue;\n\t\t\t\tconst existing = indexesMap.get(idxRow.indexname);\n\t\t\t\tif (existing) existing.columns.push(idxRow.attname);\n\t\t\t\telse indexesMap.set(idxRow.indexname, {\n\t\t\t\t\tcolumns: [idxRow.attname],\n\t\t\t\t\tname: idxRow.indexname,\n\t\t\t\t\tunique: idxRow.indisunique\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst indexes = Array.from(indexesMap.values()).map((idx) => ({\n\t\t\t\tcolumns: Object.freeze([...idx.columns]),\n\t\t\t\tname: idx.name,\n\t\t\t\tunique: idx.unique\n\t\t\t}));\n\t\t\ttables[tableName] = {\n\t\t\t\tname: tableName,\n\t\t\t\tcolumns,\n\t\t\t\t...ifDefined(\"primaryKey\", primaryKey),\n\t\t\t\tforeignKeys,\n\t\t\t\tuniques,\n\t\t\t\tindexes\n\t\t\t};\n\t\t}\n\t\tconst dependencies = extensionsResult.rows.map((row) => ({ id: `postgres.extension.${row.extname}` }));\n\t\tconst storageTypes = await pgEnumControlHooks.introspectTypes?.({\n\t\t\tdriver,\n\t\t\tschemaName: schema\n\t\t}) ?? {};\n\t\treturn {\n\t\t\ttables,\n\t\t\tdependencies,\n\t\t\tannotations: { pg: {\n\t\t\t\tschema,\n\t\t\t\tversion: await this.getPostgresVersion(driver),\n\t\t\t\t...ifDefined(\"storageTypes\", Object.keys(storageTypes).length > 0 ? storageTypes : void 0)\n\t\t\t} }\n\t\t};\n\t}\n\t/**\n\t* Gets the Postgres version from the database.\n\t*/\n\tasync getPostgresVersion(driver) {\n\t\treturn ((await driver.query(\"SELECT version() AS version\", [])).rows[0]?.version ?? \"\").match(/PostgreSQL (\\d+\\.\\d+)/)?.[1] ?? \"unknown\";\n\t}\n};\n/**\n* Pre-computed lookup map for simple prefix-based type normalization.\n* Maps short Postgres type names to their canonical SQL names.\n* Using a Map for O(1) lookup instead of multiple startsWith checks.\n*/\nconst TYPE_PREFIX_MAP = new Map([\n\t[\"varchar\", \"character varying\"],\n\t[\"bpchar\", \"character\"],\n\t[\"varbit\", \"bit varying\"]\n]);\n/**\n* Normalizes a Postgres schema native type to its canonical form for comparison.\n*\n* Uses a pre-computed lookup map for simple prefix replacements (O(1))\n* and handles complex temporal type normalization separately.\n*/\nfunction normalizeSchemaNativeType(nativeType) {\n\tconst trimmed = nativeType.trim();\n\tfor (const [prefix, replacement] of TYPE_PREFIX_MAP) if (trimmed.startsWith(prefix)) return replacement + trimmed.slice(prefix.length);\n\tif (trimmed.includes(\" with time zone\")) {\n\t\tif (trimmed.startsWith(\"timestamp\")) return `timestamptz${trimmed.slice(9).replace(\" with time zone\", \"\")}`;\n\t\tif (trimmed.startsWith(\"time\")) return `timetz${trimmed.slice(4).replace(\" with time zone\", \"\")}`;\n\t}\n\tif (trimmed.includes(\" without time zone\")) return trimmed.replace(\" without time zone\", \"\");\n\treturn trimmed;\n}\nfunction normalizeFormattedType(formattedType, dataType, udtName) {\n\tif (formattedType === \"integer\") return \"int4\";\n\tif (formattedType === \"smallint\") return \"int2\";\n\tif (formattedType === \"bigint\") return \"int8\";\n\tif (formattedType === \"real\") return \"float4\";\n\tif (formattedType === \"double precision\") return \"float8\";\n\tif (formattedType === \"boolean\") return \"bool\";\n\tif (formattedType.startsWith(\"varchar\")) return formattedType.replace(\"varchar\", \"character varying\");\n\tif (formattedType.startsWith(\"bpchar\")) return formattedType.replace(\"bpchar\", \"character\");\n\tif (formattedType.startsWith(\"varbit\")) return formattedType.replace(\"varbit\", \"bit varying\");\n\tif (dataType === \"timestamp with time zone\" || udtName === \"timestamptz\") return formattedType.replace(\"timestamp\", \"timestamptz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"timestamp without time zone\" || udtName === \"timestamp\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (dataType === \"time with time zone\" || udtName === \"timetz\") return formattedType.replace(\"time\", \"timetz\").replace(\" with time zone\", \"\").trim();\n\tif (dataType === \"time without time zone\" || udtName === \"time\") return formattedType.replace(\" without time zone\", \"\").trim();\n\tif (formattedType.startsWith(\"\\\"\") && formattedType.endsWith(\"\\\"\")) return formattedType.slice(1, -1);\n\treturn formattedType;\n}\nconst PG_REFERENTIAL_ACTION_MAP = {\n\t\"NO ACTION\": \"noAction\",\n\tRESTRICT: \"restrict\",\n\tCASCADE: \"cascade\",\n\t\"SET NULL\": \"setNull\",\n\t\"SET DEFAULT\": \"setDefault\"\n};\n/**\n* Maps a Postgres referential action rule to the canonical SqlReferentialAction.\n* Returns undefined for 'NO ACTION' (the database default) to keep the IR sparse.\n* Throws for unrecognized rules to prevent silent data loss.\n*/\nfunction mapReferentialAction(rule) {\n\tconst mapped = PG_REFERENTIAL_ACTION_MAP[rule];\n\tif (mapped === void 0) throw new Error(`Unknown PostgreSQL referential action rule: \"${rule}\". Expected one of: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT.`);\n\tif (mapped === \"noAction\") return void 0;\n\treturn mapped;\n}\n/**\n* Groups an array of objects by a specified key.\n* Returns a Map for O(1) lookup by group key.\n*/\nfunction groupBy(items, key) {\n\tconst map = /* @__PURE__ */ new Map();\n\tfor (const item of items) {\n\t\tconst groupKey = item[key];\n\t\tlet group = map.get(groupKey);\n\t\tif (!group) {\n\t\t\tgroup = [];\n\t\t\tmap.set(groupKey, group);\n\t\t}\n\t\tgroup.push(item);\n\t}\n\treturn map;\n}\n\n//#endregion\n//#region src/core/control-mutation-defaults.ts\nfunction invalidArgumentDiagnostic(input) {\n\treturn {\n\t\tok: false,\n\t\tdiagnostic: {\n\t\t\tcode: \"PSL_INVALID_DEFAULT_FUNCTION_ARGUMENT\",\n\t\t\tmessage: input.message,\n\t\t\tsourceId: input.context.sourceId,\n\t\t\tspan: input.span\n\t\t}\n\t};\n}\nfunction executionGenerator(id, params) {\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"execution\",\n\t\t\tgenerated: {\n\t\t\t\tkind: \"generator\",\n\t\t\t\tid,\n\t\t\t\t...params ? { params } : {}\n\t\t\t}\n\t\t}\n\t};\n}\nfunction expectNoArgs(input) {\n\tif (input.call.args.length === 0) return;\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: `Default function \"${input.call.name}\" does not accept arguments. Use ${input.usage}.`\n\t});\n}\nfunction parseIntegerArgument(raw) {\n\tconst trimmed = raw.trim();\n\tif (!/^-?\\d+$/.test(trimmed)) return;\n\tconst value = Number(trimmed);\n\tif (!Number.isInteger(value)) return;\n\treturn value;\n}\nfunction parseStringLiteral(raw) {\n\tconst match = raw.trim().match(/^(['\"])(.*)\\1$/s);\n\tif (!match) return;\n\treturn match[2] ?? \"\";\n}\nfunction lowerAutoincrement(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`autoincrement()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: \"autoincrement()\"\n\t\t\t}\n\t\t}\n\t};\n}\nfunction lowerNow(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`now()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: \"now()\"\n\t\t\t}\n\t\t}\n\t};\n}\nfunction lowerUuid(input) {\n\tif (input.call.args.length === 0) return executionGenerator(\"uuidv4\");\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"uuid\\\" accepts at most one version argument: `uuid()`, `uuid(4)`, or `uuid(7)`.\"\n\t});\n\tconst version = parseIntegerArgument(input.call.args[0]?.raw ?? \"\");\n\tif (version === 4) return executionGenerator(\"uuidv4\");\n\tif (version === 7) return executionGenerator(\"uuidv7\");\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"uuid\\\" supports only `uuid()`, `uuid(4)`, or `uuid(7)` in SQL PSL provider v1.\"\n\t});\n}\nfunction lowerCuid(input) {\n\tif (input.call.args.length === 0) return {\n\t\tok: false,\n\t\tdiagnostic: {\n\t\t\tcode: \"PSL_UNKNOWN_DEFAULT_FUNCTION\",\n\t\t\tmessage: \"Default function \\\"cuid()\\\" is not supported in SQL PSL provider v1. Use `cuid(2)` instead.\",\n\t\t\tsourceId: input.context.sourceId,\n\t\t\tspan: input.call.span\n\t\t}\n\t};\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"cuid\\\" accepts exactly one version argument: `cuid(2)`.\"\n\t});\n\tif (parseIntegerArgument(input.call.args[0]?.raw ?? \"\") === 2) return executionGenerator(\"cuid2\");\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"cuid\\\" supports only `cuid(2)` in SQL PSL provider v1.\"\n\t});\n}\nfunction lowerUlid(input) {\n\tconst maybeNoArgs = expectNoArgs({\n\t\tcall: input.call,\n\t\tcontext: input.context,\n\t\tusage: \"`ulid()`\"\n\t});\n\tif (maybeNoArgs) return maybeNoArgs;\n\treturn executionGenerator(\"ulid\");\n}\nfunction lowerNanoid(input) {\n\tif (input.call.args.length === 0) return executionGenerator(\"nanoid\");\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"nanoid\\\" accepts at most one size argument: `nanoid()` or `nanoid(<2-255>)`.\"\n\t});\n\tconst size = parseIntegerArgument(input.call.args[0]?.raw ?? \"\");\n\tif (size !== void 0 && size >= 2 && size <= 255) return executionGenerator(\"nanoid\", { size });\n\treturn invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"nanoid\\\" size argument must be an integer between 2 and 255.\"\n\t});\n}\nfunction lowerDbgenerated(input) {\n\tif (input.call.args.length !== 1) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" requires exactly one string argument: `dbgenerated(\\\"...\\\")`.\"\n\t});\n\tconst rawExpression = parseStringLiteral(input.call.args[0]?.raw ?? \"\");\n\tif (rawExpression === void 0) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" argument must be a string literal.\"\n\t});\n\tif (rawExpression.trim().length === 0) return invalidArgumentDiagnostic({\n\t\tcontext: input.context,\n\t\tspan: input.call.args[0]?.span ?? input.call.span,\n\t\tmessage: \"Default function \\\"dbgenerated\\\" argument cannot be empty.\"\n\t});\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tkind: \"storage\",\n\t\t\tdefaultValue: {\n\t\t\t\tkind: \"function\",\n\t\t\t\texpression: rawExpression\n\t\t\t}\n\t\t}\n\t};\n}\nconst postgresDefaultFunctionRegistryEntries = [\n\t[\"autoincrement\", {\n\t\tlower: lowerAutoincrement,\n\t\tusageSignatures: [\"autoincrement()\"]\n\t}],\n\t[\"now\", {\n\t\tlower: lowerNow,\n\t\tusageSignatures: [\"now()\"]\n\t}],\n\t[\"uuid\", {\n\t\tlower: lowerUuid,\n\t\tusageSignatures: [\n\t\t\t\"uuid()\",\n\t\t\t\"uuid(4)\",\n\t\t\t\"uuid(7)\"\n\t\t]\n\t}],\n\t[\"cuid\", {\n\t\tlower: lowerCuid,\n\t\tusageSignatures: [\"cuid(2)\"]\n\t}],\n\t[\"ulid\", {\n\t\tlower: lowerUlid,\n\t\tusageSignatures: [\"ulid()\"]\n\t}],\n\t[\"nanoid\", {\n\t\tlower: lowerNanoid,\n\t\tusageSignatures: [\"nanoid()\", \"nanoid(<2-255>)\"]\n\t}],\n\t[\"dbgenerated\", {\n\t\tlower: lowerDbgenerated,\n\t\tusageSignatures: [\"dbgenerated(\\\"...\\\")\"]\n\t}]\n];\nconst postgresScalarTypeDescriptors = new Map([\n\t[\"String\", \"pg/text@1\"],\n\t[\"Boolean\", \"pg/bool@1\"],\n\t[\"Int\", \"pg/int4@1\"],\n\t[\"BigInt\", \"pg/int8@1\"],\n\t[\"Float\", \"pg/float8@1\"],\n\t[\"Decimal\", \"pg/numeric@1\"],\n\t[\"DateTime\", \"pg/timestamptz@1\"],\n\t[\"Json\", \"pg/jsonb@1\"],\n\t[\"Bytes\", \"pg/bytea@1\"]\n]);\nfunction createPostgresDefaultFunctionRegistry() {\n\treturn new Map(postgresDefaultFunctionRegistryEntries);\n}\nfunction createPostgresMutationDefaultGeneratorDescriptors() {\n\treturn builtinGeneratorRegistryMetadata.map(({ id, applicableCodecIds }) => ({\n\t\tid,\n\t\tapplicableCodecIds,\n\t\tresolveGeneratedColumnDescriptor: ({ generated }) => {\n\t\t\tif (generated.kind !== \"generator\" || generated.id !== id) return;\n\t\t\tconst descriptor = resolveBuiltinGeneratedColumnDescriptor({\n\t\t\t\tid,\n\t\t\t\t...generated.params ? { params: generated.params } : {}\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tcodecId: descriptor.type.codecId,\n\t\t\t\tnativeType: descriptor.type.nativeType,\n\t\t\t\t...descriptor.type.typeRef ? { typeRef: descriptor.type.typeRef } : {},\n\t\t\t\t...descriptor.typeParams ? { typeParams: descriptor.typeParams } : {}\n\t\t\t};\n\t\t}\n\t}));\n}\nfunction createPostgresScalarTypeDescriptors() {\n\treturn new Map(postgresScalarTypeDescriptors);\n}\n\n//#endregion\n//#region src/exports/control.ts\nconst postgresAdapterDescriptor = {\n\t...postgresAdapterDescriptorMeta,\n\tscalarTypeDescriptors: createPostgresScalarTypeDescriptors(),\n\tcontrolMutationDefaults: {\n\t\tdefaultFunctionRegistry: createPostgresDefaultFunctionRegistry(),\n\t\tgeneratorDescriptors: createPostgresMutationDefaultGeneratorDescriptors()\n\t},\n\tcreate() {\n\t\treturn new PostgresControlAdapter();\n\t}\n};\nvar control_default = postgresAdapterDescriptor;\n\n//#endregion\nexport { SqlEscapeError, control_default as default, escapeLiteral, normalizeSchemaNativeType, parsePostgresDefault, qualifyName, quoteIdentifier };\n//# sourceMappingURL=control.mjs.map","/**\n * Migration strategies for the descriptor-based planner.\n *\n * Each strategy examines the issue list, consumes issues it handles,\n * and returns the ops to handle them. The planner chains strategies,\n * then handles whatever's left with default issue-to-descriptor mapping.\n *\n * Different strategy sets are used for different contexts:\n * - `migration plan`: data-safe strategies (dataTransform for NOT NULL, type changes, etc.)\n * - `db update`: dev-push strategies (temp defaults, destructive type changes, no data transforms)\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport {\n addColumn,\n addEnumValues,\n alterColumnType,\n createEnumType,\n dataTransform,\n dropEnumType,\n type PostgresMigrationOpDescriptor,\n renameType,\n setNotNull,\n TODO,\n} from './operation-descriptors';\n\n// ============================================================================\n// Strategy types\n// ============================================================================\n\n/** Context passed to each migration strategy — the from/to contracts for the migration. */\nexport interface StrategyContext {\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n}\n\n/**\n * A migration strategy examines schema issues, consumes the ones it handles,\n * and returns the descriptor ops to address them. Returns `'no_match'` if\n * none of the issues are relevant. The planner chains strategies in order —\n * earlier strategies consume issues before later ones see them.\n */\nexport type MigrationStrategy = (\n issues: readonly SchemaIssue[],\n context: StrategyContext,\n) =>\n | { kind: 'match'; issues: readonly SchemaIssue[]; ops: readonly PostgresMigrationOpDescriptor[] }\n | { kind: 'no_match' };\n\n// ============================================================================\n// Recipes\n// ============================================================================\n\nconst REBUILD_SUFFIX = '__prisma_next_new';\n\n/**\n * Produces the descriptor sequence for rebuilding a Postgres enum type:\n * createEnumType(temp, values) → alterColumnType(USING cast) per column → dropEnumType(old) → renameType(temp, old)\n *\n * Used by the enum change strategy for value removal and reorder scenarios.\n * Finds all columns referencing the enum via `typeRef` in the destination contract.\n */\nfunction enumRebuildRecipe(\n typeName: string,\n ctx: StrategyContext,\n): readonly PostgresMigrationOpDescriptor[] {\n const toType = ctx.toContract.storage.types?.[typeName];\n if (!toType) return [];\n const nativeType = toType.nativeType;\n const desiredValues = (toType.typeParams['values'] ?? []) as readonly string[];\n const tempName = `${nativeType}${REBUILD_SUFFIX}`;\n\n const columnRefs: { table: string; column: string }[] = [];\n for (const [tableName, table] of Object.entries(ctx.toContract.storage.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.typeRef === typeName) {\n columnRefs.push({ table: tableName, column: columnName });\n }\n }\n }\n\n return [\n createEnumType(tempName, desiredValues),\n ...columnRefs.map((ref) =>\n alterColumnType(ref.table, ref.column, {\n toType: tempName,\n using: `${ref.column}::text::${tempName}`,\n }),\n ),\n dropEnumType(nativeType),\n renameType(tempName, nativeType),\n ];\n}\n\n// ============================================================================\n// Data-safe strategies (for `migration plan`)\n// ============================================================================\n\n/**\n * NOT NULL backfill strategy.\n *\n * When a missing column is NOT NULL without a default, the planner can't just\n * add it — existing rows would violate the constraint. Instead, emit:\n * addColumn(nullable) → dataTransform (user fills in backfill) → setNotNull\n */\nexport const notNullBackfillStrategy: MigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const ops: PostgresMigrationOpDescriptor[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'missing_column' || !issue.table || !issue.column) continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column) continue;\n if (column.nullable === true || column.default !== undefined) continue;\n\n matched.push(issue);\n ops.push(\n addColumn(issue.table, issue.column, { nullable: true }),\n dataTransform(`backfill-${issue.table}-${issue.column}`, {\n check: TODO,\n run: TODO,\n }),\n setNotNull(issue.table, issue.column),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n ops,\n };\n};\n\n/**\n * Unsafe type change strategy.\n *\n * Safe widenings (int4 → int8) emit alterColumnType directly.\n * Unsafe changes emit dataTransform for user to handle conversion.\n */\nexport const typeChangeStrategy: MigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const ops: PostgresMigrationOpDescriptor[] = [];\n\n const SAFE_WIDENINGS = new Set(['int2→int4', 'int2→int8', 'int4→int8', 'float4→float8']);\n function isSafeWidening(fromType: string, toType: string): boolean {\n return SAFE_WIDENINGS.has(`${fromType}→${toType}`);\n }\n\n for (const issue of issues) {\n if (issue.kind !== 'type_mismatch') continue;\n if (!issue.table || !issue.column) continue;\n const fromColumn = ctx.fromContract?.storage.tables[issue.table]?.columns[issue.column];\n const toColumn = ctx.toContract?.storage.tables[issue.table]?.columns[issue.column];\n if (!fromColumn || !toColumn) continue;\n const fromType = fromColumn.nativeType;\n const toType = toColumn.nativeType;\n if (fromType === toType) continue;\n matched.push(issue);\n if (isSafeWidening(fromType, toType)) {\n ops.push(alterColumnType(issue.table, issue.column));\n } else {\n ops.push(\n dataTransform(`typechange-${issue.table}-${issue.column}`, {\n check: TODO,\n run: TODO,\n }),\n alterColumnType(issue.table, issue.column),\n );\n }\n }\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n ops,\n };\n};\n\n/**\n * Nullable → NOT NULL tightening strategy.\n *\n * When an existing column changes from nullable to NOT NULL, existing rows\n * may have NULLs that violate the constraint. Emit:\n * dataTransform (user fills in NULL handling) → setNotNull\n */\nexport const nullableTighteningStrategy: MigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const ops: PostgresMigrationOpDescriptor[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'nullability_mismatch' || !issue.table || !issue.column) continue;\n\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column) continue;\n if (column.nullable === true) continue;\n\n matched.push(issue);\n ops.push(\n dataTransform(`handle-nulls-${issue.table}-${issue.column}`, {\n check: TODO,\n run: TODO,\n }),\n setNotNull(issue.table, issue.column),\n );\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n ops,\n };\n};\n\n/**\n * Enum value change strategy.\n *\n * When enum values change between contracts:\n * - Add only → addEnumValues\n * - Reorder (same values, different order) → rebuild recipe (no data transform)\n * - Removal → dataTransform (user migrates rows) + rebuild recipe\n */\nexport const enumChangeStrategy: MigrationStrategy = (issues, ctx) => {\n const matched: SchemaIssue[] = [];\n const ops: PostgresMigrationOpDescriptor[] = [];\n\n for (const issue of issues) {\n if (issue.kind !== 'enum_values_changed') continue;\n matched.push(issue);\n\n if (issue.removedValues.length > 0) {\n ops.push(\n dataTransform(`migrate-${issue.typeName}-values`, { check: TODO, run: TODO }),\n ...enumRebuildRecipe(issue.typeName, ctx),\n );\n } else if (issue.addedValues.length === 0) {\n // Reorder only — rebuild without data transform\n ops.push(...enumRebuildRecipe(issue.typeName, ctx));\n } else {\n ops.push(addEnumValues(issue.typeName, issue.addedValues));\n }\n }\n\n if (matched.length === 0) return { kind: 'no_match' };\n return {\n kind: 'match',\n issues: issues.filter((i) => !matched.includes(i)),\n ops,\n };\n};\n\n/** Default strategy set for `migration plan` — data-safe, requires user input for destructive changes. */\nexport const migrationPlanStrategies: readonly MigrationStrategy[] = [\n enumChangeStrategy,\n notNullBackfillStrategy,\n typeChangeStrategy,\n nullableTighteningStrategy,\n];\n","/**\n * Descriptor-based migration planner.\n *\n * Takes schema issues (from verifySqlSchema) and emits PostgresMigrationOpDescriptor[].\n * Migration strategies consume issues they recognize and produce specialized op\n * sequences (e.g., NOT NULL backfill → addColumn(nullable) + dataTransform + setNotNull).\n * Remaining issues get default descriptor mapping.\n *\n * This planner does NOT produce SqlMigrationPlanOperation — that's the resolver's job.\n * The separation means the same descriptors work for both planner-generated and\n * user-authored migrations.\n */\n\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { SqlPlannerConflict } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { Result } from '@prisma-next/utils/result';\nimport { notOk, ok } from '@prisma-next/utils/result';\nimport {\n addColumn,\n addForeignKey,\n addPrimaryKey,\n addUnique,\n alterColumnType,\n createDependency,\n createEnumType,\n createIndex,\n createTable,\n dropColumn,\n dropConstraint,\n dropDefault,\n dropIndex,\n dropNotNull,\n dropTable,\n type PostgresMigrationOpDescriptor,\n setDefault,\n setNotNull,\n} from './operation-descriptors';\nimport {\n type MigrationStrategy,\n migrationPlanStrategies,\n type StrategyContext,\n} from './planner-strategies';\n\nexport type { MigrationStrategy, StrategyContext };\n\n// ============================================================================\n// Issue kind ordering (dependency order)\n// ============================================================================\n\nconst ISSUE_KIND_ORDER: Record<string, number> = {\n // Dependencies and types first\n dependency_missing: 1,\n type_missing: 2,\n type_values_mismatch: 3,\n enum_values_changed: 3,\n\n // Drops (reconciliation — clear the way for creates)\n // FKs dropped first (they depend on other constraints)\n extra_foreign_key: 10,\n extra_unique_constraint: 11,\n extra_primary_key: 12,\n extra_index: 13,\n extra_default: 14,\n extra_column: 15,\n extra_table: 16,\n\n // Tables before columns\n missing_table: 20,\n\n // Columns before constraints\n missing_column: 30,\n\n // Reconciliation alters (on existing objects)\n type_mismatch: 40,\n nullability_mismatch: 41,\n default_missing: 42,\n default_mismatch: 43,\n\n // Constraints after columns exist\n primary_key_mismatch: 50,\n unique_constraint_mismatch: 51,\n index_mismatch: 52,\n foreign_key_mismatch: 60,\n};\n\nfunction issueOrder(issue: SchemaIssue): number {\n return ISSUE_KIND_ORDER[issue.kind] ?? 99;\n}\n\n// ============================================================================\n// Conflict helpers\n// ============================================================================\n\nfunction issueConflict(\n kind: SqlPlannerConflict['kind'],\n summary: string,\n location?: SqlPlannerConflict['location'],\n): SqlPlannerConflict {\n return {\n kind,\n summary,\n why: 'Use `migration new` to author a custom migration for this change.',\n ...(location ? { location } : {}),\n };\n}\n\n// ============================================================================\n// Default issue-to-descriptor mapping\n// ============================================================================\n\nfunction isMissing(issue: SchemaIssue): boolean {\n if (issue.kind === 'enum_values_changed') return false;\n return issue.actual === undefined;\n}\n\nfunction mapIssue(\n issue: SchemaIssue,\n ctx: StrategyContext,\n): Result<readonly PostgresMigrationOpDescriptor[], SqlPlannerConflict> {\n switch (issue.kind) {\n // Additive — missing structures\n case 'missing_table': {\n if (!issue.table)\n return notOk(\n issueConflict('unsupportedOperation', 'Missing table issue has no table name'),\n );\n const contractTable = ctx.toContract.storage.tables[issue.table];\n if (!contractTable) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Table \"${issue.table}\" reported missing but not found in destination contract`,\n ),\n );\n }\n const ops: PostgresMigrationOpDescriptor[] = [createTable(issue.table)];\n for (const index of contractTable.indexes) {\n ops.push(createIndex(issue.table, [...index.columns]));\n }\n const explicitIndexColumnSets = new Set(\n contractTable.indexes.map((idx) => idx.columns.join(',')),\n );\n for (const fk of contractTable.foreignKeys) {\n if (fk.constraint) {\n ops.push(addForeignKey(issue.table, [...fk.columns]));\n }\n if (fk.index && !explicitIndexColumnSets.has(fk.columns.join(','))) {\n ops.push(createIndex(issue.table, [...fk.columns]));\n }\n }\n for (const unique of contractTable.uniques) {\n ops.push(addUnique(issue.table, [...unique.columns]));\n }\n return ok(ops);\n }\n\n case 'missing_column':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Missing column issue has no table/column name'),\n );\n return ok([addColumn(issue.table, issue.column)]);\n\n case 'default_missing':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Default missing issue has no table/column name'),\n );\n return ok([setDefault(issue.table, issue.column)]);\n\n // Destructive — extra structures\n case 'extra_table':\n if (!issue.table)\n return notOk(issueConflict('unsupportedOperation', 'Extra table issue has no table name'));\n return ok([dropTable(issue.table)]);\n\n case 'extra_column':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra column issue has no table/column name'),\n );\n return ok([dropColumn(issue.table, issue.column)]);\n\n case 'extra_index':\n if (!issue.table || !issue.indexOrConstraint)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra index issue has no table/index name'),\n );\n return ok([dropIndex(issue.table, issue.indexOrConstraint)]);\n\n case 'extra_unique_constraint':\n case 'extra_foreign_key':\n case 'extra_primary_key':\n if (!issue.table || !issue.indexOrConstraint)\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n 'Extra constraint issue has no table/constraint name',\n ),\n );\n return ok([dropConstraint(issue.table, issue.indexOrConstraint)]);\n\n case 'extra_default':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Extra default issue has no table/column name'),\n );\n return ok([dropDefault(issue.table, issue.column)]);\n\n // Nullability changes\n case 'nullability_mismatch': {\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('nullabilityConflict', 'Nullability mismatch has no table/column name'),\n );\n const column = ctx.toContract.storage.tables[issue.table]?.columns[issue.column];\n if (!column)\n return notOk(\n issueConflict(\n 'nullabilityConflict',\n `Column \"${issue.table}\".\"${issue.column}\" not found in destination contract`,\n ),\n );\n return ok(\n column.nullable\n ? [dropNotNull(issue.table, issue.column)]\n : [setNotNull(issue.table, issue.column)],\n );\n }\n\n // Type changes\n case 'type_mismatch':\n if (!issue.table || !issue.column)\n return notOk(issueConflict('typeMismatch', 'Type mismatch has no table/column name'));\n return ok([alterColumnType(issue.table, issue.column)]);\n\n // Default changes\n case 'default_mismatch':\n if (!issue.table || !issue.column)\n return notOk(\n issueConflict('unsupportedOperation', 'Default mismatch has no table/column name'),\n );\n return ok([setDefault(issue.table, issue.column)]);\n\n // Constraints — missing (actual undefined) vs mismatched (actual defined)\n case 'primary_key_mismatch':\n if (!issue.table)\n return notOk(issueConflict('indexIncompatible', 'Primary key issue has no table name'));\n if (isMissing(issue)) return ok([addPrimaryKey(issue.table)]);\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Primary key on \"${issue.table}\" has different columns (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'unique_constraint_mismatch':\n if (!issue.table)\n return notOk(\n issueConflict('indexIncompatible', 'Unique constraint issue has no table name'),\n );\n if (isMissing(issue) && issue.expected) {\n const columns = issue.expected.split(', ');\n return ok([addUnique(issue.table, columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Unique constraint on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'index_mismatch':\n if (!issue.table)\n return notOk(issueConflict('indexIncompatible', 'Index issue has no table name'));\n if (isMissing(issue) && issue.expected) {\n const columns = issue.expected.split(', ');\n return ok([createIndex(issue.table, columns)]);\n }\n return notOk(\n issueConflict(\n 'indexIncompatible',\n `Index on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n case 'foreign_key_mismatch':\n if (!issue.table)\n return notOk(issueConflict('foreignKeyConflict', 'Foreign key issue has no table name'));\n if (isMissing(issue) && issue.expected) {\n const arrowIdx = issue.expected.indexOf(' -> ');\n if (arrowIdx >= 0) {\n const columns = issue.expected.slice(0, arrowIdx).split(', ');\n return ok([addForeignKey(issue.table, columns)]);\n }\n }\n return notOk(\n issueConflict(\n 'foreignKeyConflict',\n `Foreign key on \"${issue.table}\" differs (expected: ${issue.expected}, actual: ${issue.actual})`,\n { table: issue.table },\n ),\n );\n\n // Types\n case 'type_missing': {\n if (!issue.typeName)\n return notOk(issueConflict('unsupportedOperation', 'Type missing issue has no typeName'));\n const typeInstance = ctx.toContract.storage.types?.[issue.typeName];\n if (!typeInstance) {\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName}\" reported missing but not found in destination contract`,\n ),\n );\n }\n // TODO: codec-specific descriptor dispatch should be driven by a registry, not hardcoded prefix checks\n if (typeInstance.codecId.startsWith('pg/enum')) {\n return ok([createEnumType(issue.typeName)]);\n }\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName}\" uses codec \"${typeInstance.codecId}\" — only enum types are supported by the descriptor planner`,\n ),\n );\n }\n\n case 'type_values_mismatch':\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Type \"${issue.typeName ?? 'unknown'}\" values differ — type alteration not yet supported by descriptor planner`,\n ),\n );\n\n // Dependencies\n case 'dependency_missing':\n if (!issue.dependencyId)\n return notOk(\n issueConflict('unsupportedOperation', 'Dependency missing issue has no dependencyId'),\n );\n return ok([createDependency(issue.dependencyId)]);\n default:\n return notOk(\n issueConflict(\n 'unsupportedOperation',\n `Unhandled issue kind: ${(issue as SchemaIssue).kind}`,\n ),\n );\n }\n}\n\n// ============================================================================\n// Planner entry point\n// ============================================================================\n\nexport interface DescriptorPlannerOptions {\n readonly issues: readonly SchemaIssue[];\n readonly toContract: Contract<SqlStorage>;\n readonly fromContract: Contract<SqlStorage> | null;\n readonly strategies?: readonly MigrationStrategy[];\n}\n\nexport interface DescriptorPlannerValue {\n readonly descriptors: readonly PostgresMigrationOpDescriptor[];\n}\n\nexport function planDescriptors(\n options: DescriptorPlannerOptions,\n): Result<DescriptorPlannerValue, readonly SqlPlannerConflict[]> {\n const context: StrategyContext = {\n toContract: options.toContract,\n fromContract: options.fromContract,\n };\n\n const strategies = options.strategies ?? migrationPlanStrategies;\n\n // Phase 1: Pattern matching — consume recognized issues\n let remaining = options.issues;\n const patternOps: PostgresMigrationOpDescriptor[] = [];\n\n for (const strategy of strategies) {\n const result = strategy(remaining, context);\n if (result.kind === 'match') {\n remaining = result.issues;\n patternOps.push(...result.ops);\n }\n }\n\n // Phase 2: Sort remaining issues by dependency order\n const sorted = [...remaining].sort((a, b) => issueOrder(a) - issueOrder(b));\n\n // Phase 3: Map remaining issues to descriptors, collecting conflicts\n const defaultOps: PostgresMigrationOpDescriptor[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n\n for (const issue of sorted) {\n const result = mapIssue(issue, context);\n if (result.ok) {\n defaultOps.push(...result.value);\n } else {\n conflicts.push(result.failure);\n }\n }\n\n if (conflicts.length > 0) {\n return notOk(conflicts);\n }\n\n // Phase 4: Order descriptors by operation kind\n const depOps = defaultOps.filter(\n (op) =>\n op.kind === 'createDependency' ||\n op.kind === 'createEnumType' ||\n op.kind === 'addEnumValues' ||\n op.kind === 'dropEnumType' ||\n op.kind === 'renameType',\n );\n const dropOps = defaultOps.filter(\n (op) =>\n op.kind === 'dropTable' ||\n op.kind === 'dropColumn' ||\n op.kind === 'dropConstraint' ||\n op.kind === 'dropIndex' ||\n op.kind === 'dropDefault',\n );\n const tableOps = defaultOps.filter((op) => op.kind === 'createTable');\n const columnOps = defaultOps.filter((op) => op.kind === 'addColumn');\n const alterOps = defaultOps.filter(\n (op) =>\n op.kind === 'alterColumnType' ||\n op.kind === 'setNotNull' ||\n op.kind === 'dropNotNull' ||\n op.kind === 'setDefault',\n );\n const constraintOps = defaultOps.filter(\n (op) =>\n op.kind === 'addPrimaryKey' ||\n op.kind === 'addUnique' ||\n op.kind === 'createIndex' ||\n op.kind === 'addForeignKey',\n );\n\n const descriptors: PostgresMigrationOpDescriptor[] = [\n ...depOps,\n ...dropOps,\n ...tableOps,\n ...columnOps,\n ...patternOps,\n ...alterOps,\n ...constraintOps,\n ];\n\n return ok({\n descriptors,\n });\n}\n","import { m as PG_JSON_CODEC_ID, p as PG_JSONB_CODEC_ID } from \"./codec-ids-BwjcIf74.mjs\";\nimport { t as codecDefinitions } from \"./codecs-C3wlpdV7.mjs\";\nimport { i as quoteIdentifier, n as escapeLiteral } from \"./sql-utils-CSfAGEwF.mjs\";\nimport { LiteralExpr, createCodecRegistry } from \"@prisma-next/sql-relational-core/ast\";\nimport { ifDefined } from \"@prisma-next/utils/defined\";\n\n//#region src/core/adapter.ts\nconst VECTOR_CODEC_ID = \"pg/vector@1\";\nfunction getCodecParamCast(codecId) {\n\tif (codecId === VECTOR_CODEC_ID) return \"vector\";\n\tif (codecId === PG_JSON_CODEC_ID) return \"json\";\n\tif (codecId === PG_JSONB_CODEC_ID) return \"jsonb\";\n}\nfunction renderTypedParam(index, codecId) {\n\tconst cast = getCodecParamCast(codecId);\n\treturn cast ? `$${index}::${cast}` : `$${index}`;\n}\nconst defaultCapabilities = Object.freeze({\n\tpostgres: {\n\t\torderBy: true,\n\t\tlimit: true,\n\t\tlateral: true,\n\t\tjsonAgg: true,\n\t\treturning: true\n\t},\n\tsql: {\n\t\tenums: true,\n\t\treturning: true,\n\t\tdefaultInInsert: true\n\t}\n});\nconst parameterizedCodecs = Object.values(codecDefinitions).map((definition) => definition.codec).filter((codec$1) => codec$1.paramsSchema !== void 0).map((codec$1) => Object.freeze({\n\tcodecId: codec$1.id,\n\tparamsSchema: codec$1.paramsSchema,\n\t...ifDefined(\"init\", codec$1.init)\n}));\nvar PostgresAdapterImpl = class {\n\tfamilyId = \"sql\";\n\ttargetId = \"postgres\";\n\tprofile;\n\tcodecRegistry = (() => {\n\t\tconst registry = createCodecRegistry();\n\t\tfor (const definition of Object.values(codecDefinitions)) registry.register(definition.codec);\n\t\treturn registry;\n\t})();\n\tconstructor(options) {\n\t\tthis.profile = Object.freeze({\n\t\t\tid: options?.profileId ?? \"postgres/default@1\",\n\t\t\ttarget: \"postgres\",\n\t\t\tcapabilities: defaultCapabilities,\n\t\t\tcodecs: () => this.codecRegistry,\n\t\t\treadMarkerStatement: () => ({\n\t\t\t\tsql: \"select core_hash, profile_hash, contract_json, canonical_version, updated_at, app_tag, meta from prisma_contract.marker where id = $1\",\n\t\t\t\tparams: [1]\n\t\t\t})\n\t\t});\n\t}\n\tparameterizedCodecs() {\n\t\treturn parameterizedCodecs;\n\t}\n\tlower(ast, context) {\n\t\tconst collectedParamRefs = ast.collectParamRefs();\n\t\tconst paramIndexMap = /* @__PURE__ */ new Map();\n\t\tconst params = [];\n\t\tfor (const ref of collectedParamRefs) {\n\t\t\tif (paramIndexMap.has(ref)) continue;\n\t\t\tparamIndexMap.set(ref, params.length + 1);\n\t\t\tparams.push(ref.value);\n\t\t}\n\t\tlet sql;\n\t\tconst node = ast;\n\t\tswitch (node.kind) {\n\t\t\tcase \"select\":\n\t\t\t\tsql = renderSelect(node, context.contract, paramIndexMap);\n\t\t\t\tbreak;\n\t\t\tcase \"insert\":\n\t\t\t\tsql = renderInsert(node, context.contract, paramIndexMap);\n\t\t\t\tbreak;\n\t\t\tcase \"update\":\n\t\t\t\tsql = renderUpdate(node, context.contract, paramIndexMap);\n\t\t\t\tbreak;\n\t\t\tcase \"delete\":\n\t\t\t\tsql = renderDelete(node, context.contract, paramIndexMap);\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unsupported AST node kind: ${node.kind}`);\n\t\t}\n\t\treturn Object.freeze({\n\t\t\tprofileId: this.profile.id,\n\t\t\tbody: Object.freeze({\n\t\t\t\tsql,\n\t\t\t\tparams\n\t\t\t})\n\t\t});\n\t}\n};\nfunction renderSelect(ast, contract, pim) {\n\treturn [\n\t\t`SELECT ${renderDistinctPrefix(ast.distinct, ast.distinctOn, contract, pim)}${renderProjection(ast.projection, contract, pim)}`,\n\t\t`FROM ${renderSource(ast.from, contract, pim)}`,\n\t\tast.joins?.length ? ast.joins.map((join) => renderJoin(join, contract, pim)).join(\" \") : \"\",\n\t\tast.where ? `WHERE ${renderWhere(ast.where, contract, pim)}` : \"\",\n\t\tast.groupBy?.length ? `GROUP BY ${ast.groupBy.map((expr) => renderExpr(expr, contract, pim)).join(\", \")}` : \"\",\n\t\tast.having ? `HAVING ${renderWhere(ast.having, contract, pim)}` : \"\",\n\t\tast.orderBy?.length ? `ORDER BY ${ast.orderBy.map((order) => {\n\t\t\treturn `${renderExpr(order.expr, contract, pim)} ${order.dir.toUpperCase()}`;\n\t\t}).join(\", \")}` : \"\",\n\t\ttypeof ast.limit === \"number\" ? `LIMIT ${ast.limit}` : \"\",\n\t\ttypeof ast.offset === \"number\" ? `OFFSET ${ast.offset}` : \"\"\n\t].filter((part) => part.length > 0).join(\" \").trim();\n}\nfunction renderProjection(projection, contract, pim) {\n\treturn projection.map((item) => {\n\t\tconst alias = quoteIdentifier(item.alias);\n\t\tif (item.expr.kind === \"literal\") return `${renderLiteral(item.expr)} AS ${alias}`;\n\t\treturn `${renderExpr(item.expr, contract, pim)} AS ${alias}`;\n\t}).join(\", \");\n}\nfunction renderDistinctPrefix(distinct, distinctOn, contract, pim) {\n\tif (distinctOn && distinctOn.length > 0) return `DISTINCT ON (${distinctOn.map((expr) => renderExpr(expr, contract, pim)).join(\", \")}) `;\n\tif (distinct) return \"DISTINCT \";\n\treturn \"\";\n}\nfunction renderSource(source, contract, pim) {\n\tconst node = source;\n\tswitch (node.kind) {\n\t\tcase \"table-source\": {\n\t\t\tconst table = quoteIdentifier(node.name);\n\t\t\tif (!node.alias) return table;\n\t\t\treturn `${table} AS ${quoteIdentifier(node.alias)}`;\n\t\t}\n\t\tcase \"derived-table-source\": return `(${renderSelect(node.query, contract, pim)}) AS ${quoteIdentifier(node.alias)}`;\n\t\tdefault: throw new Error(`Unsupported source node kind: ${node.kind}`);\n\t}\n}\nfunction assertScalarSubquery(query) {\n\tif (query.projection.length !== 1) throw new Error(\"Subquery expressions must project exactly one column\");\n}\nfunction renderSubqueryExpr(expr, contract, pim) {\n\tassertScalarSubquery(expr.query);\n\treturn `(${renderSelect(expr.query, contract, pim)})`;\n}\nfunction renderWhere(expr, contract, pim) {\n\treturn renderExpr(expr, contract, pim);\n}\nfunction renderNullCheck(expr, contract, pim) {\n\tconst rendered = renderExpr(expr.expr, contract, pim);\n\tconst renderedExpr = expr.expr.kind === \"operation\" || expr.expr.kind === \"subquery\" ? `(${rendered})` : rendered;\n\treturn expr.isNull ? `${renderedExpr} IS NULL` : `${renderedExpr} IS NOT NULL`;\n}\nfunction renderBinary(expr, contract, pim) {\n\tif (expr.right.kind === \"list\" && expr.right.values.length === 0) {\n\t\tif (expr.op === \"in\") return \"FALSE\";\n\t\tif (expr.op === \"notIn\") return \"TRUE\";\n\t}\n\tconst leftExpr = expr.left;\n\tconst left = renderExpr(leftExpr, contract, pim);\n\tconst leftRendered = leftExpr.kind === \"operation\" || leftExpr.kind === \"subquery\" ? `(${left})` : left;\n\tconst rightNode = expr.right;\n\tlet right;\n\tswitch (rightNode.kind) {\n\t\tcase \"list\":\n\t\t\tright = renderListLiteral(rightNode, pim);\n\t\t\tbreak;\n\t\tcase \"literal\":\n\t\t\tright = renderLiteral(rightNode);\n\t\t\tbreak;\n\t\tcase \"column-ref\":\n\t\t\tright = renderColumn(rightNode);\n\t\t\tbreak;\n\t\tcase \"param-ref\":\n\t\t\tright = renderParamRef(rightNode, pim);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tright = renderExpr(rightNode, contract, pim);\n\t\t\tbreak;\n\t}\n\treturn `${leftRendered} ${{\n\t\teq: \"=\",\n\t\tneq: \"!=\",\n\t\tgt: \">\",\n\t\tlt: \"<\",\n\t\tgte: \">=\",\n\t\tlte: \"<=\",\n\t\tlike: \"LIKE\",\n\t\tilike: \"ILIKE\",\n\t\tin: \"IN\",\n\t\tnotIn: \"NOT IN\"\n\t}[expr.op]} ${right}`;\n}\nfunction renderListLiteral(expr, pim) {\n\tif (expr.values.length === 0) return \"(NULL)\";\n\treturn `(${expr.values.map((v) => {\n\t\tif (v.kind === \"param-ref\") return renderParamRef(v, pim);\n\t\tif (v.kind === \"literal\") return renderLiteral(v);\n\t\treturn renderExpr(v, void 0, pim);\n\t}).join(\", \")})`;\n}\nfunction renderColumn(ref) {\n\tif (ref.table === \"excluded\") return `excluded.${quoteIdentifier(ref.column)}`;\n\treturn `${quoteIdentifier(ref.table)}.${quoteIdentifier(ref.column)}`;\n}\nfunction renderAggregateExpr(expr, contract, pim) {\n\tconst fn = expr.fn.toUpperCase();\n\tif (!expr.expr) return `${fn}(*)`;\n\treturn `${fn}(${renderExpr(expr.expr, contract, pim)})`;\n}\nfunction renderJsonObjectExpr(expr, contract, pim) {\n\treturn `json_build_object(${expr.entries.flatMap((entry) => {\n\t\tconst key = `'${escapeLiteral(entry.key)}'`;\n\t\tif (entry.value.kind === \"literal\") return [key, renderLiteral(entry.value)];\n\t\treturn [key, renderExpr(entry.value, contract, pim)];\n\t}).join(\", \")})`;\n}\nfunction renderOrderByItems(items, contract, pim) {\n\treturn items.map((item) => `${renderExpr(item.expr, contract, pim)} ${item.dir.toUpperCase()}`).join(\", \");\n}\nfunction renderJsonArrayAggExpr(expr, contract, pim) {\n\tconst aggregateOrderBy = expr.orderBy && expr.orderBy.length > 0 ? ` ORDER BY ${renderOrderByItems(expr.orderBy, contract, pim)}` : \"\";\n\tconst aggregated = `json_agg(${renderExpr(expr.expr, contract, pim)}${aggregateOrderBy})`;\n\tif (expr.onEmpty === \"emptyArray\") return `coalesce(${aggregated}, json_build_array())`;\n\treturn aggregated;\n}\nfunction renderExpr(expr, contract, pim) {\n\tconst node = expr;\n\tswitch (node.kind) {\n\t\tcase \"column-ref\": return renderColumn(node);\n\t\tcase \"identifier-ref\": return quoteIdentifier(node.name);\n\t\tcase \"operation\": return renderOperation(node, contract, pim);\n\t\tcase \"subquery\": return renderSubqueryExpr(node, contract, pim);\n\t\tcase \"aggregate\": return renderAggregateExpr(node, contract, pim);\n\t\tcase \"json-object\": return renderJsonObjectExpr(node, contract, pim);\n\t\tcase \"json-array-agg\": return renderJsonArrayAggExpr(node, contract, pim);\n\t\tcase \"binary\": return renderBinary(node, contract, pim);\n\t\tcase \"and\":\n\t\t\tif (node.exprs.length === 0) return \"TRUE\";\n\t\t\treturn `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(\" AND \")})`;\n\t\tcase \"or\":\n\t\t\tif (node.exprs.length === 0) return \"FALSE\";\n\t\t\treturn `(${node.exprs.map((part) => renderExpr(part, contract, pim)).join(\" OR \")})`;\n\t\tcase \"exists\": return `${node.notExists ? \"NOT \" : \"\"}EXISTS (${renderSelect(node.subquery, contract, pim)})`;\n\t\tcase \"null-check\": return renderNullCheck(node, contract, pim);\n\t\tcase \"not\": return `NOT (${renderExpr(node.expr, contract, pim)})`;\n\t\tcase \"param-ref\": return renderParamRef(node, pim);\n\t\tcase \"literal\": return renderLiteral(node);\n\t\tcase \"list\": return renderListLiteral(node, pim);\n\t\tdefault: throw new Error(`Unsupported expression node kind: ${node.kind}`);\n\t}\n}\nfunction renderParamRef(ref, pim) {\n\tconst index = pim?.get(ref);\n\tif (index === void 0) throw new Error(\"ParamRef not found in index map\");\n\treturn renderTypedParam(index, ref.codecId);\n}\nfunction renderLiteral(expr) {\n\tif (typeof expr.value === \"string\") return `'${escapeLiteral(expr.value)}'`;\n\tif (typeof expr.value === \"number\" || typeof expr.value === \"boolean\") return String(expr.value);\n\tif (typeof expr.value === \"bigint\") return String(expr.value);\n\tif (expr.value === null) return \"NULL\";\n\tif (expr.value === void 0) return \"NULL\";\n\tif (expr.value instanceof Date) return `'${escapeLiteral(expr.value.toISOString())}'`;\n\tif (Array.isArray(expr.value)) return `ARRAY[${expr.value.map((v) => renderLiteral(new LiteralExpr(v))).join(\", \")}]`;\n\tconst json = JSON.stringify(expr.value);\n\tif (json === void 0) return \"NULL\";\n\treturn `'${escapeLiteral(json)}'`;\n}\nfunction renderOperation(expr, contract, pim) {\n\tconst self = renderExpr(expr.self, contract, pim);\n\tconst args = expr.args.map((arg) => {\n\t\treturn renderExpr(arg, contract, pim);\n\t});\n\tlet result = expr.lowering.template;\n\tresult = result.replace(/\\{\\{self\\}\\}/g, self);\n\tfor (let i = 0; i < args.length; i++) result = result.replace(new RegExp(`\\\\{\\\\{arg${i}\\\\}\\\\}`, \"g\"), args[i] ?? \"\");\n\treturn result;\n}\nfunction renderJoin(join, contract, pim) {\n\treturn `${join.joinType.toUpperCase()} JOIN ${join.lateral ? \"LATERAL \" : \"\"}${renderSource(join.source, contract, pim)} ON ${renderJoinOn(join.on, contract, pim)}`;\n}\nfunction renderJoinOn(on, contract, pim) {\n\tif (on.kind === \"eq-col-join-on\") return `${renderColumn(on.left)} = ${renderColumn(on.right)}`;\n\treturn renderWhere(on, contract, pim);\n}\nfunction getInsertColumnOrder(rows, contract, tableName) {\n\tconst orderedColumns = [];\n\tconst seenColumns = /* @__PURE__ */ new Set();\n\tfor (const row of rows) for (const column of Object.keys(row)) {\n\t\tif (seenColumns.has(column)) continue;\n\t\tseenColumns.add(column);\n\t\torderedColumns.push(column);\n\t}\n\tif (orderedColumns.length > 0) return orderedColumns;\n\treturn Object.keys(contract.storage.tables[tableName]?.columns ?? {});\n}\nfunction renderInsertValue(value, pim) {\n\tif (!value || value.kind === \"default-value\") return \"DEFAULT\";\n\tswitch (value.kind) {\n\t\tcase \"param-ref\": return renderParamRef(value, pim);\n\t\tcase \"column-ref\": return renderColumn(value);\n\t\tdefault: throw new Error(`Unsupported value node in INSERT: ${value.kind}`);\n\t}\n}\nfunction renderInsert(ast, contract, pim) {\n\tconst table = quoteIdentifier(ast.table.name);\n\tconst rows = ast.rows;\n\tif (rows.length === 0) throw new Error(\"INSERT requires at least one row\");\n\tconst hasExplicitValues = rows.some((row) => Object.keys(row).length > 0);\n\treturn `${(() => {\n\t\tif (!hasExplicitValues) {\n\t\t\tif (rows.length === 1) return `INSERT INTO ${table} DEFAULT VALUES`;\n\t\t\tconst defaultColumns = getInsertColumnOrder(rows, contract, ast.table.name);\n\t\t\tif (defaultColumns.length === 0) return `INSERT INTO ${table} VALUES ${rows.map(() => \"()\").join(\", \")}`;\n\t\t\tconst quotedColumns = defaultColumns.map((column) => quoteIdentifier(column));\n\t\t\tconst defaultRow = `(${defaultColumns.map(() => \"DEFAULT\").join(\", \")})`;\n\t\t\treturn `INSERT INTO ${table} (${quotedColumns.join(\", \")}) VALUES ${rows.map(() => defaultRow).join(\", \")}`;\n\t\t}\n\t\tconst columnOrder = getInsertColumnOrder(rows, contract, ast.table.name);\n\t\tconst columns = columnOrder.map((column) => quoteIdentifier(column));\n\t\tconst values = rows.map((row) => {\n\t\t\treturn `(${columnOrder.map((column) => renderInsertValue(row[column], pim)).join(\", \")})`;\n\t\t}).join(\", \");\n\t\treturn `INSERT INTO ${table} (${columns.join(\", \")}) VALUES ${values}`;\n\t})()}${ast.onConflict ? (() => {\n\t\tconst conflictColumns = ast.onConflict.columns.map((col) => quoteIdentifier(col.column));\n\t\tif (conflictColumns.length === 0) throw new Error(\"INSERT onConflict requires at least one conflict column\");\n\t\tconst action = ast.onConflict.action;\n\t\tswitch (action.kind) {\n\t\t\tcase \"do-nothing\": return ` ON CONFLICT (${conflictColumns.join(\", \")}) DO NOTHING`;\n\t\t\tcase \"do-update-set\": {\n\t\t\t\tconst updates = Object.entries(action.set).map(([colName, value]) => {\n\t\t\t\t\tconst target = quoteIdentifier(colName);\n\t\t\t\t\tif (value.kind === \"param-ref\") return `${target} = ${renderParamRef(value, pim)}`;\n\t\t\t\t\treturn `${target} = ${renderColumn(value)}`;\n\t\t\t\t});\n\t\t\t\treturn ` ON CONFLICT (${conflictColumns.join(\", \")}) DO UPDATE SET ${updates.join(\", \")}`;\n\t\t\t}\n\t\t\tdefault: throw new Error(`Unsupported onConflict action: ${action.kind}`);\n\t\t}\n\t})() : \"\"}${ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(\", \")}` : \"\"}`;\n}\nfunction renderUpdate(ast, contract, pim) {\n\tconst table = quoteIdentifier(ast.table.name);\n\tconst setClauses = Object.entries(ast.set).map(([col, val]) => {\n\t\tconst column = quoteIdentifier(col);\n\t\tlet value;\n\t\tswitch (val.kind) {\n\t\t\tcase \"param-ref\":\n\t\t\t\tvalue = renderParamRef(val, pim);\n\t\t\t\tbreak;\n\t\t\tcase \"column-ref\":\n\t\t\t\tvalue = renderColumn(val);\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unsupported value node in UPDATE: ${val.kind}`);\n\t\t}\n\t\treturn `${column} = ${value}`;\n\t});\n\tconst whereClause = ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : \"\";\n\tconst returningClause = ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(\", \")}` : \"\";\n\treturn `UPDATE ${table} SET ${setClauses.join(\", \")}${whereClause}${returningClause}`;\n}\nfunction renderDelete(ast, contract, pim) {\n\treturn `DELETE FROM ${quoteIdentifier(ast.table.name)}${ast.where ? ` WHERE ${renderWhere(ast.where, contract, pim)}` : \"\"}${ast.returning?.length ? ` RETURNING ${ast.returning.map((col) => `${quoteIdentifier(col.table)}.${quoteIdentifier(col.column)}`).join(\", \")}` : \"\"}`;\n}\nfunction createPostgresAdapter(options) {\n\treturn Object.freeze(new PostgresAdapterImpl(options));\n}\n\n//#endregion\nexport { createPostgresAdapter as t };\n//# sourceMappingURL=adapter-7pXt8ej9.mjs.map","import type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\n\nexport type ResolvedColumnTypeMetadata = Pick<\n StorageColumn,\n 'nativeType' | 'codecId' | 'typeParams'\n>;\n\nexport function resolveColumnTypeMetadata(\n column: StorageColumn,\n storageTypes: Record<string, StorageTypeInstance>,\n): ResolvedColumnTypeMetadata {\n if (!column.typeRef) {\n return column;\n }\n\n const referencedType = storageTypes[column.typeRef];\n if (!referencedType) {\n return column;\n }\n\n return {\n codecId: referencedType.codecId,\n nativeType: referencedType.nativeType,\n typeParams: referencedType.typeParams,\n };\n}\n","import { escapeLiteral, quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\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\n/**\n * When `table` is omitted the check matches by name + schema across all tables.\n * Pass `table` to scope the check to a single table (prevents false matches on\n * identically-named constraints in different tables).\n */\nexport function constraintExistsCheck({\n constraintName,\n schema,\n table,\n exists = true,\n}: {\n constraintName: string;\n schema: string;\n table?: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? 'EXISTS' : 'NOT EXISTS';\n const tableFilter = table\n ? `AND c.conrelid = to_regclass(${toRegclassLiteral(schema, table)})`\n : '';\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 ${tableFilter}\n)`;\n}\n\nexport function columnExistsCheck({\n schema,\n table,\n column,\n exists = true,\n}: {\n schema: string;\n table: string;\n column: string;\n exists?: boolean;\n}): string {\n const existsClause = exists ? '' : 'NOT ';\n return `SELECT ${existsClause}EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n)`;\n}\n\nexport function columnNullabilityCheck({\n schema,\n table,\n column,\n nullable,\n}: {\n schema: string;\n table: string;\n column: string;\n nullable: boolean;\n}): string {\n const expected = nullable ? 'YES' : 'NO';\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n AND is_nullable = '${expected}'\n)`;\n}\n\nexport function tableIsEmptyCheck(qualifiedTableName: string): string {\n return `SELECT NOT EXISTS (SELECT 1 FROM ${qualifiedTableName} LIMIT 1)`;\n}\n\nexport function columnHasNoDefaultCheck(opts: {\n schema: string;\n table: string;\n column: string;\n}): string {\n return `SELECT NOT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(opts.schema)}'\n AND table_name = '${escapeLiteral(opts.table)}'\n AND column_name = '${escapeLiteral(opts.column)}'\n AND column_default IS NOT NULL\n)`;\n}\n\nconst FORMAT_TYPE_DISPLAY: ReadonlyMap<string, string> = new Map([\n ['int2', 'smallint'],\n ['int4', 'integer'],\n ['int8', 'bigint'],\n ['float4', 'real'],\n ['float8', 'double precision'],\n ['bool', 'boolean'],\n ['timestamp', 'timestamp without time zone'],\n ['timestamptz', 'timestamp with time zone'],\n ['time', 'time without time zone'],\n ['timetz', 'time with time zone'],\n]);\n\nconst UNQUOTED_POSTGRES_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/;\n\nconst POSTGRES_RESERVED_IDENTIFIER_WORDS = new Set([\n 'all',\n 'analyse',\n 'analyze',\n 'and',\n 'any',\n 'array',\n 'as',\n 'asc',\n 'asymmetric',\n 'authorization',\n 'between',\n 'binary',\n 'both',\n 'case',\n 'cast',\n 'check',\n 'collate',\n 'column',\n 'constraint',\n 'create',\n 'current_catalog',\n 'current_date',\n 'current_role',\n 'current_time',\n 'current_timestamp',\n 'current_user',\n 'default',\n 'deferrable',\n 'desc',\n 'distinct',\n 'do',\n 'else',\n 'end',\n 'except',\n 'false',\n 'fetch',\n 'for',\n 'foreign',\n 'freeze',\n 'from',\n 'full',\n 'grant',\n 'group',\n 'having',\n 'ilike',\n 'in',\n 'initially',\n 'inner',\n 'intersect',\n 'into',\n 'is',\n 'isnull',\n 'join',\n 'lateral',\n 'leading',\n 'left',\n 'like',\n 'limit',\n 'localtime',\n 'localtimestamp',\n 'natural',\n 'not',\n 'notnull',\n 'null',\n 'offset',\n 'on',\n 'only',\n 'or',\n 'order',\n 'outer',\n 'overlaps',\n 'placing',\n 'primary',\n 'references',\n 'right',\n 'select',\n 'session_user',\n 'similar',\n 'some',\n 'symmetric',\n 'table',\n 'then',\n 'to',\n 'trailing',\n 'true',\n 'union',\n 'unique',\n 'user',\n 'using',\n 'variadic',\n 'verbose',\n 'when',\n 'where',\n 'window',\n 'with',\n]);\n\nfunction formatUserDefinedTypeName(identifier: string): string {\n if (\n UNQUOTED_POSTGRES_IDENTIFIER_PATTERN.test(identifier) &&\n !POSTGRES_RESERVED_IDENTIFIER_WORDS.has(identifier)\n ) {\n return identifier;\n }\n\n return quoteIdentifier(identifier);\n}\n\nexport function buildExpectedFormatType(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (resolved.typeParams && resolved.codecId) {\n const hooks = codecHooks.get(resolved.codecId);\n if (hooks?.expandNativeType) {\n return hooks.expandNativeType({\n nativeType: resolved.nativeType,\n codecId: resolved.codecId,\n typeParams: resolved.typeParams,\n });\n }\n }\n\n if (column.typeRef) {\n return formatUserDefinedTypeName(resolved.nativeType);\n }\n\n return FORMAT_TYPE_DISPLAY.get(resolved.nativeType) ?? resolved.nativeType;\n}\n\nexport function columnTypeCheck({\n schema,\n table,\n column,\n expectedType,\n}: {\n schema: string;\n table: string;\n column: string;\n expectedType: string;\n}): string {\n return `SELECT EXISTS (\n SELECT 1\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = '${escapeLiteral(schema)}'\n AND c.relname = '${escapeLiteral(table)}'\n AND a.attname = '${escapeLiteral(column)}'\n AND format_type(a.atttypid, a.atttypmod) = '${escapeLiteral(expectedType)}'\n AND NOT a.attisdropped\n)`;\n}\n\nexport function columnDefaultExistsCheck({\n schema,\n table,\n column,\n exists = true,\n}: {\n schema: string;\n table: string;\n column: string;\n exists?: boolean;\n}): string {\n const nullCheck = exists ? 'IS NOT NULL' : 'IS NULL';\n return `SELECT EXISTS (\n SELECT 1\n FROM information_schema.columns\n WHERE table_schema = '${escapeLiteral(schema)}'\n AND table_name = '${escapeLiteral(table)}'\n AND column_name = '${escapeLiteral(column)}'\n AND column_default ${nullCheck}\n)`;\n}\n\nexport function 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","import { escapeLiteral, quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type {\n ForeignKey,\n ReferentialAction,\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport type { PostgresColumnDefault } from '../types';\nimport { qualifyTableName } from './planner-sql-checks';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\n\nexport function buildCreateTableSql(\n qualifiedTableName: string,\n table: StorageTable,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const columnDefinitions = Object.entries(table.columns).map(\n ([columnName, column]: [string, StorageColumn]) => {\n const parts = [\n quoteIdentifier(columnName),\n buildColumnTypeSql(column, codecHooks, storageTypes),\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 * Renders the SQL type for a column in DDL context.\n *\n * @param allowPseudoTypes - When true (default), autoincrement integer columns\n * produce SERIAL/BIGSERIAL/SMALLSERIAL pseudo-types. Set to false for contexts\n * like ALTER COLUMN TYPE where pseudo-types are invalid.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n allowPseudoTypes = true,\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (allowPseudoTypes) {\n const columnDefault = column.default;\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (resolved.nativeType === 'int4' || resolved.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (resolved.nativeType === 'int8' || resolved.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (resolved.nativeType === 'int2' || resolved.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n }\n\n const expanded = expandParameterizedTypeSql(resolved, codecHooks);\n if (expanded !== null) {\n return expanded;\n }\n\n if (column.typeRef) {\n return quoteIdentifier(resolved.nativeType);\n }\n\n assertSafeNativeType(resolved.nativeType);\n return resolved.nativeType;\n}\n\nfunction expandParameterizedTypeSql(\n column: Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>,\n codecHooks: Map<string, CodecControlHooks>,\n): string | null {\n if (!column.typeParams) {\n return null;\n }\n\n if (!column.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(column.codecId);\n if (!hooks?.expandNativeType) {\n if (hooks?.planTypeOperations) {\n return null;\n }\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${column.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n\n const expanded = hooks.expandNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n typeParams: column.typeParams,\n });\n\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/** Autoincrement columns use SERIAL types, so this returns empty for them. */\nexport function buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n return `DEFAULT nextval('${escapeLiteral(quoteIdentifier(columnDefault.name))}'::regclass)`;\n }\n}\n\nexport function renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (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 buildAddColumnSql(\n qualifiedTableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n temporaryDefault?: string | null,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const typeSql = buildColumnTypeSql(column, codecHooks, storageTypes);\n const defaultSql =\n buildColumnDefaultSql(column.default, column) ||\n (temporaryDefault ? `DEFAULT ${temporaryDefault}` : '');\n const parts = [\n `ALTER TABLE ${qualifiedTableName}`,\n `ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,\n defaultSql,\n column.nullable ? '' : 'NOT NULL',\n ].filter(Boolean);\n return parts.join(' ');\n}\n\nconst REFERENTIAL_ACTION_SQL: Record<ReferentialAction, string> = {\n noAction: 'NO ACTION',\n restrict: 'RESTRICT',\n cascade: 'CASCADE',\n setNull: 'SET NULL',\n setDefault: 'SET DEFAULT',\n};\n\nexport function buildForeignKeySql(\n schemaName: string,\n tableName: string,\n fkName: string,\n foreignKey: ForeignKey,\n): string {\n let sql = `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(fkName)}\nFOREIGN KEY (${foreignKey.columns.map(quoteIdentifier).join(', ')})\nREFERENCES ${qualifyTableName(schemaName, foreignKey.references.table)} (${foreignKey.references.columns\n .map(quoteIdentifier)\n .join(', ')})`;\n\n if (foreignKey.onDelete !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onDelete];\n if (!action) {\n throw new Error(`Unknown referential action for onDelete: ${String(foreignKey.onDelete)}`);\n }\n sql += `\\nON DELETE ${action}`;\n }\n if (foreignKey.onUpdate !== undefined) {\n const action = REFERENTIAL_ACTION_SQL[foreignKey.onUpdate];\n if (!action) {\n throw new Error(`Unknown referential action for onUpdate: ${String(foreignKey.onUpdate)}`);\n }\n sql += `\\nON UPDATE ${action}`;\n }\n\n return sql;\n}\n","/**\n * Resolves thin operation descriptors into SqlMigrationPlanOperation objects\n * by looking up contract types and calling existing planner SQL helpers.\n *\n * This is the bridge between the ergonomic builder API (descriptors) and\n * the planner's SQL generation pipeline. It runs at verification time.\n */\n\nimport { createPostgresAdapter } from '@prisma-next/adapter-postgres/adapter';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n ComponentDatabaseDependency,\n SqlMigrationPlanOperation,\n} from '@prisma-next/family-sql/control';\nimport type {\n DataTransformOperation,\n SerializedQueryPlan,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn, StorageTable } from '@prisma-next/sql-contract/types';\nimport type { SqlQueryPlan } from '@prisma-next/sql-relational-core/plan';\nimport { lowerSqlPlan } from '@prisma-next/sql-runtime';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type {\n AddColumnDescriptor,\n AddEnumValuesDescriptor,\n AddForeignKeyDescriptor,\n AddPrimaryKeyDescriptor,\n AddUniqueDescriptor,\n AlterColumnTypeDescriptor,\n CreateDependencyDescriptor,\n CreateEnumTypeDescriptor,\n CreateIndexDescriptor,\n CreateTableDescriptor,\n DataTransformDescriptor,\n DropColumnDescriptor,\n DropConstraintDescriptor,\n DropDefaultDescriptor,\n DropEnumTypeDescriptor,\n DropIndexDescriptor,\n DropNotNullDescriptor,\n DropTableDescriptor,\n PostgresMigrationOpDescriptor,\n RenameTypeDescriptor,\n SetDefaultDescriptor,\n SetNotNullDescriptor,\n} from './operation-descriptors';\nimport {\n buildAddColumnSql,\n buildColumnDefaultSql,\n buildCreateTableSql,\n buildForeignKeySql,\n} from './planner-ddl-builders';\nimport {\n buildExpectedFormatType,\n columnExistsCheck,\n columnNullabilityCheck,\n columnTypeCheck,\n constraintExistsCheck,\n qualifyTableName,\n toRegclassLiteral,\n} from './planner-sql-checks';\nimport type { OperationClass, PostgresPlanTargetDetails } from './planner-target-details';\n\nexport interface OperationResolverContext {\n readonly toContract: Contract<SqlStorage>;\n readonly schemaName: string;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly dependencies?: readonly ComponentDatabaseDependency<unknown>[];\n readonly db?: unknown;\n}\n\ntype ResolvedOp = SqlMigrationPlanOperation<PostgresPlanTargetDetails>;\n\nfunction getTable(contract: Contract<SqlStorage>, tableName: string): StorageTable | undefined {\n return contract.storage.tables[tableName];\n}\n\nfunction getColumn(\n contract: Contract<SqlStorage>,\n tableName: string,\n columnName: string,\n): StorageColumn | undefined {\n return getTable(contract, tableName)?.columns[columnName];\n}\n\nfunction targetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n): { readonly id: 'postgres'; readonly details: PostgresPlanTargetDetails } {\n return {\n id: 'postgres',\n details: { schema, objectType, name, ...ifDefined('table', table) },\n };\n}\n\nfunction step(description: string, sql: string) {\n return { description, sql };\n}\n\nfunction resolveCreateTable(\n desc: CreateTableDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n if (!table) throw new Error(`Table \"${desc.table}\" not found in destination contract`);\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `table.${desc.table}`,\n label: `Create table \"${desc.table}\"`,\n summary: `Creates table \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('table', desc.table, ctx.schemaName),\n precheck: [\n step(\n `ensure table \"${desc.table}\" does not exist`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.table)}) IS NULL`,\n ),\n ],\n execute: [\n step(`create table \"${desc.table}\"`, buildCreateTableSql(qualified, table, ctx.codecHooks)),\n ],\n postcheck: [\n step(\n `verify table \"${desc.table}\" exists`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.table)}) IS NOT NULL`,\n ),\n ],\n };\n}\n\nfunction resolveDropTable(desc: DropTableDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `dropTable.${desc.table}`,\n label: `Drop table \"${desc.table}\"`,\n operationClass: 'destructive',\n target: targetDetails('table', desc.table, ctx.schemaName),\n precheck: [\n step(\n `ensure table \"${desc.table}\" exists`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.table)}) IS NOT NULL`,\n ),\n ],\n execute: [step(`drop table \"${desc.table}\"`, `DROP TABLE ${qualified}`)],\n postcheck: [\n step(\n `verify table \"${desc.table}\" does not exist`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.table)}) IS NULL`,\n ),\n ],\n };\n}\n\nfunction resolveAddColumn(desc: AddColumnDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const contractColumn = getColumn(ctx.toContract, desc.table, desc.column);\n if (!contractColumn)\n throw new Error(`Column \"${desc.table}\".\"${desc.column}\" not found in destination contract`);\n // Apply overrides — e.g., nullable: true for the add-nullable → backfill → setNotNull pattern\n const column: StorageColumn = {\n ...contractColumn,\n nullable:\n desc.overrides?.nullable !== undefined ? desc.overrides.nullable : contractColumn.nullable,\n };\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `column.${desc.table}.${desc.column}`,\n label: `Add column \"${desc.column}\" to \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" is missing`,\n columnExistsCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n exists: false,\n }),\n ),\n ],\n execute: [\n step(\n `add column \"${desc.column}\"`,\n buildAddColumnSql(qualified, desc.column, column, ctx.codecHooks),\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n };\n}\n\nfunction resolveDropColumn(desc: DropColumnDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `dropColumn.${desc.table}.${desc.column}`,\n label: `Drop column \"${desc.column}\" from \"${desc.table}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `drop column \"${desc.column}\"`,\n `ALTER TABLE ${qualified} DROP COLUMN ${quoteId(desc.column)}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" does not exist`,\n columnExistsCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n exists: false,\n }),\n ),\n ],\n };\n}\n\nfunction resolveAlterColumnType(\n desc: AlterColumnTypeDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const column = getColumn(ctx.toContract, desc.table, desc.column);\n if (!column)\n throw new Error(`Column \"${desc.table}\".\"${desc.column}\" not found in destination contract`);\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n const qualifiedTargetType = desc.toType\n ? qualifyName(ctx.schemaName, desc.toType)\n : buildExpectedFormatType(column, ctx.codecHooks);\n // format_type() returns unqualified names for types in search_path\n const formatTypeExpected = desc.toType ?? buildExpectedFormatType(column, ctx.codecHooks);\n return {\n id: `alterType.${desc.table}.${desc.column}`,\n label: `Alter type of \"${desc.table}\".\"${desc.column}\" to ${desc.toType ?? column.nativeType}`,\n operationClass: 'destructive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `alter type of \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} TYPE ${qualifiedTargetType}${desc.using ? ` USING ${desc.using}` : ` USING ${quoteId(desc.column)}::${qualifiedTargetType}`}`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" has type \"${formatTypeExpected}\"`,\n columnTypeCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n expectedType: formatTypeExpected,\n }),\n ),\n ],\n meta: { warning: 'TABLE_REWRITE' },\n };\n}\n\nfunction resolveSetNotNull(desc: SetNotNullDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `alterNullability.${desc.table}.${desc.column}`,\n label: `Set NOT NULL on \"${desc.table}\".\"${desc.column}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n step(\n `ensure no NULL values in \"${desc.column}\"`,\n `SELECT NOT EXISTS (SELECT 1 FROM ${qualified} WHERE ${quoteId(desc.column)} IS NULL)`,\n ),\n ],\n execute: [\n step(\n `set NOT NULL on \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} SET NOT NULL`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" is NOT NULL`,\n columnNullabilityCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n nullable: false,\n }),\n ),\n ],\n };\n}\n\nfunction resolveDropNotNull(\n desc: DropNotNullDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `alterNullability.${desc.table}.${desc.column}`,\n label: `Drop NOT NULL on \"${desc.table}\".\"${desc.column}\"`,\n operationClass: 'widening',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `drop NOT NULL on \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} DROP NOT NULL`,\n ),\n ],\n postcheck: [\n step(\n `verify column \"${desc.column}\" is nullable`,\n columnNullabilityCheck({\n schema: ctx.schemaName,\n table: desc.table,\n column: desc.column,\n nullable: true,\n }),\n ),\n ],\n };\n}\n\nfunction resolveSetDefault(desc: SetDefaultDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const column = getColumn(ctx.toContract, desc.table, desc.column);\n if (!column)\n throw new Error(`Column \"${desc.table}\".\"${desc.column}\" not found in destination contract`);\n const defaultSql = buildColumnDefaultSql(column.default, column);\n if (!defaultSql)\n throw new Error(\n `Column \"${desc.table}\".\"${desc.column}\" has no default in destination contract`,\n );\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `setDefault.${desc.table}.${desc.column}`,\n label: `Set default on \"${desc.table}\".\"${desc.column}\"`,\n operationClass: 'additive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `set default on \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} ${defaultSql}`,\n ),\n ],\n postcheck: [],\n };\n}\n\nfunction resolveDropDefault(\n desc: DropDefaultDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `dropDefault.${desc.table}.${desc.column}`,\n label: `Drop default on \"${desc.table}\".\"${desc.column}\"`,\n operationClass: 'destructive',\n target: targetDetails('column', desc.column, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure column \"${desc.column}\" exists`,\n columnExistsCheck({ schema: ctx.schemaName, table: desc.table, column: desc.column }),\n ),\n ],\n execute: [\n step(\n `drop default on \"${desc.column}\"`,\n `ALTER TABLE ${qualified} ALTER COLUMN ${quoteId(desc.column)} DROP DEFAULT`,\n ),\n ],\n postcheck: [],\n };\n}\n\nfunction resolveAddPrimaryKey(\n desc: AddPrimaryKeyDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n if (!table?.primaryKey)\n throw new Error(`Table \"${desc.table}\" has no primary key in destination contract`);\n const constraintName = table.primaryKey.name ?? `${desc.table}_pkey`;\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n const columnList = table.primaryKey.columns.map(quoteId).join(', ');\n return {\n id: `primaryKey.${desc.table}.${constraintName}`,\n label: `Add primary key on \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('primaryKey', constraintName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure primary key \"${constraintName}\" does not exist`,\n constraintExistsCheck({\n constraintName,\n schema: ctx.schemaName,\n table: desc.table,\n exists: false,\n }),\n ),\n ],\n execute: [\n step(\n `add primary key \"${constraintName}\"`,\n `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteId(constraintName)} PRIMARY KEY (${columnList})`,\n ),\n ],\n postcheck: [\n step(\n `verify primary key \"${constraintName}\" exists`,\n constraintExistsCheck({ constraintName, schema: ctx.schemaName, table: desc.table }),\n ),\n ],\n };\n}\n\nfunction resolveAddUnique(desc: AddUniqueDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n const unique = table?.uniques?.find((u) => u.columns.join(',') === desc.columns.join(','));\n const constraintName = unique?.name ?? `${desc.table}_${desc.columns.join('_')}_key`;\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n const columnList = desc.columns.map(quoteId).join(', ');\n return {\n id: `unique.${desc.table}.${constraintName}`,\n label: `Add unique constraint on \"${desc.table}\" (${desc.columns.join(', ')})`,\n operationClass: 'additive',\n target: targetDetails('unique', constraintName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure constraint \"${constraintName}\" does not exist`,\n constraintExistsCheck({\n constraintName,\n schema: ctx.schemaName,\n table: desc.table,\n exists: false,\n }),\n ),\n ],\n execute: [\n step(\n `add unique constraint \"${constraintName}\"`,\n `ALTER TABLE ${qualified} ADD CONSTRAINT ${quoteId(constraintName)} UNIQUE (${columnList})`,\n ),\n ],\n postcheck: [\n step(\n `verify constraint \"${constraintName}\" exists`,\n constraintExistsCheck({ constraintName, schema: ctx.schemaName, table: desc.table }),\n ),\n ],\n };\n}\n\nfunction resolveAddForeignKey(\n desc: AddForeignKeyDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n const fk = table?.foreignKeys?.find((f) => f.columns.join(',') === desc.columns.join(','));\n\n if (!fk) {\n throw new Error(\n `Foreign key on \"${desc.table}\" (${desc.columns.join(', ')}) not found in destination contract. ` +\n 'Ensure the FK is declared in the contract before authoring a migration that adds it.',\n );\n }\n\n const fkName = fk.name ?? `${desc.table}_${desc.columns.join('_')}_fkey`;\n\n return {\n id: `foreignKey.${desc.table}.${fkName}`,\n label: `Add foreign key \"${fkName}\" on \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('foreignKey', fkName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure FK \"${fkName}\" does not exist`,\n constraintExistsCheck({\n constraintName: fkName,\n schema: ctx.schemaName,\n table: desc.table,\n exists: false,\n }),\n ),\n ],\n execute: [\n step(`add FK \"${fkName}\"`, buildForeignKeySql(ctx.schemaName, desc.table, fkName, fk)),\n ],\n postcheck: [\n step(\n `verify FK \"${fkName}\" exists`,\n constraintExistsCheck({\n constraintName: fkName,\n schema: ctx.schemaName,\n table: desc.table,\n }),\n ),\n ],\n };\n}\n\nfunction resolveDropConstraint(\n desc: DropConstraintDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n return {\n id: `dropConstraint.${desc.table}.${desc.constraintName}`,\n label: `Drop constraint \"${desc.constraintName}\" on \"${desc.table}\"`,\n operationClass: 'destructive',\n target: targetDetails('unique', desc.constraintName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure constraint \"${desc.constraintName}\" exists`,\n constraintExistsCheck({\n constraintName: desc.constraintName,\n schema: ctx.schemaName,\n table: desc.table,\n }),\n ),\n ],\n execute: [\n step(\n `drop constraint \"${desc.constraintName}\"`,\n `ALTER TABLE ${qualified} DROP CONSTRAINT ${quoteId(desc.constraintName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify constraint \"${desc.constraintName}\" does not exist`,\n constraintExistsCheck({\n constraintName: desc.constraintName,\n schema: ctx.schemaName,\n table: desc.table,\n exists: false,\n }),\n ),\n ],\n };\n}\n\nfunction resolveCreateIndex(\n desc: CreateIndexDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const table = getTable(ctx.toContract, desc.table);\n const index = table?.indexes?.find((i) => i.columns.join(',') === desc.columns.join(','));\n const indexName = index?.name ?? `${desc.table}_${desc.columns.join('_')}_idx`;\n const qualified = qualifyTableName(ctx.schemaName, desc.table);\n const columnList = desc.columns.map(quoteId).join(', ');\n return {\n id: `index.${desc.table}.${indexName}`,\n label: `Create index \"${indexName}\" on \"${desc.table}\"`,\n operationClass: 'additive',\n target: targetDetails('index', indexName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure index \"${indexName}\" does not exist`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, indexName)}) IS NULL`,\n ),\n ],\n execute: [\n step(\n `create index \"${indexName}\"`,\n `CREATE INDEX ${quoteId(indexName)} ON ${qualified} (${columnList})`,\n ),\n ],\n postcheck: [\n step(\n `verify index \"${indexName}\" exists`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, indexName)}) IS NOT NULL`,\n ),\n ],\n };\n}\n\nfunction resolveDropIndex(desc: DropIndexDescriptor, ctx: OperationResolverContext): ResolvedOp {\n return {\n id: `dropIndex.${desc.table}.${desc.indexName}`,\n label: `Drop index \"${desc.indexName}\"`,\n operationClass: 'destructive',\n target: targetDetails('index', desc.indexName, ctx.schemaName, desc.table),\n precheck: [\n step(\n `ensure index \"${desc.indexName}\" exists`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.indexName)}) IS NOT NULL`,\n ),\n ],\n execute: [\n step(\n `drop index \"${desc.indexName}\"`,\n `DROP INDEX ${qualifyTableName(ctx.schemaName, desc.indexName)}`,\n ),\n ],\n postcheck: [\n step(\n `verify index \"${desc.indexName}\" does not exist`,\n `SELECT to_regclass(${toRegclassLiteral(ctx.schemaName, desc.indexName)}) IS NULL`,\n ),\n ],\n };\n}\n\nfunction enumTypeExistsCheck(schemaName: string, nativeType: string, exists = true): string {\n const clause = exists ? 'EXISTS' : 'NOT EXISTS';\n return `SELECT ${clause} (\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(nativeType)}'\n)`;\n}\n\nfunction resolveCreateEnumType(\n desc: CreateEnumTypeDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n // When explicit values are provided (e.g., temp type in rebuild recipe), use them directly.\n // The typeName may be a temp name not in the contract.\n const nativeType = desc.typeName;\n let values: readonly string[];\n if (desc.values) {\n values = desc.values;\n } else {\n const typeInstance = ctx.toContract.storage.types?.[desc.typeName];\n if (!typeInstance) {\n throw new Error(`Type \"${desc.typeName}\" not found in destination contract storage.types`);\n }\n const typeValues = typeInstance.typeParams?.['values'];\n if (\n !Array.isArray(typeValues) ||\n !typeValues.every((v): v is string => typeof v === 'string')\n ) {\n throw new Error(`Type \"${desc.typeName}\" has no valid enum values in typeParams`);\n }\n values = typeValues;\n }\n const qualifiedType = qualifyName(ctx.schemaName, nativeType);\n const literalValues = values.map((v) => `'${escapeLiteral(v)}'`).join(', ');\n return {\n id: `type.${nativeType}`,\n label: `Create enum type \"${nativeType}\"`,\n operationClass: 'additive',\n target: targetDetails('type', nativeType, ctx.schemaName),\n precheck: [\n step(\n `ensure type \"${nativeType}\" does not exist`,\n enumTypeExistsCheck(ctx.schemaName, nativeType, false),\n ),\n ],\n execute: [\n step(\n `create enum type \"${nativeType}\"`,\n `CREATE TYPE ${qualifiedType} AS ENUM (${literalValues})`,\n ),\n ],\n postcheck: [\n step(`verify type \"${nativeType}\" exists`, enumTypeExistsCheck(ctx.schemaName, nativeType)),\n ],\n };\n}\n\nfunction resolveAddEnumValues(\n desc: AddEnumValuesDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const typeInstance = ctx.toContract.storage.types?.[desc.typeName];\n if (!typeInstance) {\n throw new Error(`Type \"${desc.typeName}\" not found in destination contract storage.types`);\n }\n const qualifiedType = qualifyName(ctx.schemaName, typeInstance.nativeType);\n return {\n id: `type.${desc.typeName}.addValues`,\n label: `Add values to enum type \"${desc.typeName}\": ${desc.values.join(', ')}`,\n operationClass: 'additive',\n target: targetDetails('type', desc.typeName, ctx.schemaName),\n precheck: [\n step(\n `ensure type \"${typeInstance.nativeType}\" exists`,\n enumTypeExistsCheck(ctx.schemaName, typeInstance.nativeType),\n ),\n ],\n execute: desc.values.map((value) =>\n step(\n `add value '${value}' to enum \"${typeInstance.nativeType}\"`,\n `ALTER TYPE ${qualifiedType} ADD VALUE '${escapeLiteral(value)}'`,\n ),\n ),\n postcheck: [\n step(\n `verify type \"${typeInstance.nativeType}\" exists`,\n enumTypeExistsCheck(ctx.schemaName, typeInstance.nativeType),\n ),\n ],\n };\n}\n\nfunction resolveDropEnumType(\n desc: DropEnumTypeDescriptor,\n ctx: OperationResolverContext,\n): ResolvedOp {\n const qualified = qualifyName(ctx.schemaName, desc.typeName);\n return {\n id: `type.${desc.typeName}.drop`,\n label: `Drop enum type \"${desc.typeName}\"`,\n operationClass: 'destructive',\n target: targetDetails('type', desc.typeName, ctx.schemaName),\n precheck: [\n step(\n `ensure type \"${desc.typeName}\" exists`,\n enumTypeExistsCheck(ctx.schemaName, desc.typeName),\n ),\n ],\n execute: [step(`drop enum type \"${desc.typeName}\"`, `DROP TYPE ${qualified}`)],\n postcheck: [\n step(\n `verify type \"${desc.typeName}\" removed`,\n enumTypeExistsCheck(ctx.schemaName, desc.typeName, false),\n ),\n ],\n };\n}\n\nfunction resolveRenameType(desc: RenameTypeDescriptor, ctx: OperationResolverContext): ResolvedOp {\n const qualifiedFrom = qualifyName(ctx.schemaName, desc.fromName);\n return {\n id: `type.${desc.fromName}.rename`,\n label: `Rename type \"${desc.fromName}\" to \"${desc.toName}\"`,\n operationClass: 'destructive',\n target: targetDetails('type', desc.fromName, ctx.schemaName),\n precheck: [\n step(\n `ensure type \"${desc.fromName}\" exists`,\n enumTypeExistsCheck(ctx.schemaName, desc.fromName),\n ),\n ],\n execute: [\n step(\n `rename type \"${desc.fromName}\" to \"${desc.toName}\"`,\n `ALTER TYPE ${qualifiedFrom} RENAME TO ${quoteId(desc.toName)}`,\n ),\n ],\n postcheck: [\n step(`verify type \"${desc.toName}\" exists`, enumTypeExistsCheck(ctx.schemaName, desc.toName)),\n ],\n };\n}\n\nfunction resolveCreateDependency(\n desc: CreateDependencyDescriptor,\n ctx: OperationResolverContext,\n): readonly ResolvedOp[] {\n const dep = ctx.dependencies?.find((d) => d.id === desc.dependencyId);\n if (!dep) {\n throw new Error(\n `Dependency \"${desc.dependencyId}\" not found in resolver context. ` +\n 'Ensure frameworkComponents are passed to resolveDescriptors.',\n );\n }\n return dep.install as readonly ResolvedOp[];\n}\n\nconst postgresAdapter = createPostgresAdapter();\n\nfunction lowerToSql(plan: SqlQueryPlan, contract: Contract<SqlStorage>): SerializedQueryPlan {\n const lowered = lowerSqlPlan(postgresAdapter, contract, plan);\n return { sql: lowered.sql, params: lowered.params };\n}\n\nfunction resolveBuildable(input: unknown, contract: Contract<SqlStorage>): SerializedQueryPlan {\n if (\n typeof input === 'object' &&\n input !== null &&\n 'build' in input &&\n typeof (input as { build: unknown }).build === 'function'\n ) {\n return lowerToSql((input as { build(): unknown }).build() as SqlQueryPlan, contract);\n }\n return lowerToSql(input as SqlQueryPlan, contract);\n}\n\n/** Resolves a single QueryPlanInput to one or more lowered SQL statements. */\nfunction resolvePlanInput(\n input: symbol | object | ((...args: never[]) => unknown),\n db: unknown,\n contract: Contract<SqlStorage>,\n): readonly SerializedQueryPlan[] {\n if (typeof input === 'symbol') {\n throw new Error(\n 'Data transform contains an unimplemented TODO placeholder. ' +\n 'Fill in the check/run queries in migration.ts before running verify.',\n );\n }\n if (typeof input === 'function') {\n const result = input(db as never);\n if (Array.isArray(result)) {\n return result.map((item) => resolveBuildable(item, contract));\n }\n return [resolveBuildable(result, contract)];\n }\n return [resolveBuildable(input, contract)];\n}\n\nfunction resolveCheck(\n check: DataTransformDescriptor['check'],\n db: unknown,\n contract: Contract<SqlStorage>,\n): SerializedQueryPlan | boolean | null {\n if (typeof check === 'boolean') return check;\n const resolved = resolvePlanInput(check, db, contract);\n const first = resolved[0];\n if (!first) return null;\n return first;\n}\n\nfunction resolveDataTransform(\n desc: DataTransformDescriptor,\n ctx: OperationResolverContext,\n): DataTransformOperation {\n const { db, toContract } = ctx;\n return {\n id: `data_migration.${desc.name}`,\n label: `Data transform: ${desc.name}`,\n operationClass: 'data',\n name: desc.name,\n source: desc.source,\n check: resolveCheck(desc.check, db, toContract),\n run: desc.run.flatMap((input) => resolvePlanInput(input, db, toContract)),\n };\n}\n\nimport {\n escapeLiteral,\n qualifyName,\n quoteIdentifier as quoteId,\n} from '@prisma-next/adapter-postgres/control';\n\n/**\n * Resolves an array of operation descriptors into SqlMigrationPlanOperation objects.\n * Most descriptors resolve 1:1, but createType and createDependency may expand to multiple ops.\n */\nexport function resolveOperations(\n descriptors: readonly PostgresMigrationOpDescriptor[],\n context: OperationResolverContext,\n): readonly (ResolvedOp | DataTransformOperation)[] {\n return descriptors.flatMap((desc) => resolveOperation(desc, context));\n}\n\nfunction resolveOperation(\n desc: PostgresMigrationOpDescriptor,\n ctx: OperationResolverContext,\n): readonly (ResolvedOp | DataTransformOperation)[] {\n switch (desc.kind) {\n case 'createTable':\n return [resolveCreateTable(desc, ctx)];\n case 'dropTable':\n return [resolveDropTable(desc, ctx)];\n case 'addColumn':\n return [resolveAddColumn(desc, ctx)];\n case 'dropColumn':\n return [resolveDropColumn(desc, ctx)];\n case 'alterColumnType':\n return [resolveAlterColumnType(desc, ctx)];\n case 'setNotNull':\n return [resolveSetNotNull(desc, ctx)];\n case 'dropNotNull':\n return [resolveDropNotNull(desc, ctx)];\n case 'setDefault':\n return [resolveSetDefault(desc, ctx)];\n case 'dropDefault':\n return [resolveDropDefault(desc, ctx)];\n case 'addPrimaryKey':\n return [resolveAddPrimaryKey(desc, ctx)];\n case 'addUnique':\n return [resolveAddUnique(desc, ctx)];\n case 'addForeignKey':\n return [resolveAddForeignKey(desc, ctx)];\n case 'dropConstraint':\n return [resolveDropConstraint(desc, ctx)];\n case 'createIndex':\n return [resolveCreateIndex(desc, ctx)];\n case 'dropIndex':\n return [resolveDropIndex(desc, ctx)];\n case 'createEnumType':\n return [resolveCreateEnumType(desc, ctx)];\n case 'addEnumValues':\n return [resolveAddEnumValues(desc, ctx)];\n case 'dropEnumType':\n return [resolveDropEnumType(desc, ctx)];\n case 'renameType':\n return [resolveRenameType(desc, ctx)];\n case 'createDependency':\n return resolveCreateDependency(desc, ctx);\n case 'dataTransform':\n return [resolveDataTransform(desc, ctx)];\n }\n}\n","import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\n\n/**\n * Resolves the identity value (monoid neutral element) as a SQL literal for a column's type.\n * Checks codec hooks first (extensions can provide type-specific identity values),\n * then falls back to the built-in map.\n */\nexport function resolveIdentityValue(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string | null {\n const referencedType = column.typeRef ? storageTypes[column.typeRef] : undefined;\n const codecId = referencedType?.codecId ?? column.codecId;\n const nativeType = referencedType?.nativeType ?? column.nativeType;\n const typeParams = referencedType?.typeParams ?? column.typeParams;\n\n if (codecId) {\n const hookDefault = codecHooks.get(codecId)?.resolveIdentityValue?.({\n nativeType,\n codecId,\n ...ifDefined('typeParams', typeParams),\n });\n if (hookDefault !== undefined) {\n return hookDefault;\n }\n }\n\n return buildBuiltinIdentityValue(nativeType, typeParams);\n}\n\n/**\n * Returns the built-in identity value (monoid neutral element) as a SQL literal for the given\n * PostgreSQL native type — e.g. 0 for integers, '' for text, false for booleans.\n *\n * This is the planner's fallback when no codec hook provides a type-specific identity value.\n *\n * Returns null for unrecognized types (for example enums and extension-owned types without a\n * hook), which causes the planner to fall back to the empty-table precheck.\n *\n * @internal Exported for testing only.\n */\nexport function buildBuiltinIdentityValue(\n nativeType: string,\n typeParams?: Record<string, unknown>,\n): string | null {\n const normalizedNativeType = normalizeIdentityValueNativeType(nativeType);\n\n if (normalizedNativeType.endsWith('[]')) {\n return \"'{}'\";\n }\n\n switch (normalizedNativeType) {\n case 'text':\n case 'character':\n case 'bpchar':\n case 'character varying':\n case 'varchar':\n return \"''\";\n\n case 'int2':\n case 'int4':\n case 'int8':\n case 'integer':\n case 'bigint':\n case 'smallint':\n case 'float4':\n case 'float8':\n case 'real':\n case 'double precision':\n case 'numeric':\n case 'decimal':\n return '0';\n\n case 'bool':\n case 'boolean':\n return 'false';\n\n case 'uuid':\n return \"'00000000-0000-0000-0000-000000000000'\";\n\n case 'json':\n return \"'{}'::json\";\n case 'jsonb':\n return \"'{}'::jsonb\";\n\n case 'date':\n case 'timestamp':\n case 'timestamptz':\n case 'timestamp with time zone':\n case 'timestamp without time zone':\n return \"'epoch'\";\n\n case 'time':\n case 'time without time zone':\n return \"'00:00:00'\";\n case 'timetz':\n case 'time with time zone':\n return \"'00:00:00+00'\";\n\n case 'interval':\n return \"'0'\";\n\n case 'bytea':\n return \"''::bytea\";\n case 'tsvector':\n return \"''::tsvector\";\n\n case 'bit':\n return buildBitIdentityValue(typeParams);\n case 'bit varying':\n case 'varbit':\n return \"B''\";\n\n default:\n return null;\n }\n}\n\nfunction normalizeIdentityValueNativeType(nativeType: string): string {\n return nativeType.trim().toLowerCase().replace(/\\s+/g, ' ');\n}\n\nfunction buildBitIdentityValue(typeParams?: Record<string, unknown>): string | null {\n const length = typeParams?.['length'];\n if (length === undefined) {\n return \"B'0'\";\n }\n if (typeof length !== 'number' || !Number.isInteger(length) || length <= 0) {\n return null;\n }\n return `B'${'0'.repeat(length)}'`;\n}\n","import { ifDefined } from '@prisma-next/utils/defined';\n\nexport type OperationClass =\n | 'dependency'\n | 'type'\n | 'table'\n | 'column'\n | 'primaryKey'\n | 'unique'\n | 'index'\n | 'foreignKey';\n\nexport interface PostgresPlanTargetDetails {\n readonly schema: string;\n readonly objectType: OperationClass;\n readonly name: string;\n readonly table?: string;\n}\n\nexport interface PlanningMode {\n readonly includeExtraObjects: boolean;\n readonly allowWidening: boolean;\n readonly allowDestructive: boolean;\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","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { CodecControlHooks, SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { buildAddColumnSql } from './planner-ddl-builders';\nimport {\n columnExistsCheck,\n columnHasNoDefaultCheck,\n columnNullabilityCheck,\n qualifyTableName,\n} from './planner-sql-checks';\nimport { buildTargetDetails, type PostgresPlanTargetDetails } from './planner-target-details';\n\nexport function buildAddColumnOperationIdentity(\n schema: string,\n tableName: string,\n columnName: string,\n): Pick<\n SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n 'id' | 'label' | 'summary' | 'target'\n> {\n return {\n id: `column.${tableName}.${columnName}`,\n label: `Add column ${columnName} to ${tableName}`,\n summary: `Adds column ${columnName} to table ${tableName}`,\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schema),\n },\n };\n}\n\nexport function buildAddNotNullColumnWithTemporaryDefaultOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n readonly temporaryDefault: string;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const { schema, tableName, columnName, column, codecHooks, storageTypes, temporaryDefault } =\n options;\n const qualified = qualifyTableName(schema, tableName);\n\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(\n qualified,\n columnName,\n column,\n codecHooks,\n temporaryDefault,\n storageTypes,\n ),\n },\n {\n description: `drop temporary default from column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified} ALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n {\n description: `verify column \"${columnName}\" has no default after temporary default removal`,\n sql: columnHasNoDefaultCheck({ schema, table: tableName, column: columnName }),\n },\n ],\n };\n}\n","import { quoteIdentifier } from '@prisma-next/adapter-postgres/control';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n CodecControlHooks,\n MigrationOperationPolicy,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n SqlStorage,\n StorageColumn,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { invariant } from '@prisma-next/utils/assertions';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { buildColumnDefaultSql, buildColumnTypeSql } from './planner-ddl-builders';\nimport {\n buildExpectedFormatType,\n columnDefaultExistsCheck,\n columnExistsCheck,\n columnNullabilityCheck,\n columnTypeCheck,\n constraintExistsCheck,\n qualifyTableName,\n toRegclassLiteral,\n} from './planner-sql-checks';\nimport {\n buildTargetDetails,\n type PlanningMode,\n type PostgresPlanTargetDetails,\n} from './planner-target-details';\n\n// ============================================================================\n// Public API\n// ============================================================================\n\nexport function buildReconciliationPlan(options: {\n readonly contract: Contract<SqlStorage>;\n readonly issues: readonly SchemaIssue[];\n readonly schemaName: string;\n readonly mode: PlanningMode;\n readonly policy: MigrationOperationPolicy;\n readonly codecHooks: Map<string, CodecControlHooks>;\n}): {\n readonly operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly conflicts: readonly SqlPlannerConflict[];\n} {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n const { mode } = options;\n const seenOperationIds = new Set<string>();\n\n for (const issue of sortSchemaIssues(options.issues)) {\n if (isAdditiveIssue(issue)) {\n continue;\n }\n\n const operation = buildReconciliationOperationFromIssue({\n issue,\n contract: options.contract,\n schemaName: options.schemaName,\n mode,\n codecHooks: options.codecHooks,\n });\n\n if (operation) {\n // Skip duplicates: different schema issues may produce the same operation id\n // (e.g., extra_unique_constraint and extra_index on the same object).\n if (!seenOperationIds.has(operation.id)) {\n seenOperationIds.add(operation.id);\n if (options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n operations.push(operation);\n } else {\n const conflict = convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n } else {\n const conflict = convertIssueToConflict(issue);\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n\n return {\n operations,\n conflicts: conflicts.sort(conflictComparator),\n };\n}\n\n// ============================================================================\n// Issue Classification\n// ============================================================================\n\nfunction isAdditiveIssue(issue: SchemaIssue): boolean {\n switch (issue.kind) {\n case 'type_missing':\n case 'type_values_mismatch':\n case 'enum_values_changed':\n case 'missing_table':\n case 'missing_column':\n case 'dependency_missing':\n return true;\n case 'primary_key_mismatch':\n return issue.actual === undefined;\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n case 'foreign_key_mismatch':\n return issue.indexOrConstraint === undefined;\n default:\n return false;\n }\n}\n\n// ============================================================================\n// Operation Builders\n// ============================================================================\n\nfunction buildReconciliationOperationFromIssue(options: {\n readonly issue: SchemaIssue;\n readonly contract: Contract<SqlStorage>;\n readonly schemaName: string;\n readonly mode: PlanningMode;\n readonly codecHooks: Map<string, CodecControlHooks>;\n}): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const { issue, contract, schemaName, mode, codecHooks } = options;\n const storageTypes = contract.storage.types ?? {};\n switch (issue.kind) {\n case 'extra_table':\n if (!mode.allowDestructive || !issue.table) {\n return null;\n }\n return buildDropTableOperation(schemaName, issue.table);\n\n case 'extra_column':\n if (!mode.allowDestructive || !issue.table || !issue.column) {\n return null;\n }\n return buildDropColumnOperation(schemaName, issue.table, issue.column);\n\n case 'extra_index':\n if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) {\n return null;\n }\n return buildDropIndexOperation(schemaName, issue.table, issue.indexOrConstraint);\n\n case 'extra_foreign_key':\n case 'extra_unique_constraint': {\n if (!mode.allowDestructive || !issue.table || !issue.indexOrConstraint) {\n return null;\n }\n const constraintKind = issue.kind === 'extra_foreign_key' ? 'foreignKey' : 'unique';\n return buildDropConstraintOperation(\n schemaName,\n issue.table,\n issue.indexOrConstraint,\n constraintKind,\n );\n }\n\n case 'extra_primary_key': {\n if (!mode.allowDestructive || !issue.table) {\n return null;\n }\n const constraintName = issue.indexOrConstraint ?? `${issue.table}_pkey`;\n return buildDropConstraintOperation(schemaName, issue.table, constraintName, 'primaryKey');\n }\n\n case 'nullability_mismatch': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (issue.expected === 'true') {\n // Contract wants nullable, DB has NOT NULL → widening\n return mode.allowWidening\n ? buildDropNotNullOperation(schemaName, issue.table, issue.column)\n : null;\n }\n // Contract wants NOT NULL, DB has nullable → destructive\n return mode.allowDestructive\n ? buildSetNotNullOperation(schemaName, issue.table, issue.column)\n : null;\n }\n\n case 'type_mismatch': {\n if (!mode.allowDestructive || !issue.table || !issue.column) {\n return null;\n }\n const contractColumn = getContractColumn(contract, issue.table, issue.column);\n if (!contractColumn) {\n return null;\n }\n return buildAlterColumnTypeOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColumn,\n codecHooks,\n storageTypes,\n );\n }\n\n case 'default_missing': {\n if (!issue.table || !issue.column) {\n return null;\n }\n const contractColMissing = getContractColumn(contract, issue.table, issue.column);\n if (!contractColMissing) {\n return null;\n }\n // NOTE: Being in the `default_missing` case means the verifier found the contract expects a default, so it should exist here. We must still narrow.\n invariant(\n contractColMissing.default !== undefined,\n `default_missing issue for \"${issue.table}\".\"${issue.column}\" but contract column has no default`,\n );\n return buildDefaultOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColMissing,\n contractColMissing.default,\n 'additive',\n 'Set',\n );\n }\n\n case 'default_mismatch': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (!mode.allowWidening) {\n return null;\n }\n const contractColMismatch = getContractColumn(contract, issue.table, issue.column);\n if (!contractColMismatch) {\n return null;\n }\n // NOTE: Being in the `default_mismatch` case means the verifier found the contract expects a different default, so it should exist here. We must still narrow.\n invariant(\n contractColMismatch.default !== undefined,\n `default_mismatch issue for \"${issue.table}\".\"${issue.column}\" but contract column has no default`,\n );\n return buildDefaultOperation(\n schemaName,\n issue.table,\n issue.column,\n contractColMismatch,\n contractColMismatch.default,\n 'widening',\n 'Change',\n );\n }\n\n case 'extra_default': {\n if (!issue.table || !issue.column) {\n return null;\n }\n if (!mode.allowDestructive) {\n return null;\n }\n return buildDropDefaultOperation(schemaName, issue.table, issue.column);\n }\n\n // Remaining issue kinds (primary_key_mismatch, unique_constraint_mismatch,\n // index_mismatch, foreign_key_mismatch) do not yet have reconciliation operation\n // builders. They fall through to the caller, which converts them to conflicts via\n // convertIssueToConflict. When a new SchemaIssue kind is added, add a case here if\n // the planner can emit an operation for it; otherwise it becomes a conflict.\n default:\n return null;\n }\n}\n\nfunction getContractColumn(\n contract: Contract<SqlStorage>,\n tableName: string,\n columnName: string,\n): StorageColumn | null {\n const table = contract.storage.tables[tableName];\n if (!table) {\n return null;\n }\n return table.columns[columnName] ?? null;\n}\n\nfunction buildDropTableOperation(\n schemaName: string,\n tableName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropTable.${tableName}`,\n label: `Drop table ${tableName}`,\n summary: `Drops extra table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n execute: [\n {\n description: `drop table \"${tableName}\"`,\n sql: `DROP TABLE ${qualifyTableName(schemaName, tableName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" is removed`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n };\n}\n\nfunction buildDropColumnOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropColumn.${tableName}.${columnName}`,\n label: `Drop column ${columnName} from ${tableName}`,\n summary: `Drops extra column ${columnName} from table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop column \"${columnName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)} DROP COLUMN ${quoteIdentifier(columnName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" is removed`,\n sql: columnExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: false,\n }),\n },\n ],\n };\n}\n\nfunction buildDropIndexOperation(\n schemaName: string,\n tableName: string,\n indexName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropIndex.${tableName}.${indexName}`,\n label: `Drop index ${indexName} on ${tableName}`,\n summary: `Drops extra index ${indexName} on table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n execute: [\n {\n description: `drop index \"${indexName}\"`,\n sql: `DROP INDEX ${qualifyTableName(schemaName, indexName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" is removed`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n };\n}\n\nfunction buildDropConstraintOperation(\n schemaName: string,\n tableName: string,\n constraintName: string,\n constraintKind: 'foreignKey' | 'unique' | 'primaryKey',\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `dropConstraint.${tableName}.${constraintName}`,\n label: `Drop constraint ${constraintName} on ${tableName}`,\n summary: `Drops extra constraint ${constraintName} on table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails(constraintKind, constraintName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName, table: tableName }),\n },\n ],\n execute: [\n {\n description: `drop constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nDROP CONSTRAINT ${quoteIdentifier(constraintName)}`,\n },\n ],\n postcheck: [\n {\n description: `verify constraint \"${constraintName}\" is removed`,\n sql: constraintExistsCheck({\n constraintName,\n schema: schemaName,\n table: tableName,\n exists: false,\n }),\n },\n ],\n };\n}\n\nfunction buildDropNotNullOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n return {\n id: `alterNullability.${tableName}.${columnName}`,\n label: `Relax nullability for ${columnName} on ${tableName}`,\n summary: `Drops NOT NULL constraint for ${columnName} on table ${tableName}`,\n operationClass: 'widening',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop NOT NULL from \"${columnName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nALTER COLUMN ${quoteIdentifier(columnName)} DROP NOT NULL`,\n },\n ],\n postcheck: [\n {\n description: `verify \"${columnName}\" is nullable`,\n sql: columnNullabilityCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: true,\n }),\n },\n ],\n };\n}\n\nfunction buildSetNotNullOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n return {\n id: `alterNullability.${tableName}.${columnName}`,\n label: `Enforce NOT NULL for ${columnName} on ${tableName}`,\n summary: `Sets NOT NULL on ${columnName} for table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n {\n description: `ensure \"${columnName}\" has no NULL values`,\n sql: `SELECT NOT EXISTS (\n SELECT 1 FROM ${qualified}\n WHERE ${quoteIdentifier(columnName)} IS NULL\n LIMIT 1\n)`,\n },\n ],\n execute: [\n {\n description: `set NOT NULL on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\nALTER COLUMN ${quoteIdentifier(columnName)} SET NOT NULL`,\n },\n ],\n postcheck: [\n {\n description: `verify \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ],\n };\n}\n\nfunction buildAlterColumnTypeOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance>,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n const expectedType = buildColumnTypeSql(column, codecHooks, storageTypes, false);\n return {\n id: `alterType.${tableName}.${columnName}`,\n label: `Alter type for ${columnName} on ${tableName}`,\n summary: `Changes type of ${columnName} to ${expectedType}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n meta: {\n warning: 'TABLE_REWRITE',\n detail:\n 'ALTER COLUMN TYPE requires a full table rewrite and acquires an ACCESS EXCLUSIVE lock. On large tables, this can cause significant downtime.',\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `alter type of \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\nALTER COLUMN ${quoteIdentifier(columnName)}\nTYPE ${expectedType}\nUSING ${quoteIdentifier(columnName)}::${expectedType}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has type ${expectedType}`,\n sql: columnTypeCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n expectedType: buildExpectedFormatType(column, codecHooks, storageTypes),\n }),\n },\n ],\n };\n}\n\nfunction buildDefaultOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n column: Omit<StorageColumn, 'default'>,\n columnDefault: NonNullable<StorageColumn['default']>,\n operationClass: 'additive' | 'widening',\n verb: 'Set' | 'Change',\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> | null {\n const qualified = qualifyTableName(schemaName, tableName);\n const defaultClause = buildColumnDefaultSql(columnDefault, column);\n // autoincrement defaults are handled by SERIAL types — buildColumnDefaultSql returns ''\n // for them. Until the IR is enriched to distinguish autoincrement (TML-2107), skip.\n if (!defaultClause) return null;\n const verbLower = verb.toLowerCase();\n return {\n id: `setDefault.${tableName}.${columnName}`,\n label: `${verb} default for ${columnName} on ${tableName}`,\n summary: `${verb}s default on column ${columnName} of table ${tableName}`,\n operationClass,\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `${verbLower} default on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\\nALTER COLUMN ${quoteIdentifier(columnName)} SET ${defaultClause}`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has a default`,\n sql: columnDefaultExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: true,\n }),\n },\n ],\n };\n}\n\nfunction buildDropDefaultOperation(\n schemaName: string,\n tableName: string,\n columnName: string,\n): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const qualified = qualifyTableName(schemaName, tableName);\n return {\n id: `dropDefault.${tableName}.${columnName}`,\n label: `Drop default for ${columnName} on ${tableName}`,\n summary: `Drops default on column ${columnName} of table ${tableName}`,\n operationClass: 'destructive',\n target: {\n id: 'postgres',\n details: buildTargetDetails('column', columnName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema: schemaName, table: tableName, column: columnName }),\n },\n ],\n execute: [\n {\n description: `drop default on \"${columnName}\"`,\n sql: `ALTER TABLE ${qualified}\\nALTER COLUMN ${quoteIdentifier(columnName)} DROP DEFAULT`,\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" has no default`,\n sql: columnDefaultExistsCheck({\n schema: schemaName,\n table: tableName,\n column: columnName,\n exists: false,\n }),\n },\n ],\n };\n}\n\n// ============================================================================\n// Conflict Conversion\n// ============================================================================\n\nfunction convertIssueToConflict(issue: SchemaIssue): SqlPlannerConflict | null {\n switch (issue.kind) {\n case 'type_mismatch':\n return buildConflict('typeMismatch', issue);\n case 'nullability_mismatch':\n return buildConflict('nullabilityConflict', issue);\n case 'default_missing':\n case 'default_mismatch':\n case 'extra_default':\n case 'extra_table':\n case 'extra_column':\n case 'extra_primary_key':\n case 'extra_foreign_key':\n case 'extra_unique_constraint':\n case 'extra_index':\n return buildConflict('missingButNonAdditive', issue);\n case 'primary_key_mismatch':\n case 'unique_constraint_mismatch':\n case 'index_mismatch':\n return buildConflict('indexIncompatible', issue);\n case 'foreign_key_mismatch':\n return buildConflict('foreignKeyConflict', issue);\n // Additive issue kinds (missing_table, missing_column, type_missing, type_values_mismatch,\n // dependency_missing) are filtered by isAdditiveIssue before reaching this method.\n // If a new SchemaIssue kind is introduced, add a mapping here so it becomes a conflict\n // rather than being silently ignored.\n default:\n return null;\n }\n}\n\nfunction buildConflict(kind: SqlPlannerConflict['kind'], issue: SchemaIssue): SqlPlannerConflict {\n const location = buildConflictLocation(issue);\n const base = issue.kind !== 'enum_values_changed' ? issue : undefined;\n const meta =\n base?.expected || base?.actual\n ? Object.freeze({\n ...ifDefined('expected', base.expected),\n ...ifDefined('actual', base.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 aBase = a.kind !== 'enum_values_changed' ? a : undefined;\n const bBase = b.kind !== 'enum_values_changed' ? b : undefined;\n const tableCompare = compareStrings(aBase?.table, bBase?.table);\n if (tableCompare !== 0) {\n return tableCompare;\n }\n const columnCompare = compareStrings(aBase?.column, bBase?.column);\n if (columnCompare !== 0) {\n return columnCompare;\n }\n return compareStrings(aBase?.indexOrConstraint, bBase?.indexOrConstraint);\n });\n}\n\nfunction buildConflictLocation(issue: SchemaIssue) {\n if (issue.kind === 'enum_values_changed') {\n return { type: issue.typeName };\n }\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 type { ForeignKey } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\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 */\nexport interface SchemaTableLookup {\n readonly uniqueKeys: Set<string>;\n readonly indexKeys: Set<string>;\n readonly uniqueIndexKeys: Set<string>;\n readonly fkKeys: Set<string>;\n}\n\nexport function 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\nexport function hasUniqueConstraint(\n lookup: SchemaTableLookup,\n columns: readonly string[],\n): boolean {\n const key = columns.join(',');\n return lookup.uniqueKeys.has(key) || lookup.uniqueIndexKeys.has(key);\n}\n\nexport function hasIndex(lookup: SchemaTableLookup, columns: readonly string[]): boolean {\n const key = columns.join(',');\n return lookup.indexKeys.has(key) || lookup.uniqueKeys.has(key);\n}\n\nexport function hasForeignKey(lookup: SchemaTableLookup, fk: ForeignKey): boolean {\n return lookup.fkKeys.has(\n `${fk.columns.join(',')}|${fk.references.table}|${fk.references.columns.join(',')}`,\n );\n}\n","import {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n quoteIdentifier,\n} from '@prisma-next/adapter-postgres/control';\nimport type {\n CodecControlHooks,\n ComponentDatabaseDependency,\n MigrationOperationPolicy,\n SqlMigrationPlanner,\n SqlMigrationPlannerPlanOptions,\n SqlMigrationPlanOperation,\n SqlPlannerConflict,\n} from '@prisma-next/family-sql/control';\nimport {\n collectInitDependencies,\n createMigrationPlan,\n extractCodecControlHooks,\n plannerFailure,\n plannerSuccess,\n} from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport type {\n StorageColumn,\n StorageTable,\n StorageTypeInstance,\n} from '@prisma-next/sql-contract/types';\nimport { defaultIndexName } from '@prisma-next/sql-schema-ir/naming';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { buildAddColumnSql, buildCreateTableSql, buildForeignKeySql } from './planner-ddl-builders';\nimport { resolveIdentityValue } from './planner-identity-values';\nimport {\n buildAddColumnOperationIdentity,\n buildAddNotNullColumnWithTemporaryDefaultOperation,\n} from './planner-recipes';\nimport { buildReconciliationPlan } from './planner-reconciliation';\nimport {\n buildSchemaLookupMap,\n hasForeignKey,\n hasIndex,\n hasUniqueConstraint,\n type SchemaTableLookup,\n} from './planner-schema-lookup';\nimport {\n columnExistsCheck,\n columnNullabilityCheck,\n constraintExistsCheck,\n qualifyTableName,\n tableHasPrimaryKeyCheck,\n tableIsEmptyCheck,\n toRegclassLiteral,\n} from './planner-sql-checks';\nimport {\n buildTargetDetails,\n type OperationClass,\n type PlanningMode,\n type PostgresPlanTargetDetails,\n} from './planner-target-details';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype PlannerDatabaseDependency = {\n readonly id: string;\n readonly label: string;\n readonly install: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n};\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): SqlMigrationPlanner<PostgresPlanTargetDetails> {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\nclass PostgresMigrationPlanner implements SqlMigrationPlanner<PostgresPlanTargetDetails> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: SqlMigrationPlannerPlanOptions) {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const 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 const storageTypes = options.contract.storage.types ?? {};\n\n const reconciliationPlan = buildReconciliationPlan({\n contract: options.contract,\n issues: schemaIssues,\n schemaName,\n mode: planningMode,\n policy: options.policy,\n codecHooks,\n });\n if (reconciliationPlan.conflicts.length > 0) {\n return plannerFailure(reconciliationPlan.conflicts);\n }\n\n const storageTypePlan = this.buildStorageTypeOperations(options, schemaName, codecHooks);\n if (storageTypePlan.conflicts.length > 0) {\n return plannerFailure(storageTypePlan.conflicts);\n }\n\n // Sort table entries once for reuse across all additive operation builders.\n const sortedTables = sortedEntries(options.contract.storage.tables);\n\n // Pre-compute constraint lookups once per schema table for O(1) checks across all builders.\n const schemaLookups = buildSchemaLookupMap(options.schema);\n\n // Build extension operations from component-owned database dependencies\n operations.push(\n ...this.buildDatabaseDependencyOperations(options),\n ...storageTypePlan.operations,\n ...reconciliationPlan.operations,\n ...this.buildTableOperations(\n sortedTables,\n options.schema,\n schemaName,\n codecHooks,\n storageTypes,\n ),\n ...this.buildColumnOperations(\n sortedTables,\n options.schema,\n schemaLookups,\n schemaName,\n codecHooks,\n storageTypes,\n ),\n ...this.buildPrimaryKeyOperations(sortedTables, options.schema, schemaName),\n ...this.buildUniqueOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildIndexOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildFkBackingIndexOperations(sortedTables, schemaLookups, schemaName),\n ...this.buildForeignKeyOperations(sortedTables, schemaLookups, schemaName),\n );\n\n const plan = createMigrationPlan<PostgresPlanTargetDetails>({\n targetId: 'postgres',\n origin: null,\n destination: {\n storageHash: options.contract.storage.storageHash,\n ...ifDefined('profileHash', options.contract.profileHash),\n },\n operations,\n });\n\n return plannerSuccess(plan);\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n /**\n * Builds migration operations from component-owned database dependencies.\n * These operations install database-side persistence structures declared by components.\n */\n private buildDatabaseDependencyOperations(\n options: PlannerOptionsWithComponents,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const dependencies = this.collectDependencies(options);\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const seenDependencyIds = new Set<string>();\n const seenOperationIds = new Set<string>();\n\n const installedIds = new Set(options.schema.dependencies.map((d) => d.id));\n\n for (const dependency of dependencies) {\n if (seenDependencyIds.has(dependency.id)) {\n continue;\n }\n seenDependencyIds.add(dependency.id);\n\n if (installedIds.has(dependency.id)) {\n continue;\n }\n\n for (const installOp of dependency.install) {\n if (seenOperationIds.has(installOp.id)) {\n continue;\n }\n seenOperationIds.add(installOp.id);\n operations.push(installOp as SqlMigrationPlanOperation<PostgresPlanTargetDetails>);\n }\n }\n\n return operations;\n }\n\n private buildStorageTypeOperations(\n options: PlannerOptionsWithComponents,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n ): {\n readonly operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n readonly conflicts: readonly SqlPlannerConflict[];\n } {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n const conflicts: SqlPlannerConflict[] = [];\n const storageTypes = options.contract.storage.types ?? {};\n\n for (const [typeName, typeInstance] of sortedEntries(storageTypes)) {\n const hook = codecHooks.get(typeInstance.codecId);\n const planResult = hook?.planTypeOperations?.({\n typeName,\n typeInstance,\n contract: options.contract,\n schema: options.schema,\n schemaName,\n policy: options.policy,\n });\n if (!planResult) {\n continue;\n }\n for (const operation of planResult.operations) {\n if (!options.policy.allowedOperationClasses.includes(operation.operationClass)) {\n conflicts.push({\n kind: 'missingButNonAdditive',\n summary: `Storage type \"${typeName}\" requires \"${operation.operationClass}\" operation \"${operation.id}\"`,\n location: {\n type: typeName,\n },\n });\n continue;\n }\n operations.push({\n ...operation,\n target: {\n id: operation.target.id,\n details: this.buildTargetDetails('type', typeName, schemaName),\n },\n });\n }\n }\n\n return { operations, conflicts };\n }\n private collectDependencies(\n options: PlannerOptionsWithComponents,\n ): ReadonlyArray<PlannerDatabaseDependency> {\n const dependencies = collectInitDependencies(options.frameworkComponents);\n return sortDependencies(dependencies.filter(isPostgresPlannerDependency));\n }\n\n private buildTableOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance>,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n if (schema.tables[tableName]) {\n continue;\n }\n const qualified = qualifyTableName(schemaName, tableName);\n operations.push({\n id: `table.${tableName}`,\n label: `Create table ${tableName}`,\n summary: `Creates table ${tableName} with required columns`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure table \"${tableName}\" does not exist`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create table \"${tableName}\"`,\n sql: buildCreateTableSql(qualified, table, codecHooks, storageTypes),\n },\n ],\n postcheck: [\n {\n description: `verify table \"${tableName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, tableName)}) IS NOT NULL`,\n },\n ],\n });\n }\n return operations;\n }\n\n private buildColumnOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance>,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const schemaTable = schema.tables[tableName];\n if (!schemaTable) {\n continue;\n }\n const schemaLookup = schemaLookups.get(tableName);\n for (const [columnName, column] of sortedEntries(table.columns)) {\n if (schemaTable.columns[columnName]) {\n continue;\n }\n operations.push(\n this.buildAddColumnOperation({\n schema: schemaName,\n tableName,\n table,\n schemaTable,\n schemaLookup,\n columnName,\n column,\n codecHooks,\n storageTypes,\n }),\n );\n }\n }\n return operations;\n }\n\n private buildAddColumnOperation(options: {\n readonly schema: string;\n readonly tableName: string;\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: SchemaTableLookup | undefined;\n readonly columnName: string;\n readonly column: StorageColumn;\n readonly codecHooks: Map<string, CodecControlHooks>;\n readonly storageTypes: Record<string, StorageTypeInstance>;\n }): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n const {\n schema,\n tableName,\n table,\n schemaTable,\n schemaLookup,\n columnName,\n column,\n codecHooks,\n storageTypes,\n } = options;\n const notNull = !column.nullable;\n const hasDefault = column.default !== undefined;\n // Planner logic decides whether this column needs the coordinated multi-step\n // strategy. The strategy recipe itself is built by a dedicated helper.\n const needsTemporaryDefault = notNull && !hasDefault;\n const temporaryDefault = needsTemporaryDefault\n ? resolveIdentityValue(column, codecHooks, storageTypes)\n : null;\n const canUseSharedTemporaryDefault =\n needsTemporaryDefault &&\n temporaryDefault !== null &&\n canUseSharedTemporaryDefaultStrategy({\n table,\n schemaTable,\n schemaLookup,\n columnName,\n });\n\n if (canUseSharedTemporaryDefault) {\n return buildAddNotNullColumnWithTemporaryDefaultOperation({\n schema,\n tableName,\n columnName,\n column,\n codecHooks,\n storageTypes,\n temporaryDefault,\n });\n }\n\n const qualified = qualifyTableName(schema, tableName);\n const requiresEmptyTableCheck = needsTemporaryDefault && !canUseSharedTemporaryDefault;\n return {\n ...buildAddColumnOperationIdentity(schema, tableName, columnName),\n operationClass: 'additive',\n precheck: [\n {\n description: `ensure column \"${columnName}\" is missing`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName, exists: false }),\n },\n ...(requiresEmptyTableCheck\n ? [\n {\n description: `ensure table \"${tableName}\" is empty before adding NOT NULL column without default`,\n sql: tableIsEmptyCheck(qualified),\n },\n ]\n : []),\n ],\n execute: [\n {\n description: `add column \"${columnName}\"`,\n sql: buildAddColumnSql(\n qualified,\n columnName,\n column,\n codecHooks,\n undefined,\n storageTypes,\n ),\n },\n ],\n postcheck: [\n {\n description: `verify column \"${columnName}\" exists`,\n sql: columnExistsCheck({ schema, table: tableName, column: columnName }),\n },\n ...(notNull\n ? [\n {\n description: `verify column \"${columnName}\" is NOT NULL`,\n sql: columnNullabilityCheck({\n schema,\n table: tableName,\n column: columnName,\n nullable: false,\n }),\n },\n ]\n : []),\n ],\n };\n }\n\n private buildPrimaryKeyOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schema: SqlSchemaIR,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n if (!table.primaryKey) {\n continue;\n }\n const schemaTable = schema.tables[tableName];\n if (!schemaTable || schemaTable.primaryKey) {\n continue;\n }\n const constraintName = table.primaryKey.name ?? `${tableName}_pkey`;\n operations.push({\n id: `primaryKey.${tableName}.${constraintName}`,\n label: `Add primary key ${constraintName} on ${tableName}`,\n summary: `Adds primary key ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('table', tableName, schemaName),\n },\n precheck: [\n {\n description: `ensure primary key does not exist on \"${tableName}\"`,\n sql: tableHasPrimaryKeyCheck(schemaName, tableName, false),\n },\n ],\n execute: [\n {\n description: `add primary key \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nPRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify primary key \"${constraintName}\" exists`,\n sql: tableHasPrimaryKeyCheck(schemaName, tableName, true, constraintName),\n },\n ],\n });\n }\n return operations;\n }\n\n private buildUniqueOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const unique of table.uniques) {\n if (lookup && hasUniqueConstraint(lookup, unique.columns)) {\n continue;\n }\n const constraintName = unique.name ?? `${tableName}_${unique.columns.join('_')}_key`;\n operations.push({\n id: `unique.${tableName}.${constraintName}`,\n label: `Add unique constraint ${constraintName} on ${tableName}`,\n summary: `Adds unique constraint ${constraintName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('unique', constraintName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure unique constraint \"${constraintName}\" is missing`,\n sql: constraintExistsCheck({\n constraintName,\n schema: schemaName,\n table: tableName,\n exists: false,\n }),\n },\n ],\n execute: [\n {\n description: `add unique constraint \"${constraintName}\"`,\n sql: `ALTER TABLE ${qualifyTableName(schemaName, tableName)}\nADD CONSTRAINT ${quoteIdentifier(constraintName)}\nUNIQUE (${unique.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify unique constraint \"${constraintName}\" exists`,\n sql: constraintExistsCheck({ constraintName, schema: schemaName, table: tableName }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildIndexOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const index of table.indexes) {\n if (lookup && hasIndex(lookup, index.columns)) {\n continue;\n }\n const indexName = index.name ?? defaultIndexName(tableName, index.columns);\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create index ${indexName} on ${tableName}`,\n summary: `Creates index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${index.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n /**\n * Generates FK-backing index operations for FKs with `index: true`,\n * but only when no matching user-declared index exists in `contractTable.indexes`.\n */\n private buildFkBackingIndexOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n // Collect column sets of user-declared indexes to avoid duplicates\n const declaredIndexColumns = new Set(table.indexes.map((idx) => idx.columns.join(',')));\n\n for (const fk of table.foreignKeys) {\n if (fk.index === false) continue;\n // Skip if user already declared an index with these columns\n if (declaredIndexColumns.has(fk.columns.join(','))) continue;\n // Skip if the index already exists in the database\n if (lookup && hasIndex(lookup, fk.columns)) continue;\n\n const indexName = defaultIndexName(tableName, fk.columns);\n operations.push({\n id: `index.${tableName}.${indexName}`,\n label: `Create FK-backing index ${indexName} on ${tableName}`,\n summary: `Creates FK-backing index ${indexName} on ${tableName}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('index', indexName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure index \"${indexName}\" is missing`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NULL`,\n },\n ],\n execute: [\n {\n description: `create FK-backing index \"${indexName}\"`,\n sql: `CREATE INDEX ${quoteIdentifier(indexName)} ON ${qualifyTableName(\n schemaName,\n tableName,\n )} (${fk.columns.map(quoteIdentifier).join(', ')})`,\n },\n ],\n postcheck: [\n {\n description: `verify index \"${indexName}\" exists`,\n sql: `SELECT to_regclass(${toRegclassLiteral(schemaName, indexName)}) IS NOT NULL`,\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildForeignKeyOperations(\n tables: ReadonlyArray<[string, StorageTable]>,\n schemaLookups: ReadonlyMap<string, SchemaTableLookup>,\n schemaName: string,\n ): readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] {\n const operations: SqlMigrationPlanOperation<PostgresPlanTargetDetails>[] = [];\n for (const [tableName, table] of tables) {\n const lookup = schemaLookups.get(tableName);\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false) continue;\n if (lookup && hasForeignKey(lookup, foreignKey)) {\n continue;\n }\n const fkName = foreignKey.name ?? `${tableName}_${foreignKey.columns.join('_')}_fkey`;\n operations.push({\n id: `foreignKey.${tableName}.${fkName}`,\n label: `Add foreign key ${fkName} on ${tableName}`,\n summary: `Adds foreign key ${fkName} referencing ${foreignKey.references.table}`,\n operationClass: 'additive',\n target: {\n id: 'postgres',\n details: this.buildTargetDetails('foreignKey', fkName, schemaName, tableName),\n },\n precheck: [\n {\n description: `ensure foreign key \"${fkName}\" is missing`,\n sql: constraintExistsCheck({\n constraintName: fkName,\n schema: schemaName,\n table: tableName,\n exists: false,\n }),\n },\n ],\n execute: [\n {\n description: `add foreign key \"${fkName}\"`,\n sql: buildForeignKeySql(schemaName, tableName, fkName, foreignKey),\n },\n ],\n postcheck: [\n {\n description: `verify foreign key \"${fkName}\" exists`,\n sql: constraintExistsCheck({\n constraintName: fkName,\n schema: schemaName,\n table: tableName,\n }),\n },\n ],\n });\n }\n }\n return operations;\n }\n\n private buildTargetDetails(\n objectType: OperationClass,\n name: string,\n schema: string,\n table?: string,\n ): PostgresPlanTargetDetails {\n return buildTargetDetails(objectType, name, schema, table);\n }\n\n private resolvePlanningMode(policy: MigrationOperationPolicy): PlanningMode {\n const allowWidening = policy.allowedOperationClasses.includes('widening');\n const allowDestructive = policy.allowedOperationClasses.includes('destructive');\n // `db init` uses additive-only policy and intentionally ignores extras.\n // Any reconciliation-capable policy should inspect extras to reconcile strict equality.\n const includeExtraObjects = allowWidening || allowDestructive;\n return { includeExtraObjects, allowWidening, allowDestructive };\n }\n\n private collectSchemaIssues(\n options: PlannerOptionsWithComponents,\n strict: boolean,\n ): readonly SchemaIssue[] {\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n\nfunction canUseSharedTemporaryDefaultStrategy(options: {\n readonly table: StorageTable;\n readonly schemaTable: SqlSchemaIR['tables'][string];\n readonly schemaLookup: SchemaTableLookup | undefined;\n readonly columnName: string;\n}): boolean {\n const { table, schemaTable, schemaLookup, columnName } = options;\n\n // Shared placeholders are only safe when later plan steps do not require\n // row-specific values for this newly added column.\n if (table.primaryKey?.columns.includes(columnName) && !schemaTable.primaryKey) {\n return false;\n }\n\n for (const unique of table.uniques) {\n if (!unique.columns.includes(columnName)) {\n continue;\n }\n if (!schemaLookup || !hasUniqueConstraint(schemaLookup, unique.columns)) {\n return false;\n }\n }\n\n for (const foreignKey of table.foreignKeys) {\n if (foreignKey.constraint === false || !foreignKey.columns.includes(columnName)) {\n continue;\n }\n if (!schemaLookup || !hasForeignKey(schemaLookup, foreignKey)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction sortDependencies(\n dependencies: ReadonlyArray<PlannerDatabaseDependency>,\n): ReadonlyArray<PlannerDatabaseDependency> {\n return [...dependencies].sort((a, b) => a.id.localeCompare(b.id));\n}\n\nfunction isPostgresPlannerDependency(\n dependency: ComponentDatabaseDependency<unknown>,\n): dependency is PlannerDatabaseDependency {\n return dependency.install.every((operation) => operation.target.id === 'postgres');\n}\n\nfunction sortedEntries<V>(record: Readonly<Record<string, V>>): Array<[string, V]> {\n return Object.entries(record).sort(([a], [b]) => a.localeCompare(b)) as Array<[string, V]>;\n}\n","export 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);\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 type { DataTransformOperation } from '@prisma-next/framework-components/control';\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-target-details';\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\nfunction isDataTransformOperation(op: unknown): op is DataTransformOperation {\n return (\n typeof op === 'object' &&\n op !== null &&\n 'operationClass' in op &&\n (op as { operationClass: string }).operationClass === 'data' &&\n 'name' in op &&\n 'check' in op &&\n 'run' in op\n );\n}\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await readMarker(driver);\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // db update (origin: null) always applies; migration-apply (origin set) skips if marker matches.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const skipOperations = markerAtDestination && options.plan.origin != null;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contract: 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 // Data transform operations have a different execution lifecycle\n if (operation.operationClass === 'data' && isDataTransformOperation(operation)) {\n const dtResult = await this.executeDataTransform(driver, operation, {\n runIdempotency,\n });\n if (!dtResult.ok) {\n return dtResult;\n }\n executedOperations.push(operation);\n operationsExecuted += 1;\n continue;\n }\n\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 /**\n * Executes a data transform operation with the check → (skip or run) → check lifecycle.\n *\n * 1. If check is a query AST: render to SQL, execute. Empty result = already applied (skip).\n * 2. If check is `true`: always skip. If `false`: always run.\n * 3. Execute run ASTs (rendered to SQL) sequentially.\n * 4. Re-execute check as post-run validation. If violations remain, fail.\n */\n private async executeDataTransform(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n op: DataTransformOperation,\n options: { runIdempotency: boolean },\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n // Step 1: Check (skip guard)\n if (op.check === true) {\n // Always skip, regardless of idempotency setting\n return okVoid();\n }\n if (options.runIdempotency && op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length === 0) {\n // No violations — already applied, skip\n return okVoid();\n }\n }\n\n // Step 2: Execute run steps\n if (op.run) {\n for (const plan of op.run) {\n try {\n await driver.query(plan.sql, plan.params);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Data transform \"${op.name}\" failed: ${error.message}`,\n {\n why: error.message,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n sql: plan.sql,\n sqlState: error.sqlState,\n },\n },\n );\n }\n throw error;\n }\n }\n }\n\n // Step 3: Post-run validation (check again)\n if (op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length > 0) {\n return runnerFailure(\n 'POSTCHECK_FAILED',\n `Data transform \"${op.name}\" did not resolve all violations (${checkResult.rows.length} remaining)`,\n {\n why: `After executing the data transform, the check query still returns ${checkResult.rows.length} violation(s).`,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n remainingViolations: checkResult.rows.length,\n },\n },\n );\n }\n }\n\n return okVoid();\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.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.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 {\n normalizeSchemaNativeType,\n parsePostgresDefault,\n} from '@prisma-next/adapter-postgres/control';\nimport type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport {\n collectInitDependencies,\n contractToSchemaIR,\n extractCodecControlHooks,\n} from '@prisma-next/family-sql/control';\nimport { MigrationDescriptorArraySchema } from '@prisma-next/family-sql/operation-descriptors';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationPlanner,\n MigrationRunner,\n OperationDescriptor,\n} from '@prisma-next/framework-components/control';\nimport { sql } from '@prisma-next/sql-builder/runtime';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport type { SqlOperationEntry } from '@prisma-next/sql-operations';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type } from 'arktype';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { planDescriptors } from '../core/migrations/descriptor-planner';\nimport { resolveOperations } from '../core/migrations/operation-resolver';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction parseDescriptors(descriptors: readonly OperationDescriptor[]) {\n const result = MigrationDescriptorArraySchema([...descriptors]);\n if (result instanceof type.errors) {\n throw new Error(`Invalid migration descriptors:\\n${result.summary}`);\n }\n return result;\n}\n\nfunction collectQueryOperationTypes(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n): Readonly<Record<string, SqlOperationEntry>> {\n const entries: Record<string, SqlOperationEntry> = {};\n if (!frameworkComponents) return entries;\n for (const component of frameworkComponents) {\n const ops = (\n component as {\n queryOperations?: () => ReadonlyArray<{ method: string } & SqlOperationEntry>;\n }\n ).queryOperations?.();\n if (!ops) continue;\n for (const { method, ...entry } of ops) {\n entries[method] = entry;\n }\n }\n return entries;\n}\n\n/**\n * Creates a SQL DSL client for migration authoring.\n * Only the fields used by the builder are populated — operations, codecs,\n * and types are unused by sql() and stubbed to satisfy the ExecutionContext type.\n */\nfunction createMigrationClient(\n toContract: Contract<SqlStorage>,\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n const queryOperationTypes = collectQueryOperationTypes(frameworkComponents);\n // sql() only reads contract, queryOperations.entries(), and applyMutationDefaults\n // from the context. The other fields are for runtime execution, not query building.\n return sql({\n context: {\n contract: toContract,\n queryOperations: { entries: () => queryOperationTypes },\n applyMutationDefaults: () => [],\n } as never,\n });\n}\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n\n if (!input.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${input.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) {\n throw new Error(\n `Column declares typeParams for nativeType \"${input.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${input.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner() as MigrationPlanner<'sql', 'postgres'>;\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n planWithDescriptors(context) {\n const toContract = context.toContract as Contract<SqlStorage>;\n const fromContract = context.fromContract as Contract<SqlStorage> | null;\n\n // Synthesize schema IR from the fromContract (same as contractToSchema flow)\n const expander = buildNativeTypeExpander(context.frameworkComponents);\n const fromSchemaIR = contractToSchemaIR(fromContract, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: context.frameworkComponents ?? [],\n });\n\n // Collect schema issues via verifier\n const verifyResult = verifySqlSchema({\n contract: toContract,\n schema: fromSchemaIR,\n strict: true,\n typeMetadataRegistry: new Map(),\n frameworkComponents: context.frameworkComponents ?? [],\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n\n // Run descriptor planner\n const planResult = planDescriptors({\n issues: verifyResult.schema.issues,\n toContract,\n fromContract,\n });\n if (!planResult.ok) {\n return { ok: false as const, conflicts: planResult.failure };\n }\n\n return {\n ok: true as const,\n descriptors: planResult.value.descriptors,\n };\n },\n\n resolveDescriptors(descriptors, context) {\n const validated = parseDescriptors(descriptors);\n const codecHooks = context.frameworkComponents\n ? extractCodecControlHooks(context.frameworkComponents)\n : new Map();\n const dependencies = context.frameworkComponents\n ? collectInitDependencies(context.frameworkComponents)\n : [];\n const toContract = context.toContract as Contract<SqlStorage>;\n const db = createMigrationClient(toContract, context.frameworkComponents);\n return resolveOperations(validated, {\n toContract,\n schemaName: context.schemaName ?? 'public',\n codecHooks,\n dependencies,\n db,\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,IAAI,iBAAiB,cAAc,MAAM;CACxC,YAAY,SAAS,OAAO,MAAM;AACjC,QAAM,QAAQ;AACd,OAAK,QAAQ;AACb,OAAK,OAAO;AACZ,OAAK,OAAO;;;;;;AAMd,MAAMA,0BAAwB;;;;;;;;;;;AAW9B,SAAS,gBAAgB,YAAY;AACpC,KAAI,WAAW,WAAW,EAAG,OAAM,IAAI,eAAe,8BAA8B,YAAY,aAAa;AAC7G,KAAI,WAAW,SAAS,KAAK,CAAE,OAAM,IAAI,eAAe,wCAAwC,WAAW,QAAQ,OAAO,MAAM,EAAE,aAAa;AAC/I,KAAI,WAAW,SAASA,wBAAuB,SAAQ,KAAK,eAAe,WAAW,MAAM,GAAG,GAAG,CAAC,4BAA4BA,wBAAsB,wCAAwC;AAC7L,QAAO,IAAI,WAAW,QAAQ,MAAM,OAAO,CAAC;;;;;;;;;;;;;AAa7C,SAAS,cAAc,OAAO;AAC7B,KAAI,MAAM,SAAS,KAAK,CAAE,OAAM,IAAI,eAAe,2CAA2C,MAAM,QAAQ,OAAO,MAAM,EAAE,UAAU;AACrI,QAAO,MAAM,QAAQ,MAAM,KAAK;;;;;AAKjC,SAAS,YAAY,YAAY,YAAY;AAC5C,QAAO,GAAG,gBAAgB,WAAW,CAAC,GAAG,gBAAgB,WAAW;;;;;;;;;;;;;AAarE,SAAS,wBAAwB,OAAO,cAAc;AACrD,KAAI,MAAM,SAASA,wBAAuB,OAAM,IAAI,eAAe,eAAe,MAAM,MAAM,GAAG,GAAG,CAAC,iBAAiB,aAAa,yBAAyBA,wBAAsB,yBAAyB,OAAO,UAAU;;;;;ACrE7N,MAAM,mBAAmB;AACzB,M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