symmetria-kit 3.2.0 → 3.3.0

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-Dog3TEh8.js","names":["levelOrder","sqlState","delay","INDEX_METHODS","RUNTIME_INDEX_METHODS"],"sources":["../src/migrations/sql.ts","../src/migrations/lint.ts","../src/migrations/publication.ts","../src/migrations/files.ts","../src/migrations/sql-lint.ts","../src/migrations/execution.ts","../src/migrations/runner.ts","../src/migrations/verify.ts","../src/migrations/config.ts","../src/introspection/names.ts","../src/introspection/columns.ts","../src/introspection/conditions.ts","../src/introspection/constraints.ts","../src/introspection/model.ts","../src/introspection/render.ts","../src/introspection/index.ts","../src/graph/mermaid.ts"],"sourcesContent":["/**\n * Splits PostgreSQL scripts into statements the way psql does: quoted strings,\n * comments, dollar bodies, parenthesized lists (CREATE RULE … DO (…; …)) and\n * SQL-standard function bodies (BEGIN ATOMIC … END) never end a statement.\n */\nexport type ParsedStatement = {\n /** The statement as written, comments included. */\n sql: string;\n /** Keywords and unquoted identifiers, upper-cased, outside comments and literals. */\n words: string[];\n /** The statement with comments removed and every string literal or dollar body replaced by ''. */\n code: string;\n};\n\nconst TRANSACTION_CONTROL = [\n \"BEGIN\",\n \"COMMIT\",\n \"END\",\n \"ROLLBACK\",\n \"ABORT\",\n \"SAVEPOINT\",\n \"RELEASE\",\n];\n\n/** CREATE [OR REPLACE] FUNCTION|PROCEDURE: the statements whose BEGIN … END blocks psql tracks. */\nconst routineDefinition = (words: readonly string[]): boolean =>\n words[0] === \"CREATE\" &&\n ([\"FUNCTION\", \"PROCEDURE\"].includes(words[1] ?? \"\") ||\n (words[1] === \"OR\" &&\n words[2] === \"REPLACE\" &&\n [\"FUNCTION\", \"PROCEDURE\"].includes(words[3] ?? \"\")));\n\nexport const parseMigrationSQL = (script: string): ParsedStatement[] => {\n const statements: ParsedStatement[] = [];\n let start = 0;\n let position = 0;\n let hasCode = false;\n let words: string[] = [];\n let code = \"\";\n // Semicolons inside parentheses or a BEGIN ATOMIC body belong to the statement.\n let parentheses = 0;\n let blocks = 0;\n\n const finish = (end: number): void => {\n if (hasCode) {\n const first = words[0];\n\n if (\n TRANSACTION_CONTROL.includes(first ?? \"\") ||\n (first === \"START\" && words[1] === \"TRANSACTION\") ||\n (first === \"PREPARE\" && words[1] === \"TRANSACTION\")\n ) {\n throw new Error(\n \"symmetria: migration transaction boundaries are managed by the runner\",\n );\n }\n\n if (first === \"COPY\" && words.includes(\"STDIN\")) {\n throw new Error(\n \"symmetria: COPY FROM STDIN is not supported in migration SQL files\",\n );\n }\n\n if (first === \"SET\" && words.includes(\"STANDARD_CONFORMING_STRINGS\")) {\n throw new Error(\n \"symmetria: migration scripts use standard_conforming_strings=on\",\n );\n }\n\n statements.push({\n sql: script.slice(start, end).trim(),\n words,\n code: code.trim(),\n });\n }\n\n hasCode = false;\n words = [];\n code = \"\";\n parentheses = 0;\n blocks = 0;\n start = end + 1;\n };\n\n while (position < script.length) {\n const character = script[position]!;\n\n if (/\\s/.test(character)) {\n code += character;\n position += 1;\n continue;\n }\n\n if (script.startsWith(\"--\", position)) {\n const newline = script.indexOf(\"\\n\", position + 2);\n position = newline < 0 ? script.length : newline + 1;\n code += \" \";\n continue;\n }\n\n if (script.startsWith(\"/*\", position)) {\n let depth = 1;\n position += 2;\n\n while (position < script.length && depth) {\n if (script.startsWith(\"/*\", position)) {\n depth += 1;\n position += 2;\n } else if (script.startsWith(\"*/\", position)) {\n depth -= 1;\n position += 2;\n } else {\n position += 1;\n }\n }\n\n if (depth) {\n throw new Error(\"symmetria: unterminated SQL block comment\");\n }\n\n code += \" \";\n continue;\n }\n\n if (character === \";\" && !parentheses && !blocks) {\n finish(position);\n position += 1;\n continue;\n }\n\n hasCode = true;\n\n if (character === \"'\" || character === '\"') {\n const escaped =\n character === \"'\" &&\n /[eE]/.test(script[position - 1] ?? \"\") &&\n !/[\\w$]/.test(script[position - 2] ?? \"\");\n const opening = position;\n position += 1;\n let closed = false;\n\n while (position < script.length) {\n if (escaped && script[position] === \"\\\\\") {\n position += 2;\n continue;\n }\n\n if (script[position] === character) {\n if (script[position + 1] === character) {\n position += 2;\n continue;\n }\n\n position += 1;\n closed = true;\n break;\n }\n\n position += 1;\n }\n\n if (!closed) {\n throw new Error(\"symmetria: unterminated SQL quote\");\n }\n\n // Identifiers stay as written; literals never take part in classification.\n code += character === '\"' ? script.slice(opening, position) : \"''\";\n continue;\n }\n\n if (character === \"$\") {\n const tag = script\n .slice(position)\n .match(/^\\$(?:[A-Za-z_\\u0080-￿][A-Za-z_0-9\\u0080-￿]*)?\\$/)?.[0];\n\n if (tag) {\n const end = script.indexOf(tag, position + tag.length);\n\n if (end < 0) {\n throw new Error(\"symmetria: unterminated SQL dollar quote\");\n }\n\n position = end + tag.length;\n code += \"''\";\n continue;\n }\n }\n\n const word = script.slice(position).match(/^[A-Za-z_][A-Za-z_0-9$]*/)?.[0];\n\n if (word) {\n const keyword = word.toUpperCase();\n words.push(keyword);\n code += word;\n position += word.length;\n\n // psql's heuristic: inside CREATE FUNCTION/PROCEDURE, BEGIN opens a block,\n // CASE nests within one and END closes the innermost.\n if (!parentheses && routineDefinition(words)) {\n if (keyword === \"BEGIN\") {\n blocks += 1;\n } else if (keyword === \"CASE\" && blocks) {\n blocks += 1;\n } else if (keyword === \"END\" && blocks) {\n blocks -= 1;\n }\n }\n\n continue;\n }\n\n if (character === \"(\") {\n parentheses += 1;\n } else if (character === \")\" && parentheses) {\n parentheses -= 1;\n }\n\n code += character;\n position += 1;\n }\n\n finish(script.length);\n\n return statements;\n};\n\nexport const splitMigrationSQL = (script: string): string[] =>\n parseMigrationSQL(script).map((statement) => statement.sql);\n\nexport const formatMigrationSQL = (statements: readonly string[]): string =>\n statements.length\n ? `${statements.join(\";\\n\\n\")};\\n`\n : \"-- No schema changes.\\n\";\n","/**\n * Schema-level lint: reviews a migration plan for operations that lose data,\n * fail on populated tables or need deploy planning.\n */\nimport { quoteIdentifier } from \"symmetria/internal\";\nimport {\n changedDefinition,\n counterparts,\n renamedDefinitions,\n type DefinitionScope,\n type MigrationPlan,\n type RenameHints,\n} from \"./diff\";\nimport {\n conversionMessage,\n embeddingChange,\n typeConversion,\n} from \"./conversions\";\nimport type { MigrationColumn, MigrationTable } from \"./snapshot\";\n\n/**\n * destructive: data is lost or becomes unrepresentable (generation requires\n * allowDestructive); blocking: the statement fails on existing data;\n * caution: locks, rewrites or deploy-order hazards.\n */\nexport type LintLevel = \"destructive\" | \"blocking\" | \"caution\";\nexport type LintFinding = {\n readonly level: LintLevel;\n readonly table: string;\n readonly column?: string;\n readonly message: string;\n readonly advice: string;\n};\n\nconst levelOrder: Record<LintLevel, number> = {\n destructive: 0,\n blocking: 1,\n caution: 2,\n};\n\n/** Review a diff for operations that fail or lose data on a populated database. */\nexport const lintMigration = (\n plan: MigrationPlan,\n renames: RenameHints = {},\n): LintFinding[] => {\n const findings: LintFinding[] = [];\n const renamedTables = renames.tables ?? {};\n const afterTables = new Map(\n plan.after.tables.map((table) => [table.name, table]),\n );\n\n const report = (\n level: LintLevel,\n table: string,\n message: string,\n advice: string,\n column?: string,\n ): void => {\n findings.push({\n level,\n table,\n ...(column ? { column } : {}),\n message,\n advice,\n });\n };\n\n // A type that keeps its labels under a new name is renamed in place (ALTER TYPE … RENAME TO).\n const renamedEnumeration = (from?: string, to?: string): boolean => {\n const previous = plan.before.enumerations.find(\n (enumeration) => enumeration.name === from,\n );\n const next = plan.after.enumerations.find(\n (enumeration) => enumeration.name === to,\n );\n\n return (\n previous !== undefined &&\n next !== undefined &&\n !plan.after.enumerations.some(\n (enumeration) => enumeration.name === from,\n ) &&\n !plan.before.enumerations.some(\n (enumeration) => enumeration.name === to,\n ) &&\n previous.values.join(\"\\u0000\") === next.values.join(\"\\u0000\")\n );\n };\n\n const rewritten = (table: MigrationTable, column: MigrationColumn): void => {\n if (column.generated !== undefined) {\n // Rewriting a table builds every index on it again; a vector index is\n // the slowest of them by far.\n const vectors = table.indexes.filter(\n (definition) =>\n definition.method === \"hnsw\" || definition.method === \"ivfflat\",\n );\n const indexes = vectors.length\n ? ` and builds every index on it again, the vector ${vectors.length === 1 ? \"index\" : \"indexes\"} ${vectors.map((definition) => `\"${definition.sqlName}\"`).join(\", \")} too,`\n : \" and builds every index on it again\";\n\n report(\n \"caution\",\n table.name,\n `Column \"${column.name}\" is computed and stored for every existing row; PostgreSQL rewrites the table${indexes} while it holds a lock that blocks reads and writes.`,\n vectors.length\n ? \"On a large table run the migration in a quiet hour; a vector index of many rows takes minutes to build.\"\n : \"On a large table run the migration in a quiet hour.\",\n column.name,\n );\n }\n };\n\n const compareColumns = (\n before: MigrationTable,\n after: MigrationTable,\n ): void => {\n const renamedColumns = renames.columns?.[after.name] ?? {};\n const afterColumns = new Map(\n after.columns.map((column) => [column.name, column]),\n );\n const beforeColumns = new Map(\n before.columns.map((column) => [column.name, column]),\n );\n\n for (const column of before.columns) {\n const renamedTo = renamedColumns[column.name];\n const next = afterColumns.get(renamedTo ?? column.name);\n\n // A generated column holds nothing of its own: PostgreSQL computes it\n // again from the columns that stay.\n if (!next && column.generated !== undefined) {\n continue;\n }\n\n if (!next) {\n report(\n \"destructive\",\n after.name,\n `Column \"${column.name}\" is dropped; its data is lost.`,\n \"Stop reading and writing the column in a release first, then drop it in a later migration.\",\n column.name,\n );\n continue;\n }\n\n if (column.generated !== undefined || next.generated !== undefined) {\n if (column.generated !== next.generated) {\n rewritten(after, next);\n }\n\n continue;\n }\n\n // Renames are catalog-only changes, and SQL lint passes the generated\n // RENAME statements; reporting them here would fail --strict only until\n // the migration is generated.\n compareColumn(after, column, next, renamedColumns);\n\n // A new foreign key validates every existing value; a changed action on\n // the same target column cannot fail, as the old key held.\n const target = column.references && {\n table:\n renamedTables[column.references.table] ?? column.references.table,\n column: column.references.column,\n };\n const targetColumn =\n target &&\n (renames.columns?.[target.table]?.[target.column] ?? target.column);\n\n if (\n next.references &&\n (target?.table !== next.references.table ||\n targetColumn !== next.references.column)\n ) {\n report(\n \"blocking\",\n after.name,\n `Column \"${next.name}\" gains a foreign key to ${next.references.table}.${next.references.column}; the statement fails when an existing value has no match.`,\n \"Fix or clear unmatched values first, or generate with --online, which adds the key NOT VALID and validates it separately.\",\n next.name,\n );\n }\n }\n\n // Checks and indexes are matched the way the diff matches them, so one\n // that only follows a renamed table or column, or is written differently,\n // is not reported as new.\n const scope: DefinitionScope = {\n affected: [],\n renamed: renamedDefinitions(\n new Map(\n Object.entries(renamedColumns).map(([previous, next]) => [\n quoteIdentifier(previous),\n quoteIdentifier(next),\n ]),\n ),\n ),\n types: new Map(\n after.columns.map((column) => [column.name, column.sqlType]),\n ),\n };\n const kept = <Definition extends { sqlName: string }>(\n previous: readonly Definition[],\n next: readonly Definition[],\n ): Set<string> => {\n const matches = counterparts(scope, previous, next);\n\n return new Set(\n previous.flatMap((definition) => {\n const match = matches.get(definition.sqlName);\n\n return match && !changedDefinition(scope, definition, match)\n ? [match.sqlName]\n : [];\n }),\n );\n };\n const keptChecks = kept(before.checks ?? [], after.checks ?? []);\n const keptIndexes = kept(before.indexes, after.indexes);\n\n // CHECK constraints validate every existing row, like NOT NULL.\n for (const definition of after.checks ?? []) {\n if (!keptChecks.has(definition.sqlName)) {\n report(\n \"blocking\",\n after.name,\n `CHECK constraint \"${definition.sqlName}\" is added; the statement fails when an existing row violates it.`,\n \"Fix violating rows first, or generate with --online, which adds the check NOT VALID and validates it separately.\",\n );\n }\n }\n\n for (const column of after.columns) {\n if (\n beforeColumns.has(column.name) ||\n Object.values(renamedColumns).includes(column.name)\n ) {\n continue;\n }\n\n if (column.generated !== undefined) {\n rewritten(after, column);\n continue;\n }\n\n if (column.notNull && column.default === undefined && !column.identity) {\n report(\n \"blocking\",\n after.name,\n `Column \"${column.name}\" is added as NOT NULL without a default; the statement fails when the table has rows.`,\n \"Add a default, or add the column as nullable, backfill it and set NOT NULL in a later migration.\",\n column.name,\n );\n }\n\n if (column.unique) {\n report(\n \"caution\",\n after.name,\n `Column \"${column.name}\" is added with a UNIQUE constraint.`,\n \"Existing rows all receive the same default; make sure the default is unique or add the constraint after backfilling.\",\n column.name,\n );\n }\n }\n\n for (const definition of after.indexes) {\n if (keptIndexes.has(definition.sqlName)) {\n continue;\n }\n\n report(\n definition.unique ? \"blocking\" : \"caution\",\n after.name,\n definition.unique\n ? `Unique index \"${definition.sqlName}\" fails when existing rows contain duplicates.`\n : `Index \"${definition.sqlName}\" is created inside the migration transaction and blocks writes while it builds.`,\n definition.unique\n ? \"Deduplicate the data first, then add the index.\"\n : \"For large tables create it separately with $createIndexes({ concurrently: true }).\",\n );\n }\n\n if (\n JSON.stringify(before.primaryKey) !== JSON.stringify(after.primaryKey)\n ) {\n report(\n \"caution\",\n after.name,\n `Primary key changes from (${before.primaryKey.join(\", \")}) to (${after.primaryKey.join(\", \")}).`,\n \"The table is rewritten and foreign keys are rebuilt; plan the deploy for low traffic.\",\n );\n }\n };\n\n const compareColumn = (\n table: MigrationTable,\n before: MigrationColumn,\n after: MigrationColumn,\n renamedColumns: Readonly<Record<string, string>> = {},\n ): void => {\n const retyped =\n before.sqlType !== after.sqlType ||\n (before.enumeration !== after.enumeration &&\n !renamedEnumeration(before.enumeration, after.enumeration));\n const change = retyped ? typeConversion(before, after) : undefined;\n const stale = embeddingChange(before, after, renamedColumns);\n\n if (stale && !change?.cleared) {\n report(\n \"destructive\",\n table.name,\n `The embeddings in \"${after.name}\" are cleared: ${stale}, so the stored ones describe other text. Every row of the table is updated.`,\n \"Generate with --allow-destructive, then run search.reindex() after the migration to compute them again; search.missing() counts what is left.\",\n after.name,\n );\n }\n\n if (change?.lossy) {\n report(\n \"destructive\",\n table.name,\n conversionMessage(before, after, change),\n change.assignmentCast\n ? \"Shorten or move longer values first, then generate with --allow-destructive; the SQL has no truncating cast, so PostgreSQL refuses values that still do not fit.\"\n : change.cleared\n ? \"Generate with --allow-destructive, then compute the embeddings again after the migration (search.reindex() for a search's own column).\"\n : change.refused\n ? \"Move or change the values that do not fit first, then generate with --allow-destructive; PostgreSQL refuses values that still do not fit.\"\n : \"Copy the column or back up the table if the lost precision matters, then generate with --allow-destructive.\",\n after.name,\n );\n } else if (retyped) {\n report(\n \"caution\",\n table.name,\n `Column \"${after.name}\" changes type from ${before.enumeration ?? before.sqlType} to ${after.enumeration ?? after.sqlType}.`,\n \"PostgreSQL rewrites the table and the USING cast can fail on existing values; add a new column, backfill in batches and swap it in a later migration.\",\n after.name,\n );\n }\n\n if (!before.notNull && after.notNull) {\n report(\n \"blocking\",\n table.name,\n `Column \"${after.name}\" becomes NOT NULL; the statement fails when existing rows contain NULL.`,\n \"Backfill NULL values first, or add a default and set NOT NULL in a later migration.\",\n after.name,\n );\n }\n\n if (!before.unique && after.unique) {\n report(\n \"blocking\",\n table.name,\n `Column \"${after.name}\" becomes UNIQUE; the statement fails when existing rows contain duplicates.`,\n \"Deduplicate the data first, then add the constraint.\",\n after.name,\n );\n }\n };\n\n for (const table of plan.before.tables) {\n const renamedTo = renamedTables[table.name];\n const next = afterTables.get(renamedTo ?? table.name);\n\n if (!next) {\n report(\n \"destructive\",\n table.name,\n `Table \"${table.name}\" is dropped; its rows are lost.`,\n \"Stop using the table in a release first, keep a backup, then drop it in a later migration.\",\n );\n continue;\n }\n\n compareColumns(table, next);\n }\n\n for (const enumeration of plan.before.enumerations) {\n const next = plan.after.enumerations.find(\n (candidate) => candidate.name === enumeration.name,\n );\n\n if (!next) {\n continue;\n }\n\n const removed = enumeration.values.filter(\n (value) => !next.values.includes(value),\n );\n\n if (removed.length) {\n // Removing a label is gated like a dropped column: rows that use it must\n // be rewritten or deleted first, and the rebuild cannot restore them.\n report(\n \"destructive\",\n enumeration.name,\n `Enum \"${enumeration.name}\" drops ${removed.map((value) => `'${value}'`).join(\", \")}; rows using those labels make the rebuild fail.`,\n \"Update or delete the rows that use the removed labels before migrating.\",\n );\n } else if (\n JSON.stringify(enumeration.values) !== JSON.stringify(next.values)\n ) {\n const added = plan.up.some((statement) =>\n statement.startsWith(\n `ALTER TYPE ${quoteIdentifier(enumeration.name)} ADD VALUE `,\n ),\n );\n\n report(\n \"caution\",\n enumeration.name,\n added\n ? `Enum \"${enumeration.name}\" gains labels in place.`\n : `Enum \"${enumeration.name}\" is rebuilt to change its labels.`,\n added\n ? \"A new label can be used only after the migration that adds it commits.\"\n : \"Dependent columns are rewritten while the type is replaced; plan for the lock.\",\n );\n }\n }\n\n return findings.sort(\n (left, right) =>\n levelOrder[left.level] - levelOrder[right.level] ||\n left.table.localeCompare(right.table),\n );\n};\n\nexport const formatLintFindings = (findings: readonly LintFinding[]): string =>\n findings.length\n ? findings\n .map(\n (finding) =>\n `${finding.level.toUpperCase().padEnd(11)} ${finding.table}${finding.column ? `.${finding.column}` : \"\"}: ${finding.message}\\n ${finding.advice}`,\n )\n .join(\"\\n\")\n : \"No risky operations found.\";\n","/**\n * Atomic publication of generated migration files: lock file, fsync, ownership record, rollback and crash recovery.\n */\nimport {\n open,\n readFile,\n rename,\n rm,\n mkdir,\n writeFile,\n stat,\n} from \"node:fs/promises\";\nimport { hostname } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\n\nexport const generationLockName = \".symmetria-generate.lock\";\nexport type Publication = {\n temporary: string;\n hadMetadata: boolean;\n moves: { source: string; destination: string; identity: string }[];\n committed: boolean;\n};\n\nexport const fileIdentity = async (\n path: string,\n): Promise<string | undefined> => {\n try {\n const value = await stat(path, { bigint: true });\n\n return `${value.dev}:${value.ino}`;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return undefined;\n }\n\n throw error;\n }\n};\n\nexport const syncPath = async (path: string) => {\n const file = await open(path, \"r\");\n\n try {\n await file.sync();\n } finally {\n await file.close();\n }\n};\n\nexport const savePublication = async (\n directory: string,\n publication: Publication,\n) => {\n const path = join(directory, generationLockName, \"publication.json\");\n await writeFile(`${path}.next`, JSON.stringify(publication));\n await syncPath(`${path}.next`);\n await rename(`${path}.next`, path);\n await syncPath(dirname(path));\n};\n\nexport const recordGenerationOwner = async (directory: string) => {\n const path = join(directory, generationLockName, \"owner.json\");\n await writeFile(path, JSON.stringify({ pid: process.pid, host: hostname() }));\n await syncPath(path);\n await syncPath(dirname(path));\n await syncPath(directory);\n};\n\nconst present = async (path: string) => {\n try {\n const file = await open(path);\n await file.close();\n\n return true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nexport const rollbackPublication = async (publication: Publication) => {\n for (const { source, destination, identity } of [\n ...publication.moves,\n ].reverse()) {\n const sourceIdentity = await fileIdentity(source);\n\n if (sourceIdentity === identity) {\n continue;\n }\n\n if (\n (await fileIdentity(destination)) === identity &&\n sourceIdentity === undefined\n ) {\n await rename(destination, source);\n await syncPath(dirname(source));\n await syncPath(dirname(destination));\n } else {\n throw new Error(\n `symmetria: conflicting publication recovery files: ${source} and ${destination}`,\n );\n }\n }\n};\n\n/**\n * Recover a process crash without discarding a live writer or guessing at\n * incomplete metadata. Resolves false when no generation lock is left behind.\n */\nexport const recoverMigrationFiles = async (\n directory: string,\n): Promise<boolean> => {\n directory = resolve(directory);\n const lock = join(directory, generationLockName);\n\n if ((await fileIdentity(lock)) === undefined) {\n return false;\n }\n\n let owner: { pid: number; host: string };\n\n try {\n owner = JSON.parse(await readFile(join(lock, \"owner.json\"), \"utf8\"));\n } catch (error) {\n throw new Error(\n `symmetria: generation lock ${lock} has no readable owner.json (the generator stopped before recording it); make sure no generate or squash is running, then inspect and remove the lock manually`,\n { cause: error },\n );\n }\n\n if (\n owner.host !== hostname() ||\n !Number.isSafeInteger(owner.pid) ||\n owner.pid < 1\n ) {\n throw new Error(\n \"symmetria: generation lock belongs to another host or has invalid ownership; inspect it manually\",\n );\n }\n\n try {\n process.kill(owner.pid, 0);\n throw new Error(\"symmetria: migration generation owner is still running\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") {\n throw error;\n }\n }\n\n const recovery = join(lock, \"recovering\");\n await mkdir(recovery);\n\n try {\n const path = join(lock, \"publication.json\");\n\n if (await present(path)) {\n const publication = JSON.parse(\n await readFile(path, \"utf8\"),\n ) as Publication;\n\n // Recovery journals may only move files within this migration directory.\n const inside = (path: string) =>\n resolve(path).startsWith(`${directory}/`);\n\n if (\n !inside(publication.temporary) ||\n !publication.temporary.startsWith(join(directory, \".symmetria-\")) ||\n typeof publication.hadMetadata !== \"boolean\" ||\n typeof publication.committed !== \"boolean\" ||\n !Array.isArray(publication.moves) ||\n publication.moves.some(\n (move) =>\n !inside(move.source) ||\n !inside(move.destination) ||\n typeof move.identity !== \"string\",\n )\n ) {\n throw new Error(\"symmetria: invalid publication recovery journal\");\n }\n\n if (!publication.committed) {\n await rollbackPublication(publication);\n\n if (!publication.hadMetadata) {\n await rm(join(directory, \"meta\"), { recursive: true, force: true });\n }\n\n publication.moves = [];\n await savePublication(directory, publication);\n }\n\n await rm(publication.temporary, { recursive: true, force: true });\n }\n\n await rm(lock, { recursive: true, force: true });\n await syncPath(directory);\n } catch (error) {\n await rm(recovery, { recursive: true, force: true });\n throw error;\n }\n\n return true;\n};\n","/**\n * Migration files on disk: manifest and state loading, SQL generation, squashing and file naming.\n */\nimport {\n mkdir,\n mkdtemp,\n readFile,\n readdir,\n realpath,\n rename,\n rm,\n writeFile,\n access,\n} from \"node:fs/promises\";\nimport { execFile } from \"node:child_process\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { SchemaSnapshot } from \"symmetria\";\nimport { diffSchemas, type MigrationDiffOptions } from \"./diff\";\nimport {\n canonicalJSON,\n checksum,\n compareNames,\n emptySnapshot,\n migrationSnapshot,\n parseMigrationSnapshot,\n snapshotHash,\n type MigrationSnapshot,\n} from \"./snapshot\";\nimport { formatMigrationSQL, splitMigrationSQL } from \"./sql\";\nimport { lintMigration } from \"./lint\";\nimport {\n fileIdentity,\n generationLockName,\n recordGenerationOwner,\n rollbackPublication,\n savePublication,\n syncPath,\n type Publication,\n} from \"./publication\";\n\nexport type MigrationManifest = {\n version: 1;\n id: string;\n parent: string | null;\n before: string;\n after: string;\n /** Omitted/batch preserves atomic execution of all pending transactional migrations. */\n transaction?: \"batch\" | \"each\" | \"none\";\n /** SHA-256 of up.sql as generate wrote it; squash refuses to drop SQL that differs. */\n generated?: string;\n};\nexport type Migration = {\n id: string;\n manifest: MigrationManifest;\n up: string;\n down: string;\n checksum: string;\n};\nexport type GeneratedMigration = Migration & { snapshot: MigrationSnapshot };\nexport type MigrationState = {\n migrations: Migration[];\n snapshot: MigrationSnapshot;\n};\nexport type GenerateMigrationOptions = MigrationDiffOptions & {\n directory: string;\n name: string;\n snapshot?: SchemaSnapshot | MigrationSnapshot;\n empty?: boolean;\n allowDestructive?: boolean;\n transaction?: \"batch\" | \"each\" | \"none\";\n};\nexport type SquashMigrationsOptions = {\n directory: string;\n name: string;\n /** Drop SQL that generate did not write (seeds, views, edited up.sql) instead of refusing. */\n allowCustomSQL?: boolean;\n};\ntype MigrationJournal = {\n version: 1;\n migrations: MigrationManifest[];\n /**\n * The snapshot before the latest migration, so `discard` can take that\n * migration back while no database has applied it. Releases that do not\n * know it ignore it.\n */\n undo?: { migration: string; snapshot: MigrationSnapshot };\n};\nexport type DiscardMigrationOptions = {\n directory: string;\n /** The migration expected to be the latest; refused when another one is. */\n id?: string;\n /** Discard an up.sql edited after generation, losing the edits. */\n allowEdited?: boolean;\n};\nexport type DiscardedMigration = {\n /** The removed migration; undefined when only the snapshot was repaired. */\n id?: string;\n /** Where the earlier snapshot came from. */\n source: \"journal\" | \"empty chain\" | \"git\";\n};\nconst migrationIdPattern = /^\\d{6}_[a-z0-9][a-z0-9_]*$/;\nconst hashPattern = /^[a-f0-9]{64}$/;\nconst metadataFiles = [\"migration.json\", \"snapshot.json\"];\nconst lockName = generationLockName;\n\n/** Checksums ignore CRLF line endings, so an editor or Git setting cannot invalidate applied migrations. */\nconst lineFeeds = (sql: string): string => sql.replaceAll(\"\\r\\n\", \"\\n\");\n\nconst migrationChecksum = (\n manifest: MigrationManifest,\n up: string,\n down: string,\n): string =>\n checksum(\n canonicalJSON({ manifest, up: lineFeeds(up), down: lineFeeds(down) }),\n );\n\n/**\n * Whether a journal checksum belongs to this migration: the line-feed form, or\n * the exact bytes that releases before the normalization hashed for CRLF files.\n */\nexport const checksumMatches = (\n migration: Migration,\n recorded: string,\n): boolean =>\n migration.checksum === recorded ||\n checksum(\n canonicalJSON({\n manifest: migration.manifest,\n up: migration.up,\n down: migration.down,\n }),\n ) === recorded;\n\nconst sqlChecksum = (up: string): string => checksum(lineFeeds(up));\n\nconst parseMetadata = (directory: string, name: string, text: string) => {\n try {\n return JSON.parse(text) as unknown;\n } catch (error) {\n throw new Error(\n `symmetria: ${join(directory, \"meta\", name)} is not valid JSON (${error instanceof Error ? error.message : String(error)}); restore it from version control`,\n { cause: error },\n );\n }\n};\n\nconst missing = (error: unknown): boolean =>\n !!error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"ENOENT\";\n\nconst exists = (path: string): Promise<boolean> =>\n access(path).then(\n () => true,\n (error: unknown) => {\n if (missing(error)) {\n return false;\n }\n\n throw error;\n },\n );\n\nconst readDirectory = (directory: string) =>\n readdir(directory, { withFileTypes: true }).catch((error: unknown) => {\n if (missing(error)) {\n return [];\n }\n\n throw error;\n });\n\nconst readMigrationState = async (\n directory: string,\n options: { readonly snapshotMismatch?: \"throw\" | \"keep\" } = {},\n): Promise<\n MigrationState & {\n readonly undo?: MigrationJournal[\"undo\"];\n /** The snapshot is not the schema after the journal's last migration. */\n readonly mismatch?: true;\n }\n> => {\n const entries = await readDirectory(directory);\n const directories = entries\n .filter(\n (entry) =>\n entry.name !== \"meta\" &&\n !entry.name.startsWith(\".\") &&\n entry.isDirectory(),\n )\n .map((entry) => entry.name)\n .sort(compareNames);\n const metadata = await readDirectory(join(directory, \"meta\"));\n\n if (!directories.length && !metadata.length) {\n return { migrations: [], snapshot: emptySnapshot() };\n }\n\n if (\n metadata.length !== metadataFiles.length ||\n metadata.some(\n (entry) => !entry.isFile() || !metadataFiles.includes(entry.name),\n )\n ) {\n throw new Error(\n \"symmetria: migration metadata must contain only meta/snapshot.json and meta/migration.json\",\n );\n }\n\n const [journalText, snapshotText] = await Promise.all(\n metadataFiles.map((name) =>\n readFile(join(directory, \"meta\", name), \"utf8\"),\n ),\n );\n const journal = parseMetadata(\n directory,\n \"migration.json\",\n journalText!,\n ) as MigrationJournal;\n const snapshot = parseMigrationSnapshot(\n parseMetadata(directory, \"snapshot.json\", snapshotText!),\n );\n\n if (\n !journal ||\n journal.version !== 1 ||\n !Array.isArray(journal.migrations) ||\n journal.migrations.length !== directories.length\n ) {\n const listed = Array.isArray(journal?.migrations)\n ? journal.migrations.map((manifest) => String(manifest?.id))\n : [];\n const unlisted = directories.filter((id) => !listed.includes(id));\n const absent = listed.filter((id) => !directories.includes(id));\n\n throw new Error(\n `symmetria: migration journal ${join(directory, \"meta\", \"migration.json\")} does not match the SQL directories in ${directory} (${listed.length} listed, ${directories.length} found${absent.length ? `; missing directories: ${absent.join(\", \")}` : \"\"}${unlisted.length ? `; directories not in the journal: ${unlisted.join(\", \")}` : \"\"})`,\n );\n }\n\n const migrations: Migration[] = [];\n let previousHash = snapshotHash(emptySnapshot());\n let previousOrdinal = 0;\n\n for (const [position, id] of directories.entries()) {\n const manifest = journal.migrations[position];\n\n if (\n !migrationIdPattern.test(id) ||\n Number(id.slice(0, 6)) <= previousOrdinal ||\n !manifest ||\n manifest.version !== 1 ||\n manifest.id !== id ||\n manifest.parent !== (migrations.at(-1)?.id ?? null) ||\n manifest.before !== previousHash ||\n typeof manifest.after !== \"string\" ||\n !hashPattern.test(manifest.after) ||\n (manifest.transaction !== undefined &&\n ![\"batch\", \"each\", \"none\"].includes(manifest.transaction)) ||\n (manifest.generated !== undefined &&\n (typeof manifest.generated !== \"string\" ||\n !hashPattern.test(manifest.generated)))\n ) {\n throw new Error(`symmetria: migration chain mismatch at \"${id}\"`);\n }\n\n const location = join(directory, id);\n\n if (\n (await readDirectory(location)).some((entry) =>\n metadataFiles.includes(entry.name),\n )\n ) {\n throw new Error(\n `symmetria: unexpected per-migration metadata in \"${id}\"`,\n );\n }\n\n const [up, down] = await Promise.all([\n readFile(join(location, \"up.sql\"), \"utf8\"),\n readFile(join(location, \"down.sql\"), \"utf8\"),\n ]);\n splitMigrationSQL(up);\n splitMigrationSQL(down);\n migrations.push({\n id,\n manifest,\n up,\n down,\n checksum: migrationChecksum(manifest, up, down),\n });\n previousHash = manifest.after;\n previousOrdinal = Number(id.slice(0, 6));\n }\n\n const undo =\n journal.undo &&\n typeof journal.undo.migration === \"string\" &&\n journal.undo.snapshot\n ? {\n migration: journal.undo.migration,\n snapshot: parseMigrationSnapshot(journal.undo.snapshot),\n }\n : undefined;\n\n if (snapshotHash(snapshot) !== previousHash) {\n if (options.snapshotMismatch === \"keep\") {\n return {\n migrations,\n snapshot,\n ...(undo ? { undo } : {}),\n mismatch: true,\n };\n }\n\n throw new Error(\n `symmetria: latest snapshot checksum does not match the migration journal: ${join(directory, \"meta\", \"snapshot.json\")} is not the schema after ${migrations.at(-1) ? `\"${migrations.at(-1)!.id}\"` : \"an empty chain\"} in ${join(directory, \"meta\", \"migration.json\")}. If a migration was removed by hand, \"symmetria discard\" puts the snapshot back; to remove a migration no database applied, run \"symmetria discard\" instead of deleting files.`,\n );\n }\n\n return { migrations, snapshot, ...(undo ? { undo } : {}) };\n};\n\n/** One current schema snapshot and a compact journal for the entire SQL chain. */\nexport const loadMigrationState = async (\n directory: string,\n): Promise<MigrationState> => {\n const assertUnlocked = async () => {\n if (await exists(join(directory, lockName))) {\n throw new Error(\"symmetria: migration generation is already locked\");\n }\n };\n\n await assertUnlocked();\n const state = await readMigrationState(directory);\n await assertUnlocked();\n\n return state;\n};\n\nexport const loadMigrations = async (directory: string): Promise<Migration[]> =>\n (await loadMigrationState(directory)).migrations;\n\nconst normalizeName = (name: string): string => {\n const normalized = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_|_$/g, \"\");\n\n if (!normalized || normalized.length > 100) {\n throw new Error(\n \"symmetria: migration names must contain 1–100 letters/digits after normalization\",\n );\n }\n\n return normalized;\n};\n\nconst withGenerationLock = async <Result>(\n directory: string,\n callback: () => Promise<Result>,\n): Promise<Result> => {\n await mkdir(directory, { recursive: true });\n const lock = join(directory, lockName);\n await mkdir(lock).catch((error: unknown) => {\n if (\n error &&\n typeof error === \"object\" &&\n \"code\" in error &&\n error.code === \"EEXIST\"\n ) {\n throw new Error(\"symmetria: migration generation is already locked\");\n }\n\n throw error;\n });\n\n try {\n await recordGenerationOwner(directory);\n\n return await callback();\n } finally {\n if (!(await exists(join(lock, \"publication.json\")))) {\n await rm(lock, { recursive: true, force: true });\n }\n }\n};\n\n/**\n * Publishes the metadata and, when given, a new migration's SQL; the\n * migrations in `replaced` leave the directory. Every step can be rolled\n * back, and `recover` finishes one a crash interrupted.\n */\nconst writeMigrationFiles = async (\n directory: string,\n migration:\n | GeneratedMigration\n | { readonly id?: undefined; readonly snapshot: MigrationSnapshot },\n manifests: MigrationManifest[],\n replaced: string[] = [],\n undo?: MigrationJournal[\"undo\"],\n): Promise<void> => {\n if (\n migration.id !== undefined &&\n !replaced.includes(migration.id) &&\n (await exists(join(directory, migration.id)))\n ) {\n throw new Error(`symmetria: migration \"${migration.id}\" already exists`);\n }\n\n const temporary = await mkdtemp(join(directory, \".symmetria-\"));\n const staged = join(temporary, \"staged\");\n const backup = join(temporary, \"backup\");\n const moved: Publication[\"moves\"] = [];\n let preserveBackup = false;\n const hadMetadata = await exists(join(directory, \"meta\"));\n const publication: Publication = {\n temporary,\n hadMetadata,\n moves: moved,\n committed: false,\n };\n\n const move = async (source: string, destination: string): Promise<void> => {\n moved.push({\n source,\n destination,\n identity: (await fileIdentity(source))!,\n });\n await savePublication(directory, publication);\n await rename(source, destination);\n await syncPath(resolve(source, \"..\"));\n await syncPath(resolve(destination, \"..\"));\n };\n\n try {\n await Promise.all([\n ...(migration.id === undefined\n ? []\n : [mkdir(join(staged, migration.id), { recursive: true })]),\n mkdir(join(staged, \"meta\"), { recursive: true }),\n mkdir(join(backup, \"meta\"), { recursive: true }),\n ]);\n const journal: MigrationJournal = {\n version: 1,\n migrations: manifests,\n ...(undo ? { undo } : {}),\n };\n await Promise.all([\n ...(\"up\" in migration\n ? [\n writeFile(join(staged, migration.id, \"up.sql\"), migration.up),\n writeFile(join(staged, migration.id, \"down.sql\"), migration.down),\n ]\n : []),\n writeFile(\n join(staged, \"meta\", \"migration.json\"),\n `${JSON.stringify(journal, null, 2)}\\n`,\n ),\n writeFile(\n join(staged, \"meta\", \"snapshot.json\"),\n `${JSON.stringify(migration.snapshot, null, 2)}\\n`,\n ),\n ]);\n\n for (const path of [\n ...(migration.id === undefined\n ? []\n : [\n join(staged, migration.id, \"up.sql\"),\n join(staged, migration.id, \"down.sql\"),\n ]),\n ...metadataFiles.map((name) => join(staged, \"meta\", name)),\n ...(migration.id === undefined ? [] : [join(staged, migration.id)]),\n join(staged, \"meta\"),\n staged,\n backup,\n temporary,\n ]) {\n await syncPath(path);\n }\n\n await savePublication(directory, publication);\n await mkdir(join(directory, \"meta\"), { recursive: true });\n\n // Retain the old pair and SQL until every replacement has been published.\n for (const id of replaced) {\n await move(join(directory, id), join(backup, id));\n }\n\n for (const name of metadataFiles) {\n const path = join(directory, \"meta\", name);\n\n if (await exists(path)) {\n await move(path, join(backup, \"meta\", name));\n }\n\n await move(join(staged, \"meta\", name), path);\n }\n\n if (migration.id !== undefined) {\n await move(join(staged, migration.id), join(directory, migration.id));\n }\n\n publication.committed = true;\n await savePublication(directory, publication);\n } catch (error) {\n if (publication.committed) {\n preserveBackup = true;\n throw new Error(\n \"symmetria: publication commit could not be confirmed; use recover after this process exits\",\n { cause: error },\n );\n }\n\n const failures: unknown[] = [error];\n\n try {\n await rollbackPublication(publication);\n } catch (rollbackError) {\n failures.push(rollbackError);\n }\n\n if (failures.length > 1) {\n preserveBackup = true;\n throw new AggregateError(\n failures,\n `symmetria: migration publication rollback failed; original files retained in ${backup}`,\n );\n }\n\n if (!hadMetadata) {\n await rm(join(directory, \"meta\"), { recursive: true, force: true });\n }\n\n preserveBackup = true;\n publication.moves = [];\n await savePublication(directory, publication);\n preserveBackup = false;\n\n throw error;\n } finally {\n if (!preserveBackup) {\n await rm(temporary, { recursive: true, force: true });\n await rm(join(directory, lockName, \"publication.json\"), { force: true });\n }\n }\n};\n\n/** Replace the SQL chain and journal with a baseline for the current snapshot. */\nexport const squashMigrations = async (\n options: SquashMigrationsOptions,\n): Promise<GeneratedMigration | null> => {\n const directory = resolve(options.directory);\n const name = normalizeName(options.name);\n\n return withGenerationLock(directory, async () => {\n const { migrations, snapshot } = await readMigrationState(directory);\n\n if (migrations.length < 2) {\n return null;\n }\n\n // The baseline is generated from the snapshot alone, so a new installation\n // never runs SQL that generate did not write.\n const custom = migrations.flatMap((migration) => {\n const { manifest } = migration;\n const empty = manifest.before === manifest.after;\n const edited =\n manifest.generated === undefined\n ? // Journals from before the recorded checksum: only empty migrations are known to be hand-written.\n empty && splitMigrationSQL(migration.up).length > 0\n : manifest.generated !== sqlChecksum(migration.up);\n\n return edited\n ? [\n ` - ${migration.id}: ${empty ? \"SQL written into an empty migration\" : \"up.sql edited after generation\"}`,\n ]\n : [];\n });\n\n if (custom.length && !options.allowCustomSQL) {\n throw new Error(\n `symmetria: squash would drop SQL that generate did not write, so new installations would never run it:\\n${custom.join(\"\\n\")}\\nCopy that SQL into a migration after the baseline (generate <name> --empty), or pass --allow-custom-sql (allowCustomSQL: true) to drop it.`,\n );\n }\n\n const plan = diffSchemas(emptySnapshot(), snapshot);\n const id = `000001_${name}`;\n const up = formatMigrationSQL(plan.up);\n const down = formatMigrationSQL(plan.down);\n const manifest: MigrationManifest = {\n version: 1,\n id,\n parent: null,\n before: snapshotHash(emptySnapshot()),\n after: snapshotHash(snapshot),\n generated: sqlChecksum(up),\n };\n const squashed: GeneratedMigration = {\n id,\n manifest,\n snapshot,\n up,\n down,\n checksum: migrationChecksum(manifest, up, down),\n };\n await writeMigrationFiles(\n directory,\n squashed,\n [manifest],\n migrations.map((migration) => migration.id),\n );\n\n return squashed;\n });\n};\n\n/** SQL files are editable before application; applied checksums include both directions. */\nexport const generateMigration = async (\n options: GenerateMigrationOptions,\n): Promise<GeneratedMigration | null> => {\n const directory = resolve(options.directory);\n const name = normalizeName(options.name);\n\n if (\n options.transaction !== undefined &&\n ![\"batch\", \"each\", \"none\"].includes(options.transaction)\n ) {\n throw new Error(\"symmetria: transaction must be batch, each, or none\");\n }\n\n if (options.online && options.transaction && options.transaction !== \"none\") {\n throw new Error(\n 'symmetria: online generation requires transaction: \"none\"',\n );\n }\n\n return withGenerationLock(directory, async () => {\n const { migrations, snapshot: before } =\n await readMigrationState(directory);\n const previous = migrations.at(-1);\n\n if (!options.empty && !options.snapshot) {\n throw new Error(\"symmetria: generation requires a schema snapshot\");\n }\n\n const next = options.empty ? before : options.snapshot!;\n const after =\n \"version\" in next\n ? parseMigrationSnapshot(next)\n : migrationSnapshot(next);\n const plan = diffSchemas(before, after, options);\n\n const destructive = options.allowDestructive\n ? []\n : lintMigration(plan, options.renames).filter(\n (finding) => finding.level === \"destructive\",\n );\n\n if (destructive.length) {\n throw new Error(\n `symmetria: destructive migration requires explicit rename hints or allowDestructive (--allow-destructive):\\n${destructive\n .map(\n (finding) =>\n ` - ${finding.table}${finding.column ? `.${finding.column}` : \"\"}: ${finding.message}`,\n )\n .join(\"\\n\")}`,\n );\n }\n\n if (!options.empty && !plan.up.length && !plan.down.length) {\n return null;\n }\n\n const ordinal = Number(previous?.id.slice(0, 6) ?? 0) + 1;\n\n if (ordinal > 999999) {\n throw new Error(\"symmetria: migration sequence exhausted\");\n }\n\n const id = `${String(ordinal).padStart(6, \"0\")}_${name}`;\n const up = formatMigrationSQL(plan.up);\n const down = formatMigrationSQL(plan.down);\n const manifest: MigrationManifest = {\n version: 1,\n id,\n parent: previous?.id ?? null,\n before: snapshotHash(before),\n after: snapshotHash(after),\n ...(options.online\n ? { transaction: \"none\" as const }\n : options.transaction && options.transaction !== \"batch\"\n ? { transaction: options.transaction }\n : {}),\n generated: sqlChecksum(up),\n };\n const migration: GeneratedMigration = {\n id,\n manifest,\n snapshot: after,\n up,\n down,\n checksum: migrationChecksum(manifest, up, down),\n };\n await writeMigrationFiles(\n directory,\n migration,\n [...migrations.map((entry) => entry.manifest), manifest],\n [],\n // The way back while no database has applied it: `discard`.\n { migration: id, snapshot: before },\n );\n\n return migration;\n });\n};\n\nconst execute = promisify(execFile);\n\n/**\n * The snapshot with a hash from the history of `meta/snapshot.json` in Git:\n * the working tree's last commit first, then older ones. Undefined outside a\n * repository or when no version has it.\n */\nconst snapshotFromHistory = async (\n directory: string,\n hash: string,\n): Promise<MigrationSnapshot | undefined> => {\n // Git names files by their real path; a temporary directory may be a link.\n const path = await realpath(join(directory, \"meta\", \"snapshot.json\")).catch(\n () => join(directory, \"meta\", \"snapshot.json\"),\n );\n const git = (from: string, ...argumentsList: string[]) =>\n execute(\"git\", [\"-C\", from, ...argumentsList], {\n maxBuffer: 64 * 1024 * 1024,\n }).then((result) => result.stdout);\n\n try {\n const root = (\n await git(dirname(path), \"rev-parse\", \"--show-toplevel\")\n ).trim();\n const file = relative(root, path).split(\"\\\\\").join(\"/\");\n const commits = (\n await git(root, \"log\", \"--format=%H\", \"-n\", \"200\", \"--\", file)\n )\n .split(\"\\n\")\n .filter(Boolean);\n\n for (const commit of commits) {\n try {\n const snapshot = parseMigrationSnapshot(\n JSON.parse(await git(root, \"show\", `${commit}:${file}`)),\n );\n\n if (snapshotHash(snapshot) === hash) {\n return snapshot;\n }\n } catch {\n // A version that does not parse is not the one looked for.\n }\n }\n } catch {\n return undefined;\n }\n\n return undefined;\n};\n\n/** The snapshot whose hash a chain expects: from the journal, the empty chain or Git. */\nconst knownSnapshot = async (\n directory: string,\n hash: string,\n undo: MigrationJournal[\"undo\"],\n): Promise<\n | { snapshot: MigrationSnapshot; source: DiscardedMigration[\"source\"] }\n | undefined\n> => {\n if (undo && snapshotHash(undo.snapshot) === hash) {\n return { snapshot: undo.snapshot, source: \"journal\" };\n }\n\n if (snapshotHash(emptySnapshot()) === hash) {\n return { snapshot: emptySnapshot(), source: \"empty chain\" };\n }\n\n const remembered = await snapshotFromHistory(directory, hash);\n\n return remembered ? { snapshot: remembered, source: \"git\" } : undefined;\n};\n\n/**\n * Takes back the latest migration: its SQL leaves the directory, and the\n * journal and the snapshot are what they were before it was generated. Only\n * for a migration no database has applied; the CLI checks the configured one.\n * With the files already removed by hand, it puts the snapshot back.\n */\nexport const discardMigration = async (\n options: DiscardMigrationOptions,\n): Promise<DiscardedMigration> => {\n const directory = resolve(options.directory);\n\n return withGenerationLock(directory, async () => {\n const state = await readMigrationState(directory, {\n snapshotMismatch: \"keep\",\n });\n const latest = state.migrations.at(-1);\n\n // A migration removed by hand left a snapshot of what it made.\n if (state.mismatch) {\n if (options.id !== undefined) {\n throw new Error(\n `symmetria: ${join(directory, \"meta\", \"snapshot.json\")} does not match the journal, so \"${options.id}\" cannot be discarded; run discard without an ID to put the snapshot back first`,\n );\n }\n\n const expected = latest?.manifest.after ?? snapshotHash(emptySnapshot());\n const found = await knownSnapshot(directory, expected, state.undo);\n\n if (!found) {\n throw new Error(\n `symmetria: the snapshot after ${latest ? `\"${latest.id}\"` : \"an empty chain\"} is not in the journal or in the Git history of ${join(directory, \"meta\", \"snapshot.json\")}; restore that file from a backup`,\n );\n }\n\n await writeMigrationFiles(\n directory,\n { snapshot: found.snapshot },\n state.migrations.map((entry) => entry.manifest),\n );\n\n return { source: found.source };\n }\n\n if (!latest) {\n throw new Error(\"symmetria: there is no migration to discard\");\n }\n\n if (options.id !== undefined && options.id !== latest.id) {\n throw new Error(\n `symmetria: only the latest migration can be discarded; it is \"${latest.id}\", not \"${options.id}\"`,\n );\n }\n\n if (\n !options.allowEdited &&\n latest.manifest.generated !== undefined &&\n latest.manifest.generated !== sqlChecksum(latest.up)\n ) {\n throw new Error(\n `symmetria: ${latest.id}/up.sql was edited after it was generated; discard would lose the edits, so it needs --force (allowEdited)`,\n );\n }\n\n const found = await knownSnapshot(\n directory,\n latest.manifest.before,\n state.undo?.migration === latest.id ? state.undo : undefined,\n );\n\n if (!found) {\n throw new Error(\n `symmetria: the snapshot before \"${latest.id}\" is not in the journal or in the Git history of ${join(directory, \"meta\", \"snapshot.json\")}; restore that file as it was before the migration was generated, then delete the \"${latest.id}\" directory and its journal entry`,\n );\n }\n\n await writeMigrationFiles(\n directory,\n { snapshot: found.snapshot },\n state.migrations.slice(0, -1).map((entry) => entry.manifest),\n [latest.id],\n );\n\n return { id: latest.id, source: found.source };\n });\n};\n","/**\n * Lints migration SQL for statements that lock or rewrite large tables, anonymous constraints and\n * volatile defaults, with safer rewrites. Every ALTER TABLE action is reviewed on its own, and\n * comments, string literals and function bodies never take part in the classification.\n */\nimport { parseMigrationSQL } from \"./sql\";\nimport type { LintFinding } from \"./lint\";\n\nexport type SQLFinding = LintFinding & { readonly statement: number };\n\nconst IDENTIFIER = String.raw`(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)`;\nconst TABLE_NAME = String.raw`(${IDENTIFIER}(?:\\s*\\.\\s*${IDENTIFIER})?)`;\nconst CREATED_TABLE = new RegExp(\n String.raw`^\\s*CREATE\\s+(?:(?:GLOBAL\\s+|LOCAL\\s+)?(?:TEMP|TEMPORARY|UNLOGGED)\\s+)?TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${TABLE_NAME}`,\n \"i\",\n);\nconst TARGET_TABLE = new RegExp(\n String.raw`^\\s*(?:CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+(?:CONCURRENTLY\\s+)?(?:(?:IF\\s+NOT\\s+EXISTS\\s+)?${IDENTIFIER}\\s+)?ON\\s+(?:ONLY\\s+)?|ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?)${TABLE_NAME}`,\n \"i\",\n);\nconst ALTER_TABLE = new RegExp(\n String.raw`^\\s*ALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?${TABLE_NAME}\\s*\\*?\\s*([\\s\\S]*)$`,\n \"i\",\n);\nconst CREATED_INDEX = new RegExp(\n String.raw`^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(${IDENTIFIER})\\s+ON\\b`,\n \"i\",\n);\nconst DROPPED_INDEX = new RegExp(\n String.raw`^\\s*DROP\\s+INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+EXISTS\\s+)?(${IDENTIFIER}(?:\\s*\\.\\s*${IDENTIFIER})?)\\s*(?:CASCADE|RESTRICT)?\\s*$`,\n \"i\",\n);\nconst RENAME = /^RENAME\\b/i;\nconst RENAMED_OBJECT = new RegExp(\n String.raw`^\\s*ALTER\\s+(?:INDEX|TYPE)\\s+(?:IF\\s+EXISTS\\s+)?${TABLE_NAME}\\s+RENAME\\b`,\n \"i\",\n);\nconst NAMED_CONSTRAINT = new RegExp(\n String.raw`^ADD\\s+CONSTRAINT\\s+(${IDENTIFIER})`,\n \"i\",\n);\nconst DROPPED_CONSTRAINT = new RegExp(\n String.raw`^DROP\\s+CONSTRAINT\\s+(?:IF\\s+EXISTS\\s+)?(${IDENTIFIER})\\s*(?:CASCADE|RESTRICT)?\\s*$`,\n \"i\",\n);\nconst ADDED_COLUMN = new RegExp(\n String.raw`^ADD\\s+(?:COLUMN\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(${IDENTIFIER})\\s+([\\s\\S]*)$`,\n \"i\",\n);\nconst ALTERED_COLUMN = new RegExp(\n String.raw`^ALTER\\s+(?:COLUMN\\s+)?(${IDENTIFIER})\\s+([\\s\\S]*)$`,\n \"i\",\n);\nconst KEY_COLUMNS = /\\b(?:PRIMARY\\s+KEY|UNIQUE|FOREIGN\\s+KEY)\\s*\\(([^)]*)\\)/i;\n// An explicit cast to a length-limited string type cuts long values instead of failing.\nconst TRUNCATING_CAST =\n /\\bUSING\\b[\\s\\S]*(?:::\\s*|\\bAS\\s+)(?:varchar|character\\s+varying|char|character|bpchar)\\s*\\(\\s*\\d+\\s*\\)/i;\n// Defaults evaluated per row: PostgreSQL 11+ stores constant and STABLE\n// defaults (now(), transaction_timestamp()) without rewriting the table.\nconst VOLATILE_DEFAULT =\n /\\bDEFAULT\\b.*\\b(?:CLOCK_TIMESTAMP|TIMEOFDAY|RANDOM|RANDOM_NORMAL|GEN_RANDOM_UUID|GEN_RANDOM_BYTES|UUIDV4|UUIDV7|UUID_GENERATE_V1|UUID_GENERATE_V1MC|UUID_GENERATE_V4|NEXTVAL)\\b/;\n\n/** An identifier the way PostgreSQL folds it: quoted names verbatim, others lower-cased. */\nconst identifierKey = (name: string): string =>\n name.startsWith('\"')\n ? name.slice(1, -1).replaceAll('\"\"', '\"')\n : name.toLowerCase();\n\n/** Normalizes a possibly qualified, possibly quoted table name the way PostgreSQL folds it. */\nconst tableKey = (name: string): string =>\n (name.match(new RegExp(IDENTIFIER, \"g\")) ?? []).map(identifierKey).join(\".\");\n\n/** The unqualified object name, for matching drops with re-creations. */\nconst objectKey = (name: string): string =>\n identifierKey(name.match(new RegExp(IDENTIFIER, \"g\"))!.at(-1)!);\n\n/** Keywords and unquoted identifiers of code whose literals are already blanked. */\nconst wordsOf = (code: string): string[] =>\n (\n code.replace(/\"(?:[^\"]|\"\")*\"/g, \" \").match(/[A-Za-z_][A-Za-z_0-9$]*/g) ?? []\n ).map((word) => word.toUpperCase());\n\n/** The comma-separated actions of an ALTER TABLE, ignoring commas inside parentheses. */\nconst splitActions = (code: string): string[] => {\n const actions: string[] = [];\n let depth = 0;\n let start = 0;\n let quoted = false;\n\n for (let position = 0; position < code.length; position++) {\n const character = code[position];\n\n if (character === '\"') {\n quoted = !quoted;\n } else if (quoted) {\n continue;\n } else if (character === \"(\") {\n depth++;\n } else if (character === \")\") {\n depth = Math.max(0, depth - 1);\n } else if (character === \",\" && !depth) {\n actions.push(code.slice(start, position).trim());\n start = position + 1;\n }\n }\n\n actions.push(code.slice(start).trim());\n\n return actions.filter(Boolean);\n};\n\nconst levelOrder = { destructive: 0, blocking: 1, caution: 2 } as const;\n\n/** Inspect the SQL that will execute, ignoring comments, strings and function bodies. */\nexport const lintMigrationSQL = (sql: string, name = \"SQL\"): SQLFinding[] => {\n const statements = parseMigrationSQL(sql);\n // Tables created earlier in the same migration are new and empty, so locks and\n // existing-row preconditions on them cannot block anything.\n const created = new Set<string>();\n // Columns added earlier without a default hold only NULL, which every foreign key accepts.\n const nullColumns = new Set<string>();\n // Columns retyped earlier: re-adding their keys and checks rebuilds what held before.\n const retyped = new Set<string>();\n // Constraints and indexes dropped earlier in this migration.\n const dropped = new Set<string>();\n // Constraints and indexes created in this migration: dropping one of them first\n // rebuilds it rather than removing it.\n const recreated = new Set(\n statements.flatMap(({ code }) => {\n const index = code.match(CREATED_INDEX)?.[1];\n const table = code.match(ALTER_TABLE);\n\n return [\n ...(index ? [objectKey(index)] : []),\n ...(table\n ? splitActions(table[2]!).flatMap((action) => {\n const constraint = action.match(NAMED_CONSTRAINT)?.[1];\n\n return constraint ? [objectKey(constraint)] : [];\n })\n : []),\n ];\n }),\n );\n\n return statements.flatMap(({ words, code }, position): SQLFinding[] => {\n const text = words.join(\" \");\n const createdTable = code.match(CREATED_TABLE)?.[1];\n\n if (createdTable) {\n created.add(tableKey(createdTable));\n }\n\n const target = code.match(TARGET_TABLE)?.[1];\n const table = target === undefined ? undefined : tableKey(target);\n const newTable = table !== undefined && created.has(table);\n const column = (name: string) => `${table}.${identifierKey(name)}`;\n\n const finding = (\n level: SQLFinding[\"level\"],\n message: string,\n advice: string,\n ): SQLFinding => ({\n level,\n table: name,\n statement: position + 1,\n message: `Statement ${position + 1}: ${message}`,\n advice,\n });\n\n const rebuild = finding(\n \"caution\",\n \"Rebuilds a constraint or index that this migration creates again.\",\n \"The rebuild scans the table under a lock; on large tables prefer a rename or a concurrent build.\",\n );\n const destructive = finding(\n \"destructive\",\n \"Removes data or a database object.\",\n \"Review the exact SQL and deploy dependent application changes first.\",\n );\n const review = finding(\n \"caution\",\n \"Contains a schema change, data operation or executable SQL requiring review.\",\n \"Verify locks, data preconditions and the upgrade against representative data. SQL lint does not analyze function bodies.\",\n );\n const unique = finding(\n \"blocking\",\n \"Requires unique existing values.\",\n \"Check and resolve duplicates before applying.\",\n );\n\n /** A key or check dropped earlier and added again after its columns changed type. */\n const rebuiltAfterRetype = (\n constraint: string | undefined,\n keys: string[] | undefined,\n ): boolean =>\n constraint !== undefined &&\n dropped.has(objectKey(constraint)) &&\n (keys\n ? keys.length > 0 && keys.every((key) => retyped.has(column(key)))\n : [...retyped].some((key) => key.startsWith(`${table}.`)));\n\n const alteration = code.match(ALTER_TABLE);\n const actions = alteration ? splitActions(alteration[2]!) : [];\n\n // Renames change the catalog only, under a brief ACCESS EXCLUSIVE lock. The\n // action itself has to be RENAME: a table or column may be called `rename`.\n if (\n RENAMED_OBJECT.test(code) ||\n (actions.length > 0 && actions.every((action) => RENAME.test(action)))\n ) {\n return [];\n }\n\n if (alteration) {\n const findings = actions.flatMap((action): SQLFinding[] => {\n const actionWords = wordsOf(action);\n const actionText = actionWords.join(\" \");\n const droppedConstraint = action.match(DROPPED_CONSTRAINT)?.[1];\n\n if (droppedConstraint !== undefined) {\n dropped.add(objectKey(droppedConstraint));\n\n return recreated.has(objectKey(droppedConstraint))\n ? [rebuild]\n : [destructive];\n }\n\n if (/\\bDROP(?:$| (?!DEFAULT\\b|NOT\\b|IDENTITY\\b))/.test(actionText)) {\n return [destructive];\n }\n\n const altered = action.match(ALTERED_COLUMN);\n const alteredText = altered ? wordsOf(altered[2]!).join(\" \") : \"\";\n const retypes = /^(?:SET DATA )?TYPE\\b/.test(alteredText);\n\n if (retypes) {\n retyped.add(column(altered![1]!));\n }\n\n if (retypes && TRUNCATING_CAST.test(altered![2]!)) {\n return [\n finding(\n \"destructive\",\n \"USING casts explicitly to a length-limited string type, which cuts longer values instead of failing.\",\n \"Leave USING out (or cast to text) so PostgreSQL refuses values that do not fit, unless the column only gets longer.\",\n ),\n ];\n }\n\n if (newTable) {\n return [];\n }\n\n if (/^SET NOT NULL\\b/.test(alteredText)) {\n return [\n finding(\n \"blocking\",\n \"Requires non-null values in existing rows.\",\n \"Backfill first, then validate the constraint.\",\n ),\n ];\n }\n\n if (retypes) {\n return [\n finding(\n \"caution\",\n \"Changing a column type rewrites the table under an ACCESS EXCLUSIVE lock unless the cast is binary-coercible.\",\n \"Expect downtime proportional to table size; for large tables add a new column, backfill and switch.\",\n ),\n ];\n }\n\n // A column default applies to future rows only: a catalog change.\n if (/^(?:SET|DROP) DEFAULT\\b/.test(alteredText)) {\n return [];\n }\n\n if (!/^ADD\\b/.test(actionText)) {\n return [review];\n }\n\n // Table constraints may be named (ADD CONSTRAINT …) or anonymous\n // (ADD PRIMARY KEY …); everything else adds a column.\n if (\n /^ADD (?:CONSTRAINT|PRIMARY KEY|UNIQUE|CHECK|FOREIGN KEY|EXCLUDE)\\b/.test(\n actionText,\n )\n ) {\n const constraint = action.match(NAMED_CONSTRAINT)?.[1];\n const keys =\n action\n .match(KEY_COLUMNS)?.[1]!\n .match(new RegExp(IDENTIFIER, \"g\")) ?? undefined;\n\n if (/\\b(?:UNIQUE|PRIMARY KEY)\\b/.test(actionText)) {\n if (/\\bUSING INDEX\\b/.test(actionText)) {\n return [review];\n }\n\n return rebuiltAfterRetype(constraint, keys ?? [])\n ? [\n finding(\n \"caution\",\n \"Rebuilds a key dropped earlier in this migration after its columns change type.\",\n \"The rebuild scans the table under an ACCESS EXCLUSIVE lock; it fails only if the conversion makes existing values collide.\",\n ),\n ]\n : [unique];\n }\n\n const foreign = /\\bFOREIGN KEY\\b/.test(actionText);\n\n if (\n /\\bNOT VALID\\b/.test(actionText) ||\n (foreign &&\n !!keys?.length &&\n keys.every((key) => nullColumns.has(column(key))))\n ) {\n return [review];\n }\n\n if (foreign || /\\bCHECK\\b/.test(actionText)) {\n return rebuiltAfterRetype(constraint, foreign ? keys : undefined)\n ? [rebuild]\n : [\n finding(\n \"blocking\",\n `Adds a ${foreign ? \"foreign key\" : \"CHECK constraint\"} that validates every existing row under a lock; the statement fails when a row violates it.`,\n \"Add it NOT VALID, then run VALIDATE CONSTRAINT in a later statement or migration, which takes a lighter lock.\",\n ),\n ];\n }\n\n return [review];\n }\n\n const added = action.match(ADDED_COLUMN);\n const definition = added ? wordsOf(added[2]!).join(\" \") : actionText;\n\n if (\n /\\bNOT NULL\\b/.test(definition) &&\n !/\\bDEFAULT\\b/.test(definition)\n ) {\n return [\n finding(\n \"blocking\",\n \"Requires non-null values in existing rows.\",\n \"Backfill first, then validate the constraint.\",\n ),\n ];\n }\n\n if (\n /\\b(?:GENERATED\\b.*\\b(?:IDENTITY|STORED)|(?:SMALL|BIG)?SERIAL)\\b/.test(\n definition,\n )\n ) {\n return [\n finding(\n \"caution\",\n \"An identity, serial or stored generated column rewrites every existing row.\",\n \"Add a plain column, backfill in batches, then attach the identity or expression.\",\n ),\n ];\n }\n\n if (VOLATILE_DEFAULT.test(definition)) {\n return [\n finding(\n \"caution\",\n \"A volatile default rewrites every existing row.\",\n \"Add the column without the default, backfill in batches, then set the default.\",\n ),\n ];\n }\n\n if (/\\b(?:UNIQUE|PRIMARY KEY)\\b/.test(definition)) {\n return /\\bDEFAULT\\b/.test(definition) ? [unique] : [];\n }\n\n if (added && !/\\bDEFAULT\\b/.test(definition)) {\n nullColumns.add(column(added[1]!));\n }\n\n return [];\n });\n\n return findings\n .filter(\n (entry, index) =>\n findings.findIndex(\n (other) =>\n other.level === entry.level && other.message === entry.message,\n ) === index,\n )\n .sort(\n (left, right) => levelOrder[left.level] - levelOrder[right.level],\n );\n }\n\n const droppedIndex = code.match(DROPPED_INDEX)?.[1];\n\n if (droppedIndex !== undefined) {\n dropped.add(objectKey(droppedIndex));\n\n return recreated.has(objectKey(droppedIndex)) ? [rebuild] : [destructive];\n }\n\n if (\n /^(DROP|TRUNCATE|DELETE)\\b/.test(text) ||\n /^(?:WITH|MERGE)\\b.*\\bDELETE\\b/.test(text)\n ) {\n return [destructive];\n }\n\n if (newTable) {\n return [];\n }\n\n if (/^CREATE UNIQUE INDEX\\b/.test(text)) {\n const index = code.match(CREATED_INDEX)?.[1];\n\n return index !== undefined &&\n dropped.has(objectKey(index)) &&\n [...retyped].some((key) => key.startsWith(`${table}.`))\n ? [rebuild]\n : [unique];\n }\n\n if (/^CREATE INDEX\\b/.test(text) && !words.includes(\"CONCURRENTLY\")) {\n return [\n finding(\n \"caution\",\n \"Index construction blocks writes.\",\n \"Use a dedicated nontransactional migration with CREATE INDEX CONCURRENTLY on large tables.\",\n ),\n ];\n }\n\n // A new enum label changes the catalog only; existing rows are untouched.\n if (/^ALTER TYPE\\b.*\\bADD VALUE\\b/.test(text)) {\n return [];\n }\n\n if (\n /^(ALTER|UPDATE|INSERT|DO|CALL|WITH|SELECT|MERGE)\\b/.test(text) ||\n /^CREATE (?:OR REPLACE )?(?:FUNCTION|PROCEDURE|TRIGGER|RULE)\\b/.test(text)\n ) {\n return [review];\n }\n\n if (!/^(CREATE|COMMENT|GRANT|REVOKE)\\b/.test(text)) {\n return [\n finding(\n \"caution\",\n \"SQL is outside the static migration checks.\",\n \"Review this statement and exercise it with verify.\",\n ),\n ];\n }\n\n return [];\n });\n};\n","/**\n * Executes migration SQL: splits statements into steps, runs them in a transaction with advisory locking,\n * and wraps failures with SQLSTATE details.\n */\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { normalizeResult } from \"symmetria/internal\";\nimport { sqlState, type QueryExecutor } from \"symmetria\";\nimport type {\n Driver,\n SessionDriver,\n TransactionDriver,\n} from \"symmetria/driver\";\nimport type { Migration } from \"./files\";\nimport { parseMigrationSQL, splitMigrationSQL } from \"./sql\";\n\nexport type ExecutionOptions = {\n advisoryLockTimeoutMs?: number;\n lockTimeoutMs?: number;\n statementTimeoutMs?: number;\n signal?: AbortSignal;\n onEvent?: (event: MigrationEvent) => void;\n};\nexport type MigrationEvent = {\n type: \"statement-start\" | \"statement-end\" | \"statement-error\";\n migration: string;\n direction: \"up\" | \"down\";\n statement: number;\n sql: string;\n durationMs?: number;\n sqlState?: string;\n};\nexport type ExecutionStep = {\n id: string;\n transaction: \"batch\" | \"each\" | \"none\";\n group: number;\n statements: string[];\n};\n\n/** ALTER TYPE … ADD VALUE: the new label cannot be used until the transaction commits. */\nconst addsEnumLabel = (words: readonly string[]): boolean =>\n words[0] === \"ALTER\" &&\n words[1] === \"TYPE\" &&\n words.some(\n (word, position) => word === \"ADD\" && words[position + 1] === \"VALUE\",\n );\n\nconst NAME = String.raw`(?:\"|[A-Z_][A-Z_0-9$]*)`;\nconst NONTRANSACTIONAL = [\n /^CREATE (?:UNIQUE )?INDEX CONCURRENTLY(?: |$)/,\n /^DROP INDEX CONCURRENTLY(?: |$)/,\n // REINDEX (VERBOSE, CONCURRENTLY) … and REINDEX TABLE CONCURRENTLY …\n /^REINDEX \\( (?:[^)]* , )?CONCURRENTLY(?! (?:FALSE|OFF) )/,\n /^REINDEX (?:\\( [^)]*\\) )?(?:INDEX|TABLE|SCHEMA|DATABASE|SYSTEM) CONCURRENTLY(?: |$)/,\n new RegExp(\n String.raw`^ALTER TABLE .* DETACH PARTITION ${NAME}(?: \\. ${NAME})* CONCURRENTLY$`,\n ),\n /^VACUUM(?: |$)/,\n /^(?:CREATE|DROP) (?:DATABASE|TABLESPACE) /,\n /^ALTER SYSTEM /,\n];\n\n/**\n * A statement PostgreSQL refuses inside a transaction block. The keyword has\n * to stand where the grammar puts it: a column, table or index may be called\n * `concurrently`, and REFRESH MATERIALIZED VIEW CONCURRENTLY runs in a\n * transaction. `code` is a statement without comments and string literals.\n */\nconst nontransactional = (code: string): boolean => {\n // Quoted identifiers become a bare `\"`, so no name reads as a keyword.\n const text = (code.match(/\"(?:[^\"]|\"\")*\"|[A-Za-z_][\\w$]*|[().,]/g) ?? [])\n .map((token) => (token.startsWith('\"') ? '\"' : token.toUpperCase()))\n .join(\" \");\n\n return NONTRANSACTIONAL.some((pattern) => pattern.test(text));\n};\n\n/**\n * Adjacent batch migrations share one transaction, except that a migration\n * adding enum labels ends its group: PostgreSQL refuses a label in the\n * transaction that added it (SQLSTATE 55P04), and the next migration may use it.\n */\nexport const executionPlan = (\n migrations: Migration[],\n direction: \"up\" | \"down\",\n): ExecutionStep[] => {\n let group = 0;\n let previous = \"\";\n let labelsAdded = false;\n\n return migrations.map((migration) => {\n const transaction = migration.manifest.transaction ?? \"batch\";\n\n if (transaction !== \"batch\" || previous !== \"batch\" || labelsAdded) {\n group++;\n }\n\n previous = transaction;\n const parsed = parseMigrationSQL(migration[direction]);\n const statements = parsed.map((statement) => statement.sql);\n labelsAdded = parsed.some(({ words }) => addsEnumLabel(words));\n\n if (\n transaction !== \"none\" &&\n parsed.some(({ code }) => nontransactional(code))\n ) {\n throw new Error(\n `symmetria: migration \"${migration.id}\" requires transaction: \"none\"`,\n );\n }\n\n return { id: migration.id, transaction, group, statements };\n });\n};\n\nexport { sqlState };\n\n/** PostgreSQL's DETAIL or HINT field, as both drivers expose it. */\nconst serverField = (\n cause: unknown,\n field: \"detail\" | \"hint\",\n): string | undefined => {\n const value =\n cause && typeof cause === \"object\"\n ? (cause as Record<string, unknown>)[field]\n : undefined;\n\n return typeof value === \"string\" && value ? value : undefined;\n};\n\nexport class MigrationExecutionError extends Error {\n readonly migration: string;\n readonly direction: \"up\" | \"down\";\n readonly statement: number;\n readonly sql: string;\n readonly sqlState: string | undefined;\n /** PostgreSQL's DETAIL, such as which key value was duplicated. */\n readonly detail: string | undefined;\n constructor(\n migration: string,\n direction: \"up\" | \"down\",\n statement: number,\n sql: string,\n cause: unknown,\n ) {\n const state = sqlState(cause);\n const detail = serverField(cause, \"detail\");\n const hint = serverField(cause, \"hint\");\n super(\n `symmetria: migration \"${migration}\" failed (${direction}, statement ${statement}${state ? `, SQLSTATE ${state}` : \"\"}): ${cause instanceof Error ? cause.message : String(cause)}${detail ? `\\nDETAIL: ${detail}` : \"\"}${hint ? `\\nHINT: ${hint}` : \"\"}\\n\\nSQL:\\n${sql}`,\n { cause },\n );\n this.name = \"MigrationExecutionError\";\n this.migration = migration;\n this.direction = direction;\n this.statement = statement;\n this.sql = sql;\n this.sqlState = state;\n this.detail = detail;\n }\n}\n\nexport const executeSQL = async (\n executor: QueryExecutor,\n sql: string,\n parameters: unknown[] = [],\n signal?: AbortSignal,\n) => {\n signal?.throwIfAborted();\n const result = normalizeResult(await executor({ sql, parameters }));\n signal?.throwIfAborted();\n\n return result;\n};\n\nexport const applyStatements = async (\n executor: QueryExecutor,\n migration: Migration,\n direction: \"up\" | \"down\",\n options: ExecutionOptions,\n completed?: (statement: number) => Promise<void>,\n): Promise<void> => {\n for (const [position, sql] of splitMigrationSQL(\n migration[direction],\n ).entries()) {\n const event = {\n migration: migration.id,\n direction,\n statement: position + 1,\n sql,\n };\n const started = performance.now();\n options.onEvent?.({ ...event, type: \"statement-start\" });\n\n try {\n await executeSQL(executor, sql, [], options.signal);\n await completed?.(position + 1);\n } catch (cause) {\n const error = new MigrationExecutionError(\n migration.id,\n direction,\n position + 1,\n sql,\n cause,\n );\n options.onEvent?.({\n ...event,\n type: \"statement-error\",\n durationMs: performance.now() - started,\n ...(error.sqlState ? { sqlState: error.sqlState } : {}),\n });\n throw error;\n }\n\n options.onEvent?.({\n ...event,\n type: \"statement-end\",\n durationMs: performance.now() - started,\n });\n }\n\n options.signal?.throwIfAborted();\n};\n\n/**\n * Where the runner works: transactions that hold the migration lock and, on a\n * driver with sessions, the pinned session that nontransactional migrations need.\n */\nexport type MigrationConnection = {\n /**\n * Runs `callback` in a READ COMMITTED transaction that holds the migration\n * lock. A session driver keeps one session lock across these transactions;\n * a transaction-only driver takes a transaction-level lock in each one, so\n * another runner can commit between two of them.\n */\n readonly transaction: <Result>(\n callback: (tx: TransactionDriver) => Promise<Result>,\n ) => Promise<Result>;\n /** The pinned session for `transaction: \"none\"` migrations; absent on transaction-only drivers. */\n readonly session?: SessionDriver;\n /** The driver has sessions, but its connection pools transactions, so they cannot pin a server. */\n readonly pooled?: boolean;\n};\n\n/**\n * The statement timeout when none is configured. It guards transactions, which\n * hold their locks until they end; the runner lifts it for the statements of a\n * `transaction: \"none\"` migration.\n */\nexport const DEFAULT_STATEMENT_TIMEOUT_MS = 600000;\n\nconst LOCK_SETTINGS =\n \"SELECT set_config('lock_timeout', $1, $4), set_config('statement_timeout', $2, $4), set_config('standard_conforming_strings', $3, $4)\";\n\n/** How long the pooling check waits for a second pool connection to answer. */\nconst POOLING_PROBE_TIMEOUT_MS = 1000;\n\nconst POOLED = Symbol(\"symmetria.pooled\");\n\nconst backendPid = async (\n execute: QueryExecutor,\n signal?: AbortSignal,\n): Promise<number> =>\n Number(\n (await executeSQL(execute, \"SELECT pg_backend_pid() AS pid\", [], signal))\n .rows[0]!.pid,\n );\n\n/**\n * The server process a session runs on, or undefined when the connection pools\n * transactions (PgBouncer with pool_mode=transaction, for example): then one\n * client connection's statements move between server processes and two client\n * connections share one, so a session lock or setting protects nothing. A\n * direct or session-pooled connection never does either. The second client\n * connection comes from the driver's pool. A pool with no free connection\n * (`max: 1`) cannot answer, and a session alone cannot tell: a pooler hands a\n * lone client the same server every time. Such a session counts as unpinned,\n * so the lock is taken per transaction, which is safe either way.\n */\nconst pinnedBackend = async (\n driver: Driver,\n session: SessionDriver,\n signal?: AbortSignal,\n): Promise<number | undefined> => {\n const first = await backendPid(session.execute, signal);\n let latest = first;\n\n // Other clients of a busy pooler can take the free server between two\n // statements and hide it once; three rounds make that unlikely.\n for (let round = 0; round < 3; round++) {\n const timer = new AbortController();\n const other = await Promise.race([\n backendPid(driver.execute).catch(() => undefined),\n delay(POOLING_PROBE_TIMEOUT_MS, undefined, {\n signal: timer.signal,\n }).catch(() => undefined),\n ]);\n timer.abort();\n const next = await backendPid(session.execute, signal);\n\n if (next !== first || other === latest || other === next) {\n return undefined;\n }\n\n if (other === undefined) {\n return undefined;\n }\n\n latest = next;\n }\n\n return first;\n};\n\n/** A session transaction must run on the session's server process, which holds the lock. */\nconst assertPinned = async (\n execute: QueryExecutor,\n pid: number,\n): Promise<void> => {\n const current = await backendPid(execute);\n\n if (current !== pid) {\n throw new Error(\n `symmetria: the migration session moved from PostgreSQL process ${pid} to ${current}: this connection pools transactions (such as PgBouncer with pool_mode=transaction), which cannot hold the migration's session lock. Migrate over a direct or session-pooled connection`,\n );\n }\n};\n\n/**\n * Session locks survive commits, so a session driver locks once. A driver that\n * only offers whole transactions locks each transaction with\n * pg_advisory_xact_lock and the same timeouts, so every driver gets the same\n * transaction boundaries. A session driver whose connection pools transactions\n * works like a transaction-only driver, since its sessions cannot hold a lock.\n */\nexport const withMigrationConnection = async <Result>(\n driver: Driver,\n lock: string,\n options: ExecutionOptions,\n callback: (connection: MigrationConnection) => Promise<Result>,\n): Promise<Result> => {\n const advisory = options.advisoryLockTimeoutMs ?? 10000;\n const ddl = options.lockTimeoutMs ?? 5000;\n const statement = options.statementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS;\n\n for (const value of [advisory, ddl, statement]) {\n if (!Number.isSafeInteger(value) || value < 0 || value > 2147483647) {\n throw new Error(\n \"symmetria: migration timeouts must be integers between 0 and 2147483647 milliseconds\",\n );\n }\n }\n\n /** Tries the advisory lock until it is free or the advisory timeout passes. */\n const acquire = async (\n execute: QueryExecutor,\n scope: \"session\" | \"transaction\",\n attempted?: () => void,\n ): Promise<void> => {\n const started = performance.now();\n\n while (true) {\n options.signal?.throwIfAborted();\n attempted?.();\n const acquired = await executeSQL(\n execute,\n `SELECT pg_try_advisory_${scope === \"transaction\" ? \"xact_\" : \"\"}lock(1937339476, hashtext($1)) AS locked`,\n [lock],\n options.signal,\n );\n\n if (acquired.rows[0]?.locked) {\n return;\n }\n\n if (performance.now() - started >= advisory) {\n throw new Error(\n `symmetria: migration advisory lock timeout after ${advisory}ms`,\n );\n }\n\n // An abort during the wait reports the signal's reason, not AbortError.\n await delay(\n Math.min(50, advisory),\n undefined,\n options.signal ? { signal: options.signal } : {},\n ).catch((error: unknown) => {\n options.signal?.throwIfAborted();\n throw error;\n });\n }\n };\n\n if (driver.session) {\n const outcome = await driver.session<Result | typeof POOLED>(\n async (session) => {\n options.signal?.throwIfAborted();\n const pid = await pinnedBackend(driver, session, options.signal);\n\n if (pid === undefined) {\n return POOLED;\n }\n\n let cancellation: Promise<void> | undefined;\n\n const abort = () => {\n cancellation = session.cancel?.();\n void cancellation?.catch(() => {});\n };\n\n options.signal?.addEventListener(\"abort\", abort, { once: true });\n let original: Record<string, unknown> | undefined;\n let lockAttempted = false;\n let moved = false;\n\n /**\n * Releases the session lock. After the session moved to another server\n * process (a pooler the check missed), an unlock can reach a process\n * that does not hold it, so it is repeated until one does, briefly.\n */\n const release = async () => {\n for (let attempt = 0; attempt < 50; attempt++) {\n const { rows } = await executeSQL(\n session.execute,\n \"SELECT pg_advisory_unlock(1937339476, hashtext($1)) AS released\",\n [lock],\n );\n\n if (rows[0]?.released || !moved) {\n return;\n }\n\n await delay(10);\n }\n };\n\n try {\n original = (\n await executeSQL(\n session.execute,\n \"SELECT current_setting('lock_timeout') AS lock_timeout, current_setting('statement_timeout') AS statement_timeout, current_setting('standard_conforming_strings') AS strings\",\n )\n ).rows[0]!;\n await acquire(session.execute, \"session\", () => {\n lockAttempted = true;\n });\n await executeSQL(session.execute, LOCK_SETTINGS, [\n `${ddl}ms`,\n `${statement}ms`,\n \"on\",\n false,\n ]);\n\n return await callback({\n transaction: (work) =>\n session.transaction(\n async (tx) => {\n try {\n await assertPinned(tx.execute, pid);\n } catch (error) {\n moved = true;\n throw error;\n }\n\n return work(tx);\n },\n { isolationLevel: \"read committed\" },\n ),\n session,\n });\n } finally {\n options.signal?.removeEventListener(\"abort\", abort);\n await cancellation?.catch(() => {});\n\n try {\n if (original) {\n await executeSQL(\n session.execute,\n \"SELECT set_config('lock_timeout', $1, false), set_config('statement_timeout', $2, false), set_config('standard_conforming_strings', $3, false)\",\n [\n original.lock_timeout,\n original.statement_timeout,\n original.strings,\n ],\n );\n }\n } finally {\n // A cancellation can arrive after PostgreSQL acquires the lock but\n // before its result reaches us. Release even when acquisition is uncertain.\n if (lockAttempted) {\n await release();\n }\n }\n }\n },\n );\n\n if (outcome !== POOLED) {\n return outcome as Result;\n }\n }\n\n if (!driver.transaction) {\n throw new Error(\n \"symmetria: migrations require a transaction-capable driver\",\n );\n }\n\n return callback({\n transaction: (work) =>\n driver.transaction!(\n async (tx) => {\n options.signal?.throwIfAborted();\n // Released at commit or rollback, like the settings.\n await acquire(tx.execute, \"transaction\");\n await executeSQL(tx.execute, LOCK_SETTINGS, [\n `${ddl}ms`,\n `${statement}ms`,\n \"on\",\n true,\n ]);\n\n return work(tx);\n },\n { isolationLevel: \"read committed\" },\n ),\n ...(driver.session ? { pooled: true } : {}),\n });\n};\n","/**\n * The migrator: applies and rolls back migrations against a database, tracking status in the migrations table.\n */\nimport { quoteIdentifier } from \"symmetria/internal\";\nimport { sqlState, type QueryExecutor } from \"symmetria\";\nimport type { Driver } from \"symmetria/driver\";\nimport {\n checksumMatches,\n loadMigrationState,\n type Migration,\n type MigrationState,\n} from \"./files\";\nimport { detectDrift, formatDriftFindings } from \"./drift\";\nimport {\n emptySnapshot,\n snapshotHash,\n type MigrationSnapshot,\n} from \"./snapshot\";\nimport {\n applyStatements,\n DEFAULT_STATEMENT_TIMEOUT_MS,\n executeSQL,\n executionPlan,\n withMigrationConnection,\n type ExecutionOptions,\n type MigrationConnection,\n type ExecutionStep,\n} from \"./execution\";\nimport { verifyBoundary } from \"./verify\";\n\nexport type MigratorOptions = ExecutionOptions & {\n driver: Driver;\n directory: string;\n metadataSchema?: string;\n metadataTable?: string;\n /** Administrative URL used only to create disposable databases for historical verification. */\n verificationDatabaseUrl?: string;\n /** Undeclared tables that adoption and repair leave out of their schema comparison. */\n ignoreTables?: readonly string[];\n};\nexport type MigrationStatus = {\n id: string;\n status: \"applied\" | \"pending\" | \"incomplete\";\n appliedAt?: Date;\n direction?: \"up\" | \"down\";\n statement?: number;\n error?: string;\n};\ntype HistoryEntry = {\n id: string;\n checksum: string;\n snapshotHash: string;\n appliedAt: Date;\n state: \"applied\" | \"incomplete\";\n direction: \"up\" | \"down\";\n statement: number;\n error?: string;\n};\n\n/** Journal columns added after the first release; older journals gain them once. */\nconst JOURNAL_COLUMNS: Readonly<Record<string, string>> = {\n state: \"text NOT NULL DEFAULT 'applied'\",\n direction: \"text NOT NULL DEFAULT 'up'\",\n statement: \"integer NOT NULL DEFAULT 0\",\n error: \"text\",\n};\n/** How long status waits for a lock on the journal before reporting it as busy. */\nconst STATUS_LOCK_TIMEOUT_MS = 2000;\n\n/** Names the migrations whose identical schema hash makes a baseline ambiguous. */\nconst ambiguousBaseline = (migrations: readonly Migration[]): Error =>\n new Error(\n `symmetria: the database schema matches multiple local migrations (${migrations.map((migration) => migration.id).join(\", \")}); migrations that change only data cannot be told apart by schema, so choose the baseline with --to <id> (adopt({ to }) in the API)`,\n );\n\nexport const migrator = (options: MigratorOptions) => {\n const metadataSchema = options.metadataSchema ?? \"public\";\n const metadataTable = options.metadataTable ?? \"_symmetria_migrations\";\n const qualifiedName = `${quoteIdentifier(metadataSchema)}.${quoteIdentifier(metadataTable)}`;\n const lockName = `symmetria:migrations:${qualifiedName}`;\n\n const connection = <Result>(\n callback: (connection: MigrationConnection) => Promise<Result>,\n ) => withMigrationConnection(options.driver, lockName, options, callback);\n\n /**\n * Creates the journal, or adds columns an older journal lacks. The catalog is\n * read first: ALTER TABLE takes an ACCESS EXCLUSIVE lock until commit even when\n * every column exists, which would block status for the whole migration.\n */\n const ensureJournal = async (execute: QueryExecutor): Promise<void> => {\n const present = (\n await executeSQL(\n execute,\n `SELECT attribute.attname AS name FROM pg_attribute attribute WHERE attribute.attrelid = to_regclass($1) AND attribute.attnum > 0 AND NOT attribute.attisdropped`,\n [qualifiedName],\n )\n ).rows.map((row) => String(row.name));\n\n if (present.length) {\n const missing = Object.entries(JOURNAL_COLUMNS).filter(\n ([name]) => !present.includes(name),\n );\n\n if (missing.length) {\n await executeSQL(\n execute,\n `ALTER TABLE ${qualifiedName} ${missing.map(([name, definition]) => `ADD COLUMN IF NOT EXISTS ${name} ${definition}`).join(\", \")}`,\n );\n }\n\n return;\n }\n\n const namespace = await executeSQL(\n execute,\n \"SELECT 1 FROM pg_namespace WHERE nspname = $1\",\n [metadataSchema],\n );\n\n if (!namespace.rows.length) {\n await executeSQL(\n execute,\n `CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(metadataSchema)}`,\n );\n }\n\n await executeSQL(\n execute,\n `CREATE TABLE IF NOT EXISTS ${qualifiedName} (id text PRIMARY KEY, checksum text NOT NULL, snapshot_hash text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp(), ${Object.entries(\n JOURNAL_COLUMNS,\n )\n .map(([name, definition]) => `${name} ${definition}`)\n .join(\", \")})`,\n );\n };\n\n const readHistory = async (\n execute: QueryExecutor,\n create: boolean,\n ): Promise<HistoryEntry[]> => {\n if (create) {\n await ensureJournal(execute);\n } else {\n const exists = await executeSQL(\n execute,\n \"SELECT to_regclass($1)::text AS name\",\n [qualifiedName],\n );\n\n if (!exists.rows[0]?.name) {\n return [];\n }\n }\n\n const result = await executeSQL(\n execute,\n `SELECT id, checksum, snapshot_hash, applied_at, to_jsonb(history)->>'state' AS state, to_jsonb(history)->>'direction' AS direction, to_jsonb(history)->>'statement' AS statement, to_jsonb(history)->>'error' AS error FROM ${qualifiedName} history ORDER BY id COLLATE \"C\"`,\n );\n\n return result.rows.map((row) => {\n const statement = Number(row.statement ?? 0);\n\n if (\n (row.state !== null &&\n ![\"applied\", \"incomplete\"].includes(String(row.state))) ||\n (row.direction !== null &&\n ![\"up\", \"down\"].includes(String(row.direction))) ||\n !Number.isSafeInteger(statement) ||\n statement < 0\n ) {\n throw new Error(\n `symmetria: invalid migration journal state at \"${row.id}\"`,\n );\n }\n\n return {\n id: String(row.id),\n checksum: String(row.checksum),\n snapshotHash: String(row.snapshot_hash),\n appliedAt: new Date(row.applied_at as string | Date),\n state: row.state === \"incomplete\" ? \"incomplete\" : \"applied\",\n direction: row.direction === \"down\" ? \"down\" : \"up\",\n statement,\n ...(row.error ? { error: String(row.error) } : {}),\n };\n });\n };\n\n const inspect = async (\n execute: QueryExecutor,\n migrations: Migration[],\n create = false,\n incomplete = false,\n ): Promise<HistoryEntry[]> => {\n const history = await readHistory(execute, create);\n\n for (const [position, entry] of history.entries()) {\n const migration = migrations[position];\n\n if (!migration || migration.id !== entry.id) {\n throw new Error(\n `symmetria: applied migration \"${entry.id}\" is missing or out of order in the local chain`,\n );\n }\n\n const edited =\n !checksumMatches(migration, entry.checksum) ||\n migration.manifest.after !== entry.snapshotHash;\n\n // An incomplete migration may be fixed in place: its files are checked\n // again when repair verifies the schema, so an edit must not lock out\n // status and repair.\n if (edited && entry.state !== \"incomplete\") {\n throw new Error(\n `symmetria: checksum mismatch for applied migration \"${entry.id}\"`,\n );\n }\n\n if (!incomplete && entry.state === \"incomplete\") {\n throw new Error(\n `symmetria: migration \"${entry.id}\" is incomplete (${entry.direction}, ${entry.statement} confirmed statements${edited ? \"; its files changed since it ran\" : \"\"}); inspect the database and use repair`,\n );\n }\n\n if (entry.state === \"incomplete\" && position !== history.length - 1) {\n throw new Error(\n `symmetria: incomplete migration \"${entry.id}\" is not the last journal entry`,\n );\n }\n }\n\n return history;\n };\n\n const targetIndex = (migrations: Migration[], to?: string): number => {\n const target =\n to === undefined\n ? migrations.length - 1\n : migrations.findIndex((migration) => migration.id === to);\n\n if (to !== undefined && target < 0) {\n throw new Error(`symmetria: unknown migration target \"${to}\"`);\n }\n\n return target;\n };\n\n const record = async (\n execute: QueryExecutor,\n migration: Migration,\n direction: \"up\" | \"down\",\n ) => {\n if (direction === \"up\") {\n await executeSQL(\n execute,\n `INSERT INTO ${qualifiedName} (id, checksum, snapshot_hash) VALUES ($1, $2, $3) ON CONFLICT (id) DO UPDATE SET checksum = EXCLUDED.checksum, snapshot_hash = EXCLUDED.snapshot_hash, state = 'applied', direction = 'up', statement = 0, error = NULL, applied_at = clock_timestamp()`,\n [migration.id, migration.checksum, migration.manifest.after],\n );\n } else {\n await executeSQL(execute, `DELETE FROM ${qualifiedName} WHERE id = $1`, [\n migration.id,\n ]);\n }\n };\n\n const checkBoundary = async (\n execute: QueryExecutor,\n state: MigrationState,\n target: number,\n snapshot?: MigrationSnapshot,\n ) => {\n const hash =\n target < 0\n ? snapshotHash(emptySnapshot())\n : state.migrations[target]!.manifest.after;\n const expected =\n snapshot ??\n (target < 0\n ? emptySnapshot()\n : hash === snapshotHash(state.snapshot)\n ? state.snapshot\n : undefined);\n\n if (expected) {\n if (snapshotHash(expected) !== hash) {\n throw new Error(\n \"symmetria: verification snapshot does not match the target migration hash; it must be the snapshot written when that migration was generated\",\n );\n }\n\n const findings = await detectDrift({\n execute,\n snapshot: expected,\n metadataSchema,\n metadataTable,\n ...(options.ignoreTables ? { ignoreTables: options.ignoreTables } : {}),\n });\n\n if (findings.length) {\n throw new Error(\n `symmetria: schema does not match the adoption/recovery target\\n${formatDriftFindings(findings)}`,\n );\n }\n } else {\n if (!options.verificationDatabaseUrl) {\n throw new Error(\n \"symmetria: this boundary is not the latest snapshot, so verifying it needs either the snapshot of that point (--snapshot <file>: meta/snapshot.json as it was at that migration, for example `git show <commit>:<dir>/meta/snapshot.json`) or a server for disposable databases (--verify-url, verificationDatabaseUrl)\",\n );\n }\n\n await verifyBoundary({\n ...options,\n execute,\n state,\n target,\n url: options.verificationDatabaseUrl,\n metadataSchema,\n metadataTable,\n });\n }\n };\n\n /**\n * Applies migrations one transactional group at a time. Each group's\n * transaction reads the journal again and asks `pending` what is left, given\n * the migrations this run already completed: a transaction-only driver\n * releases the lock between groups, so another runner may have applied or\n * reverted migrations in the meantime.\n */\n const run = async (\n link: MigrationConnection,\n migrations: Migration[],\n direction: \"up\" | \"down\",\n pending: (\n history: HistoryEntry[],\n completed: readonly string[],\n ) => Migration[],\n ): Promise<string[]> => {\n const completed: string[] = [];\n\n while (true) {\n const next = await link.transaction(async (tx) => {\n const history = await inspect(tx.execute, migrations);\n const remaining = pending(history, completed);\n\n if (!remaining.length) {\n return undefined;\n }\n\n // Created, or given the columns an older journal lacks, only when\n // there is work, so an up-to-date run leaves the journal alone.\n await ensureJournal(tx.execute);\n\n const plan = executionPlan(remaining, direction);\n\n if (!link.session && plan.some((step) => step.transaction === \"none\")) {\n const id = plan.find((step) => step.transaction === \"none\")!.id;\n\n throw new Error(\n link.pooled\n ? `symmetria: migration \"${id}\" uses transaction: \"none\", which needs one server connection for its statements and the migration lock; this connection pools transactions (such as PgBouncer with pool_mode=transaction), or its pool has a single connection, which leaves none to check that. Run it over a direct or session-pooled connection with at least two connections (max: 2)`\n : `symmetria: migration \"${id}\" uses transaction: \"none\", which needs a driver with sessions (driver.session); this driver only runs whole transactions`,\n );\n }\n\n const [first] = plan;\n\n if (first!.transaction === \"none\") {\n const migration = remaining[0]!;\n\n if (direction === \"up\") {\n await executeSQL(\n tx.execute,\n `INSERT INTO ${qualifiedName} (id, checksum, snapshot_hash, state, direction) VALUES ($1, $2, $3, 'incomplete', 'up')`,\n [migration.id, migration.checksum, migration.manifest.after],\n );\n } else {\n await executeSQL(\n tx.execute,\n `UPDATE ${qualifiedName} SET state = 'incomplete', direction = 'down', statement = 0, error = NULL WHERE id = $1`,\n [migration.id],\n );\n }\n\n return { migrations: [migration], transactional: false };\n }\n\n const group = remaining.filter(\n (_, position) => plan[position]!.group === first!.group,\n );\n\n for (const migration of group) {\n await applyStatements(tx.execute, migration, direction, options);\n await record(tx.execute, migration, direction);\n }\n\n options.signal?.throwIfAborted();\n\n return { migrations: group, transactional: true };\n });\n\n if (!next) {\n return completed;\n }\n\n if (!next.transactional) {\n // Statements of a \"none\" migration commit one by one on the session.\n const session = link.session!;\n const migration = next.migrations[0]!;\n // The default statement timeout would cancel a long CREATE INDEX\n // CONCURRENTLY and leave an invalid index behind; nothing here holds a\n // transaction open, so only a configured timeout applies.\n const statementTimeout = (milliseconds: number) =>\n options.statementTimeoutMs === undefined\n ? executeSQL(\n session.execute,\n \"SELECT set_config('statement_timeout', $1, false)\",\n [`${milliseconds}ms`],\n )\n : undefined;\n\n try {\n await statementTimeout(0);\n await applyStatements(\n session.execute,\n migration,\n direction,\n options,\n async (statement) => {\n await executeSQL(\n session.execute,\n `UPDATE ${qualifiedName} SET statement = $2 WHERE id = $1`,\n [migration.id, statement],\n );\n },\n );\n await record(session.execute, migration, direction);\n } catch (error) {\n await executeSQL(\n session.execute,\n `UPDATE ${qualifiedName} SET error = $2 WHERE id = $1`,\n [\n migration.id,\n error instanceof Error ? error.message : String(error),\n ],\n );\n throw error;\n } finally {\n // A session that failed cannot be set back, and is not used again.\n await Promise.resolve(\n statementTimeout(DEFAULT_STATEMENT_TIMEOUT_MS),\n ).catch(() => {});\n }\n }\n\n completed.push(...next.migrations.map((migration) => migration.id));\n }\n };\n\n return Object.freeze({\n status: async (): Promise<MigrationStatus[]> => {\n const { migrations } = await loadMigrationState(options.directory);\n // A read of committed journal rows: it must not wait for a running\n // migration's advisory lock, so a deploy in progress still reports. A\n // short lock_timeout turns a journal held by DDL into an error, not a hang.\n const read = (execute: QueryExecutor) =>\n inspect(execute, migrations, false, true);\n const history = await (options.driver.transaction\n ? options.driver.transaction(\n async (tx) => {\n await executeSQL(\n tx.execute,\n \"SELECT set_config('lock_timeout', $1, true)\",\n [`${STATUS_LOCK_TIMEOUT_MS}ms`],\n );\n\n return read(tx.execute);\n },\n { isolationLevel: \"read committed\", readOnly: true },\n )\n : read(options.driver.execute)\n ).catch((error: unknown) => {\n if (sqlState(error) === \"55P03\") {\n throw new Error(\n `symmetria: the migration journal ${qualifiedName} is locked by another session; status gave up after ${STATUS_LOCK_TIMEOUT_MS}ms. A migration creating or upgrading the journal holds the lock until it commits; try again when it finishes`,\n { cause: error },\n );\n }\n\n throw error;\n });\n\n return migrations.map((migration, position) => {\n const entry = history[position];\n\n return entry\n ? {\n id: migration.id,\n status: entry.state,\n appliedAt: entry.appliedAt,\n ...(entry.state === \"incomplete\"\n ? {\n direction: entry.direction,\n statement: entry.statement,\n ...(entry.error ? { error: entry.error } : {}),\n }\n : {}),\n }\n : { id: migration.id, status: \"pending\" };\n });\n },\n plan: async (\n settings: { to?: string; steps?: number; direction?: \"up\" | \"down\" } = {},\n ): Promise<ExecutionStep[]> => {\n const { migrations } = await loadMigrationState(options.directory);\n\n return connection((link) =>\n link.transaction(async (tx) => {\n const history = await inspect(tx.execute, migrations);\n const direction = settings.direction ?? \"up\";\n const steps = settings.steps ?? 1;\n\n if (\n direction === \"down\" &&\n (!Number.isSafeInteger(steps) ||\n steps < 1 ||\n steps > history.length)\n ) {\n throw new Error(\n `symmetria: invalid rollback steps: ${steps} requested, ${history.length} applied`,\n );\n }\n\n return executionPlan(\n direction === \"up\"\n ? migrations.slice(\n history.length,\n targetIndex(migrations, settings.to) + 1,\n )\n : migrations\n .slice(history.length - steps, history.length)\n .reverse(),\n direction,\n );\n }),\n );\n },\n migrate: async (settings: { to?: string } = {}): Promise<string[]> => {\n const { migrations } = await loadMigrationState(options.directory);\n const target = targetIndex(migrations, settings.to);\n\n return connection((link) =>\n run(link, migrations, \"up\", (history) =>\n migrations.slice(history.length, target + 1),\n ),\n );\n },\n rollback: async (\n settings: {\n steps?: number;\n /**\n * The migrations a plan showed, latest first. The rollback reverts\n * exactly these or nothing: if another process changed the journal in\n * between, it stops before running any SQL.\n */\n expected?: readonly string[];\n } = {},\n ): Promise<string[]> => {\n const steps = settings.steps ?? 1;\n\n if (!Number.isSafeInteger(steps) || steps < 1) {\n throw new Error(\n \"symmetria: rollback steps must be a positive safe integer\",\n );\n }\n\n const { migrations } = await loadMigrationState(options.directory);\n // Chosen from the journal the first group reads; later groups revert the\n // rest, and only while it is still the latest applied migration.\n let reverting: Migration[] | undefined;\n\n return connection((link) =>\n run(link, migrations, \"down\", (history, completed) => {\n if (!reverting) {\n if (steps > history.length && history.length) {\n throw new Error(\n `symmetria: rollback steps exceed the applied migration count: ${steps} requested, ${history.length} applied`,\n );\n }\n\n reverting = migrations\n .slice(Math.max(history.length - steps, 0), history.length)\n .reverse();\n\n const { expected } = settings;\n\n if (\n expected &&\n (expected.length !== reverting.length ||\n reverting.some(\n (migration, position) => migration.id !== expected[position],\n ))\n ) {\n throw new Error(\n `symmetria: the applied migrations changed since this rollback was planned: it was to revert ${expected.join(\", \") || \"nothing\"}, and would now revert ${reverting.map((migration) => migration.id).join(\", \") || \"nothing\"}. Nothing was rolled back; check status and run rollback again`,\n );\n }\n }\n\n const remaining = reverting.filter(\n (migration) => !completed.includes(migration.id),\n );\n\n if (remaining.length && history.at(-1)?.id !== remaining[0]!.id) {\n throw new Error(\n `symmetria: the migration journal changed during rollback: \"${history.at(-1)?.id}\" is now the latest applied migration, not \"${remaining[0]!.id}\"; check status and roll back again`,\n );\n }\n\n return remaining;\n }),\n );\n },\n adopt: async (\n settings: { to?: string; snapshot?: MigrationSnapshot } = {},\n ): Promise<string[]> => {\n const state = await loadMigrationState(options.directory);\n const { migrations } = state;\n\n return connection((link) =>\n link.transaction(async (tx) => {\n const history = await readHistory(tx.execute, true);\n\n if (history.some((entry) => entry.state === \"incomplete\")) {\n throw new Error(\n \"symmetria: repair incomplete migrations before adopting history\",\n );\n }\n\n const latest = history.at(-1);\n let target = targetIndex(migrations, settings.to);\n\n /** Local migrations that leave the schema at this hash. */\n const matchingHash = (hash: string | undefined): number[] =>\n migrations.flatMap((migration, position) =>\n migration.manifest.after === hash ? [position] : [],\n );\n\n if (settings.to === undefined && latest) {\n const matching = matchingHash(latest.snapshotHash);\n const existing = matching.find(\n (position) =>\n migrations[position]!.id === latest.id &&\n checksumMatches(migrations[position]!, latest.checksum),\n );\n\n if (existing === undefined && matching.length > 1) {\n throw ambiguousBaseline(\n matching.map((position) => migrations[position]!),\n );\n }\n\n target = existing ?? matching[0] ?? -1;\n } else if (settings.to === undefined && target >= 0) {\n // Without history the latest migration is only a guess: a data-only\n // migration (a seed, an --empty migration) leaves the same schema\n // hash as the one before it, and recording it would skip its SQL.\n const matching = matchingHash(migrations[target]!.manifest.after);\n\n if (matching.length > 1) {\n throw ambiguousBaseline(\n matching.map((position) => migrations[position]!),\n );\n }\n }\n\n if (target < 0) {\n throw new Error(\n \"symmetria: the database schema matches no local migration; choose the baseline with --to <id> (adopt({ to }) in the API)\",\n );\n }\n\n await checkBoundary(tx.execute, state, target, settings.snapshot);\n await executeSQL(tx.execute, `DELETE FROM ${qualifiedName}`);\n const adopted = migrations.slice(0, target + 1);\n\n for (const migration of adopted) {\n await record(tx.execute, migration, \"up\");\n }\n\n return adopted.map((migration) => migration.id);\n }),\n );\n },\n repair: async (settings: {\n id: string;\n action: \"retry\" | \"complete\";\n snapshot?: MigrationSnapshot;\n }): Promise<void> => {\n if (![\"retry\", \"complete\"].includes(settings.action)) {\n throw new Error(\"symmetria: repair action must be retry or complete\");\n }\n\n const state = await loadMigrationState(options.directory);\n await connection((link) =>\n link.transaction(async (tx) => {\n const history = await inspect(\n tx.execute,\n state.migrations,\n true,\n true,\n );\n const entry = history.find((entry) => entry.id === settings.id);\n\n if (\n !entry ||\n entry.state !== \"incomplete\" ||\n history.at(-1) !== entry\n ) {\n throw new Error(\n `symmetria: repair requires the last, incomplete migration; \"${settings.id}\" is ${entry ? (entry.state === \"incomplete\" ? \"not the last journal entry\" : \"applied\") : \"not in the journal\"}`,\n );\n }\n\n const index = state.migrations.findIndex(\n (migration) => migration.id === entry.id,\n );\n const applied =\n (settings.action === \"complete\") === (entry.direction === \"up\");\n await checkBoundary(\n tx.execute,\n state,\n applied ? index : index - 1,\n settings.snapshot,\n );\n await record(\n tx.execute,\n state.migrations[index]!,\n applied ? \"up\" : \"down\",\n );\n }),\n );\n },\n });\n};\n","/**\n * Replays migrations against a scratch database and compares the resulting catalog with the expected snapshot.\n */\nimport { randomUUID } from \"node:crypto\";\nimport type { QueryExecutor } from \"symmetria\";\nimport { postgres, type Driver } from \"symmetria/driver\";\nimport { quoteIdentifier } from \"symmetria/internal\";\nimport { readCatalog } from \"./catalog\";\nimport { canonicalJSON } from \"./snapshot\";\nimport { detectDrift, formatDriftFindings, undeclaredTables } from \"./drift\";\nimport { executeSQL, type ExecutionOptions } from \"./execution\";\nimport { loadMigrationState, type MigrationState } from \"./files\";\nimport { migrator } from \"./runner\";\n\nexport type VerificationContext = {\n driver: Driver;\n migration: string;\n phase: \"up\" | \"down\" | \"reapply\";\n};\nexport type VerifyOptions = ExecutionOptions & {\n directory: string;\n /** A connection with CREATEDB permission. Only newly created databases receive migration SQL. */\n url: string;\n schemaName?: string;\n metadataSchema?: string;\n metadataTable?: string;\n /**\n * Undeclared tables (other tools, extensions such as PostGIS) left out of\n * catalog comparisons; tables the latest snapshot declares are compared.\n */\n ignoreTables?: readonly string[];\n beforeMigration?: (context: VerificationContext) => Promise<void>;\n afterMigration?: (context: VerificationContext) => Promise<void>;\n};\n\nconst disposableDatabase = async <Result>(\n url: string,\n schemaName: string,\n callback: (driver: Driver) => Promise<Result>,\n): Promise<Result> => {\n const admin = postgres({ url, max: 1 });\n const name = `symmetria_verify_${randomUUID().replaceAll(\"-\", \"\")}`;\n let created = false;\n let driver: Driver | undefined;\n\n try {\n await executeSQL(\n admin.execute,\n `CREATE DATABASE ${quoteIdentifier(name)} TEMPLATE template0`,\n );\n created = true;\n const address = new URL(url);\n address.pathname = `/${name}`;\n // Migrations run in sessions, whose connections are closed afterwards, so\n // every connection takes the search_path from its startup options. The\n // second connection answers the migrator's transaction-pooling check.\n address.searchParams.set(\n \"options\",\n `-c search_path=${quoteIdentifier(schemaName).replace(/[\\\\\\s]/g, \"\\\\$&\")}`,\n );\n driver = postgres({ url: address.toString(), max: 2 });\n\n if (schemaName !== \"public\") {\n await executeSQL(\n driver.execute,\n `CREATE SCHEMA ${quoteIdentifier(schemaName)}`,\n );\n }\n\n return await callback(driver);\n } finally {\n try {\n await driver?.close();\n } finally {\n try {\n if (created) {\n await executeSQL(\n admin.execute,\n `DROP DATABASE ${quoteIdentifier(name)} WITH (FORCE)`,\n );\n }\n } finally {\n await admin.close();\n }\n }\n }\n};\n\n/** Catalog rows present on one side only, so a refused repair or adoption says what to reconcile. */\nconst catalogDifferences = (\n expected: Record<string, readonly unknown[]>,\n actual: Record<string, readonly unknown[]>,\n): string[] =>\n Object.keys({ ...expected, ...actual })\n .sort()\n .flatMap((section) => {\n const wanted = new Set((expected[section] ?? []).map(canonicalJSON));\n const found = new Set((actual[section] ?? []).map(canonicalJSON));\n\n return [\n ...[...found]\n .filter((row) => !wanted.has(row))\n .map((row) => {\n const index = JSON.parse(row) as { name?: string; valid?: boolean };\n\n return section === \"indexes\" && index.valid === false\n ? ` unexpected invalid index ${index.name} (left by a failed CONCURRENTLY build; DROP INDEX CONCURRENTLY it before retrying): ${row}`\n : ` unexpected ${section}: ${row}`;\n }),\n ...[...wanted]\n .filter((row) => !found.has(row))\n .map((row) => ` missing ${section}: ${row}`),\n ];\n });\n\nconst catalogMatches = (expected: unknown, actual: unknown, label: string) => {\n if (canonicalJSON(expected) !== canonicalJSON(actual)) {\n const differences = catalogDifferences(\n expected as Record<string, readonly unknown[]>,\n actual as Record<string, readonly unknown[]>,\n );\n const shown = differences.slice(0, 20);\n\n throw new Error(\n [\n `symmetria: ${label}: database catalog does not match the verified migration boundary`,\n ...shown,\n ...(differences.length > shown.length\n ? [` … ${differences.length - shown.length} more`]\n : []),\n ].join(\"\\n\"),\n );\n }\n};\n\ntype BoundaryOptions = ExecutionOptions & {\n execute: QueryExecutor;\n state: MigrationState;\n target: number;\n url: string;\n directory: string;\n metadataSchema?: string;\n metadataTable?: string;\n ignoreTables?: readonly string[];\n};\n\n/** Reconstruct an older boundary by replaying SQL; no historical snapshots are persisted. */\nconst readBoundary = async (\n options: BoundaryOptions,\n): Promise<{ expected: unknown; actual: unknown }> => {\n const schemaName = String(\n (await executeSQL(options.execute, \"SELECT current_schema() AS name\"))\n .rows[0]!.name,\n );\n const ignoreTables = undeclaredTables(\n options.ignoreTables,\n options.state.snapshot,\n );\n const actual = await readCatalog({ ...options, schemaName, ignoreTables });\n const expected = await disposableDatabase(\n options.url,\n schemaName,\n async (driver) => {\n if (options.target >= 0) {\n await migrator({ ...options, driver }).migrate({\n to: options.state.migrations[options.target]!.id,\n });\n }\n\n return readCatalog({\n ...options,\n execute: driver.execute,\n schemaName,\n ignoreTables,\n });\n },\n );\n\n return { expected, actual };\n};\n\n/** Refuses a database whose catalog is not what the chain up to `target` builds. */\nexport const verifyBoundary = async (\n options: BoundaryOptions,\n): Promise<void> => {\n const { expected, actual } = await readBoundary(options);\n catalogMatches(\n expected,\n actual,\n \"schema does not match the adoption/recovery target\",\n );\n};\n\n/**\n * What the database has more or less than the chain up to `target` builds, one\n * line each; empty when they match. For `drift` on a database that is\n * intentionally behind the latest snapshot.\n */\nexport const boundaryDifferences = async (\n options: BoundaryOptions,\n): Promise<string[]> => {\n const { expected, actual } = await readBoundary(options);\n\n return canonicalJSON(expected) === canonicalJSON(actual)\n ? []\n : catalogDifferences(\n expected as Record<string, readonly unknown[]>,\n actual as Record<string, readonly unknown[]>,\n ).map((line) => line.trim());\n};\n\n/** Exercise fresh installation, populated upgrades, rollback and reapplication on real PostgreSQL. */\nexport const verifyMigrations = async (\n options: VerifyOptions,\n): Promise<{ migrations: string[]; verified: true }> => {\n const state = await loadMigrationState(options.directory);\n const schemaName = options.schemaName ?? \"public\";\n const ignoreTables = undeclaredTables(options.ignoreTables, state.snapshot);\n\n const assertLatest = async (driver: Driver) => {\n const findings = await detectDrift({\n ...options,\n execute: driver.execute,\n snapshot: state.snapshot,\n schemaName,\n });\n\n if (findings.length) {\n throw new Error(\n `symmetria: verified SQL differs from the latest snapshot\\n${formatDriftFindings(findings)}`,\n );\n }\n };\n\n await disposableDatabase(options.url, schemaName, async (driver) => {\n await migrator({ ...options, driver }).migrate();\n await assertLatest(driver);\n });\n await disposableDatabase(options.url, schemaName, async (driver) => {\n const runner = migrator({ ...options, driver });\n\n const catalog = () =>\n readCatalog({\n ...options,\n execute: driver.execute,\n schemaName,\n ignoreTables,\n });\n\n for (const migration of state.migrations) {\n const before = await catalog();\n const up: VerificationContext = {\n driver,\n migration: migration.id,\n phase: \"up\",\n };\n await options.beforeMigration?.(up);\n await runner.migrate({ to: migration.id });\n const after = await catalog();\n await options.afterMigration?.(up);\n const down: VerificationContext = { ...up, phase: \"down\" };\n await options.beforeMigration?.(down);\n await runner.rollback();\n catalogMatches(before, await catalog(), `rollback of ${migration.id}`);\n await options.afterMigration?.(down);\n const reapply: VerificationContext = { ...up, phase: \"reapply\" };\n await options.beforeMigration?.(reapply);\n await runner.migrate({ to: migration.id });\n catalogMatches(\n after,\n await catalog(),\n `reapplication of ${migration.id}`,\n );\n await options.afterMigration?.(reapply);\n }\n\n await assertLatest(driver);\n });\n\n return {\n migrations: state.migrations.map((migration) => migration.id),\n verified: true,\n };\n};\n","import type { SchemaSnapshot } from \"symmetria\";\nimport type { ExecutionOptions } from \"./execution\";\nimport type { VerifyOptions } from \"./verify\";\n\nexport type MigrationConfig = ExecutionOptions & {\n readonly schema?: { $snapshot: () => SchemaSnapshot } | SchemaSnapshot;\n readonly directory?: string;\n readonly databaseUrl?: string | undefined;\n /** Migration journal schema (default public); does not change the application search_path. */\n readonly metadataSchema?: string;\n readonly metadataTable?: string;\n /**\n * Undeclared tables that pull, drift, adopt, repair and verify leave out:\n * another tool's tables, PostGIS `spatial_ref_sys`. A table the schema\n * declares is still compared. The CLI adds `_prisma_migrations` everywhere\n * but in pull, which reports it.\n */\n readonly ignoreTables?: readonly string[];\n readonly verificationDatabaseUrl?: string;\n readonly verify?: Pick<\n VerifyOptions,\n \"schemaName\" | \"beforeMigration\" | \"afterMigration\"\n >;\n};\n\nexport const defineMigrationConfig = (\n config: MigrationConfig,\n): MigrationConfig => config;\n","/**\n * Name conversions for introspection: SQL identifiers to schema keys that round-trip\n * through the assembler's snakeCase, conventional object names and source-text escaping.\n */\nimport { snakeCase, sqlKey, type Casing } from \"symmetria\";\nimport { objectName } from \"../migrations/snapshot\";\n\n/** Names the table handle resolves to its own methods before columns. */\nconst RESERVED_COLUMN_KEYS = new Set([\n \"indexes\",\n \"checks\",\n \"primaryKey\",\n \"computed\",\n \"nullable\",\n \"unique\",\n \"index\",\n \"onDelete\",\n \"onUpdate\",\n \"inverse\",\n \"relations\",\n \"named\",\n \"by\",\n \"column\",\n]);\nconst RESERVED_TABLE_KEYS = new Set([\"constructor\", \"prototype\", \"__proto__\"]);\n\n/**\n * The camelCase key whose snake_case form is exactly `sqlName`, or undefined when\n * no key can produce that SQL name (uppercase letters, leading/trailing or doubled\n * underscores, digits after an underscore, a leading digit).\n */\nexport const camelKey = (sqlName: string): string | undefined => {\n if (!/^[a-z][a-z0-9]*(_[a-z][a-z0-9]*)*$/.test(sqlName)) {\n return undefined;\n }\n\n const key = sqlName.replace(/_([a-z])/g, (_, letter: string) =>\n letter.toUpperCase(),\n );\n\n return snakeCase(key) === sqlName ? key : undefined;\n};\n\n/** Keys written as they are: a lowercase start, then letters and digits. */\nconst PRESERVED_KEY = /^[a-z][A-Za-z0-9]*$/;\n\n/** The key whose SQL name under `casing` is exactly `sqlName`, or undefined. */\nexport const naturalKey = (\n sqlName: string,\n casing: Casing,\n): string | undefined =>\n casing === \"preserve\"\n ? PRESERVED_KEY.test(sqlName)\n ? sqlName\n : undefined\n : camelKey(sqlName);\n\n/**\n * A camelCase key for any SQL name (`User` → `user`, `CamelCol` → `camelCol`,\n * `_prisma_migrations` → `prismaMigrations`); the declaration adds `.named()`\n * when the key does not produce the name by itself.\n */\nexport const derivedKey = (sqlName: string): string => {\n const words = sqlName\n .split(/[^A-Za-z0-9]+|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/)\n .filter(Boolean);\n const key = words\n .map((word, position) =>\n position === 0\n ? word.toLowerCase()\n : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),\n )\n .join(\"\");\n\n return !key ? \"unnamed\" : /^[0-9]/.test(key) ? `n${key}` : key;\n};\n\nexport const keyFor = (sqlName: string, casing: Casing): string =>\n naturalKey(sqlName, casing) ?? derivedKey(sqlName);\n\n/**\n * The casing that lets most names be declared without `.named()`: Prisma-style\n * camelCase (`createdAt`) chooses `\"preserve\"`, snake_case (`created_at`) the default.\n */\nexport const chooseCasing = (names: readonly string[]): Casing => {\n let snake = 0;\n let preserved = 0;\n\n for (const name of names) {\n const asSnake = camelKey(name) !== undefined;\n const asPreserved = PRESERVED_KEY.test(name);\n\n if (asSnake && !asPreserved) {\n snake += 1;\n } else if (asPreserved && !asSnake) {\n preserved += 1;\n }\n }\n\n return preserved > snake ? \"preserve\" : \"snake_case\";\n};\n\n/** Relation key and explicit column for a foreign-key column under a casing. */\nexport const referenceKey = (\n sqlName: string,\n casing: Casing,\n): { key: string; column?: string } => {\n const base =\n casing === \"preserve\"\n ? /^[a-z][A-Za-z0-9]*Id$/.test(sqlName)\n ? sqlName.slice(0, -2)\n : undefined\n : sqlName.endsWith(\"_id\") && sqlName.length > 3\n ? camelKey(sqlName.slice(0, -3))\n : undefined;\n\n if (base) {\n return { key: base };\n }\n\n const key = keyFor(sqlName, casing);\n\n return {\n key: key.endsWith(\"Id\") && key.length > 2 ? key.slice(0, -2) : key,\n column: sqlName,\n };\n};\n\n/** Allocates distinct keys, suffixing a number when two names derive the same key. */\nexport const keyAllocator = (\n reserved: (key: string) => boolean = () => false,\n) => {\n const taken = new Set<string>();\n\n return (base: string): string => {\n let key = reserved(base) ? `${base}Value` : base;\n let ordinal = 2;\n\n while (taken.has(key)) {\n key = `${base}${ordinal++}`;\n }\n\n taken.add(key);\n\n return key;\n };\n};\n\n/** Every identifier a generated module imports or declares at its top level. */\nexport const MODULE_IDENTIFIERS: readonly string[] = [\n \"and\",\n \"bigint\",\n \"bool\",\n \"bytea\",\n \"customType\",\n \"date\",\n \"doublePrecision\",\n \"index\",\n \"inet\",\n \"int\",\n \"interval\",\n \"jsonb\",\n \"junction\",\n \"not\",\n \"numeric\",\n \"oneOf\",\n \"operatorClass\",\n \"or\",\n \"passthrough\",\n \"real\",\n \"schema\",\n \"smallint\",\n \"sql\",\n \"table\",\n \"text\",\n \"time\",\n \"timestamp\",\n \"timestamptz\",\n \"tsvector\",\n \"uuid\",\n \"varchar\",\n \"vector\",\n \"halfvec\",\n];\n\n/** Words a module cannot use as a parameter or binding name. */\nconst RESERVED_WORDS = new Set([\n \"arguments\",\n \"await\",\n \"break\",\n \"case\",\n \"catch\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"finally\",\n \"for\",\n \"function\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"interface\",\n \"let\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"static\",\n \"super\",\n \"switch\",\n \"this\",\n \"throw\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"while\",\n \"with\",\n \"yield\",\n]);\n\n/**\n * Identifiers for tables inside generated callbacks. A table keyed like a builder\n * (`date`, `text`) would shadow the import in `({ date }) =>`, and a reserved word\n * cannot be a parameter, so those tables are bound as `dateTable` instead.\n */\nexport const tableBindings = (keys: readonly string[]): Map<string, string> => {\n const taken = new Set([...MODULE_IDENTIFIERS, ...keys]);\n const bindings = new Map<string, string>();\n\n for (const key of keys) {\n if (!MODULE_IDENTIFIERS.includes(key) && !RESERVED_WORDS.has(key)) {\n bindings.set(key, key);\n continue;\n }\n\n let binding = `${key}Table`;\n let ordinal = 2;\n\n while (taken.has(binding)) {\n binding = `${key}Table${ordinal++}`;\n }\n\n taken.add(binding);\n bindings.set(key, binding);\n }\n\n return bindings;\n};\n\nexport const isReservedColumnKey = (key: string): boolean =>\n RESERVED_COLUMN_KEYS.has(key);\n\nexport const isReservedTableKey = (key: string): boolean =>\n RESERVED_TABLE_KEYS.has(key);\n\nexport const pascal = (key: string): string =>\n key.charAt(0).toUpperCase() + key.slice(1);\n\n/** The constraint and index names the DSL derives for a table. */\nexport const conventionalNames = {\n primaryKey: (table: string) => objectName(table, \"pkey\"),\n unique: (table: string, column: string) => objectName(table, column, \"key\"),\n foreignKey: (table: string, column: string) =>\n objectName(table, column, \"fkey\"),\n check: (table: string, key: string, casing?: Casing) =>\n objectName(table, sqlKey(key, casing), \"check\"),\n index: (table: string, key: string, casing?: Casing) =>\n objectName(table, sqlKey(key, casing), \"idx\"),\n /** Automatic index on one column, named after the column's SQL name. */\n columnIndex: (table: string, column: string) =>\n objectName(table, column, \"idx\"),\n enumeration: (table: string, column: string) =>\n objectName(table, column, \"enum\"),\n};\n\n/** Escapes text for a JavaScript template literal. */\nexport const escapeTemplate = (text: string): string =>\n text.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"`\", \"\\\\`\").replaceAll(\"${\", \"\\\\${\");\n\n/** A double-quoted JavaScript string literal. */\nexport const quoteString = (text: string): string => JSON.stringify(text);\n\n/** `\"identifier\"` in SQL, for suggested fixes. */\nexport const quoteSql = (identifier: string): string =>\n `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n\n/** `'text'` in SQL, for suggested fixes. */\nexport const sqlString = (text: string): string =>\n `'${text.replaceAll(\"'\", \"''\")}'`;\n","import { normalizeSqlType } from \"../migrations/drift\";\nimport { isReservedColumnKey } from \"./names\";\nimport type {\n PullWarning,\n ColumnType,\n ColumnDefault,\n PulledColumn,\n} from \"./pulled\";\nimport {\n type CatalogColumn,\n type TableFacts,\n customValueType,\n serialFix,\n} from \"./model\";\n\nexport type ColumnTools = {\n ownsEnum: (column: CatalogColumn) => boolean;\n enumValues: (name: string) => string[] | undefined;\n serialSequence: (\n column: CatalogColumn,\n reference: string,\n ) => { exclusive: boolean; reason: string };\n warn: (warning: PullWarning) => void;\n uniqueFor: (columnName: string) => { unique: boolean; comments: string[] };\n indexFor: (columnName: string, unique: boolean) => boolean;\n};\n\nexport const columnMember = (\n column: CatalogColumn,\n key: string,\n table: TableFacts,\n tools: ColumnTools,\n): PulledColumn => {\n const comments: string[] = [];\n const { unique, comments: uniqueComments } = tools.uniqueFor(\n column.column_name,\n );\n comments.push(...uniqueComments);\n const { type, array } = columnType(column, table, tools, comments);\n const member: PulledColumn = {\n kind: \"column\",\n key,\n sqlName: column.column_name,\n type,\n array,\n nullable: !column.not_null,\n unique,\n index: tools.indexFor(column.column_name, unique),\n primaryKey: false,\n comments,\n };\n\n if (column.collation) {\n const collatable =\n (type.kind === \"builder\" && type.name === \"text\") ||\n type.kind === \"varchar\" ||\n (type.kind === \"custom\" && /^string(\\[\\])?$/.test(type.valueType));\n\n if (collatable) {\n member.collation = column.collation;\n } else {\n comments.push(`collation \"${column.collation}\" is not declared`);\n tools.warn({\n code: \"collation\",\n table: table.sqlName,\n column: column.column_name,\n object: column.collation,\n message: `\"${table.sqlName}.${column.column_name}\" uses collation \"${column.collation}\", which the schema cannot declare for ${column.data_type}`,\n });\n }\n }\n\n if (isReservedColumnKey(key)) {\n comments.push(\n `\"${key}\" is also a table method; use it inside shape callbacks`,\n );\n tools.warn({\n code: \"name\",\n table: table.sqlName,\n column: column.column_name,\n message: `\"${table.sqlName}.${column.column_name}\" shares its key with a table method; reach it inside shape callbacks`,\n });\n }\n\n if (table.generated.has(column.column_name)) {\n comments.push(\"generated column; the expression is not declared\");\n tools.warn({\n code: \"generated-column\",\n table: table.sqlName,\n column: column.column_name,\n message: `\"${table.sqlName}.${column.column_name}\" is a generated column; the schema declares a plain column`,\n });\n\n return member;\n }\n\n const value = columnDefault(column, type, array, table, tools, comments);\n\n if (value) {\n member.default = value;\n }\n\n return member;\n};\n\nexport const columnType = (\n column: CatalogColumn,\n table: TableFacts,\n tools: ColumnTools,\n comments: string[],\n): { type: ColumnType; array: boolean } => {\n const normalized = normalizeSqlType(column.data_type);\n const array = normalized.endsWith(\"[]\") && !normalized.endsWith(\"[][]\");\n const base = array ? normalized.slice(0, -2) : normalized;\n\n if (column.enum_name && column.enum_schema === null && !array) {\n const values = tools.enumValues(column.enum_name);\n\n if (values) {\n return {\n type: {\n kind: \"enum\",\n values,\n ...(tools.ownsEnum(column) ? {} : { name: column.enum_name }),\n },\n array: false,\n };\n }\n }\n\n const builder = (\n {\n integer: \"int\",\n bigint: \"bigint\",\n smallint: \"smallint\",\n real: \"real\",\n \"double precision\": \"doublePrecision\",\n text: \"text\",\n boolean: \"bool\",\n uuid: \"uuid\",\n \"timestamp with time zone\": \"timestamptz\",\n date: \"date\",\n \"time without time zone\": \"time\",\n interval: \"interval\",\n bytea: \"bytea\",\n inet: \"inet\",\n jsonb: \"jsonb\",\n tsvector: \"tsvector\",\n } as const\n )[base];\n\n if (builder) {\n return { type: { kind: \"builder\", name: builder }, array };\n }\n\n const stamp = /^timestamp (with|without) time zone(?:\\((\\d)\\))?$/.exec(base);\n\n if (stamp) {\n return {\n type: {\n kind: \"builder\",\n name: stamp[1] === \"with\" ? \"timestamptz\" : \"timestamp\",\n ...(stamp[2] ? { precision: Number(stamp[2]) } : {}),\n },\n array,\n };\n }\n\n const vectorType = /^(vector|halfvec)(?:\\((\\d+)\\))?$/.exec(base);\n\n if (vectorType && !array) {\n return {\n type: {\n kind: \"vector\",\n ...(vectorType[1] === \"halfvec\" ? { half: true as const } : {}),\n ...(vectorType[2] ? { dimensions: Number(vectorType[2]) } : {}),\n },\n array: false,\n };\n }\n\n const varchar = /^character varying(?:\\((\\d+)\\))?$/.exec(base);\n\n if (varchar) {\n return {\n type: {\n kind: \"varchar\",\n ...(varchar[1] ? { length: Number(varchar[1]) } : {}),\n },\n array,\n };\n }\n\n const numeric = /^numeric(?:\\((\\d+)(?:,(\\d+))?\\))?$/.exec(base);\n\n if (numeric) {\n return {\n type: {\n kind: \"numeric\",\n ...(numeric[1] ? { precision: Number(numeric[1]) } : {}),\n ...(numeric[2] ? { scale: Number(numeric[2]) } : {}),\n },\n array,\n };\n }\n\n // Enums of other schemas and arrays of enums have no oneOf() form either.\n const sqlType = column.data_type;\n const valueType =\n customValueType(base) + (normalized.endsWith(\"[]\") ? \"[]\" : \"\");\n comments.push(`no builder for ${sqlType}`);\n tools.warn({\n code: \"custom-type\",\n table: table.sqlName,\n column: column.column_name,\n object: sqlType,\n message: `\"${table.sqlName}.${column.column_name}\" uses ${sqlType}, declared through customType() with driver-native values`,\n });\n\n return { type: { kind: \"custom\", sqlType, valueType }, array: false };\n};\n\nexport const columnDefault = (\n column: CatalogColumn,\n type: ColumnType,\n array: boolean,\n table: TableFacts,\n tools: ColumnTools,\n comments: string[],\n): ColumnDefault | undefined => {\n const name = `${table.sqlName}.${column.column_name}`;\n const integer =\n type.kind === \"builder\" &&\n (type.name === \"int\" ||\n type.name === \"bigint\" ||\n type.name === \"smallint\") &&\n !array;\n\n if (column.identity !== \"\") {\n if (integer) {\n return column.identity === \"d\"\n ? { kind: \"auto\", byDefault: true }\n : { kind: \"auto\" };\n }\n\n comments.push(\"identity column\");\n tools.warn({\n code: \"identity-type\",\n table: table.sqlName,\n column: column.column_name,\n message: `\"${name}\" is an identity column of type ${column.data_type}; it is declared through a raw identity default`,\n });\n\n return { kind: \"identity\" };\n }\n\n const text = column.default;\n\n if (text === null) {\n return undefined;\n }\n\n if (!array && type.kind === \"builder\") {\n if (\n (type.name === \"timestamptz\" || type.name === \"timestamp\") &&\n text === \"now()\"\n ) {\n return { kind: \"now\" };\n }\n\n if (type.name === \"uuid\" && text === \"gen_random_uuid()\") {\n return { kind: \"v4\" };\n }\n\n if (type.name === \"uuid\" && text === \"uuidv7()\") {\n return { kind: \"v7\" };\n }\n }\n\n const serial = /^nextval\\('((?:[^']|'')*)'::regclass\\)$/.exec(text);\n\n if (serial) {\n const sequence = unescapeLiteral(serial[1]!);\n const { exclusive, reason } = tools.serialSequence(column, sequence);\n\n // Dropping a sequence other columns draw from would break their defaults.\n if (!exclusive) {\n comments.push(\n \"default from a shared sequence; migrations will not create the sequence\",\n );\n tools.warn({\n code: \"sequence\",\n table: table.sqlName,\n column: column.column_name,\n object: sequence,\n message: `\"${name}\" takes its default from sequence ${sequence}, which ${reason}; the schema keeps the nextval() default but migrations from this schema will not create the sequence, and no identity fix is offered because it would drop a sequence something else may use`,\n });\n\n return { kind: \"sql\", sql: text };\n }\n\n comments.push(\"serial column; migrations will not create the sequence\");\n tools.warn({\n code: \"serial\",\n table: table.sqlName,\n column: column.column_name,\n message: integer\n ? `\"${name}\" is a serial column; the schema keeps its nextval() default but migrations from this schema will not create the sequence. The fix makes it an identity column (.auto.byDefault) that continues the sequence`\n : `\"${name}\" is a serial column; the schema keeps its nextval() default but migrations from this schema will not create the sequence`,\n ...(integer\n ? { fix: serialFix(table.sqlName, column.column_name, sequence) }\n : {}),\n });\n\n return { kind: \"sql\", sql: text };\n }\n\n const literal = !array ? literalDefault(text, type) : undefined;\n\n return literal\n ? { kind: \"value\", source: literal }\n : { kind: \"sql\", sql: text };\n};\n\nexport const unescapeLiteral = (text: string) => text.replaceAll(\"''\", \"'\");\n\n/** JavaScript source for defaults PostgreSQL prints as simple literals. */\nexport const literalDefault = (\n text: string,\n type: ColumnType,\n): string | undefined => {\n const quoted = /^'((?:[^']|'')*)'::(.+)$/.exec(text);\n const integer =\n /^(-?\\d+)$/.exec(text) ??\n /^'(-?\\d+)'::(integer|bigint|smallint)$/.exec(text);\n\n const decimal =\n /^(-?\\d+(?:\\.\\d+)?)$/.exec(text) ??\n /^'(-?\\d+(?:\\.\\d+)?)'::(real|double precision|integer|numeric)$/.exec(text);\n\n switch (type.kind) {\n case \"builder\":\n switch (type.name) {\n case \"int\":\n case \"smallint\":\n return integer ? integer[1] : undefined;\n case \"bigint\":\n return integer ? `${integer[1]}n` : undefined;\n case \"real\":\n case \"doublePrecision\":\n return decimal ? decimal[1] : undefined;\n case \"date\":\n return quoted && quoted[2] === \"date\"\n ? JSON.stringify(unescapeLiteral(quoted[1]!))\n : undefined;\n case \"time\":\n return quoted && quoted[2] === \"time without time zone\"\n ? JSON.stringify(unescapeLiteral(quoted[1]!))\n : undefined;\n case \"interval\":\n return quoted && quoted[2] === \"interval\"\n ? JSON.stringify(unescapeLiteral(quoted[1]!))\n : undefined;\n case \"inet\":\n return quoted && quoted[2] === \"inet\"\n ? JSON.stringify(unescapeLiteral(quoted[1]!))\n : undefined;\n case \"bool\":\n return text === \"true\" || text === \"false\" ? text : undefined;\n case \"text\":\n case \"uuid\":\n return quoted &&\n /^(text|character varying(\\(\\d+\\))?|uuid|bpchar)$/.test(quoted[2]!)\n ? JSON.stringify(unescapeLiteral(quoted[1]!))\n : undefined;\n case \"jsonb\":\n return quoted &&\n quoted[2] === \"jsonb\" &&\n /^(\\{\\}|\\[\\])$/.test(quoted[1]!)\n ? quoted[1]\n : undefined;\n default:\n return undefined;\n }\n case \"varchar\":\n return quoted &&\n /^(text|character varying(\\(\\d+\\))?|bpchar)$/.test(quoted[2]!)\n ? JSON.stringify(unescapeLiteral(quoted[1]!))\n : undefined;\n case \"numeric\": {\n const decimal =\n /^(-?\\d+(?:\\.\\d+)?)$/.exec(text) ??\n /^'(-?\\d+(?:\\.\\d+)?)'::numeric(\\(\\d+(,\\d+)?\\))?$/.exec(text);\n\n return decimal ? JSON.stringify(decimal[1]) : undefined;\n }\n case \"enum\":\n return quoted && type.values.includes(unescapeLiteral(quoted[1]!))\n ? JSON.stringify(unescapeLiteral(quoted[1]!))\n : undefined;\n case \"custom\": {\n if (type.valueType === \"number\") {\n const number =\n /^(-?\\d+(?:\\.\\d+)?)$/.exec(text) ??\n /^'(-?\\d+(?:\\.\\d+)?)'::\\w+( \\w+)?$/.exec(text);\n\n return number ? number[1] : undefined;\n }\n\n if (type.valueType.startsWith('\"') && quoted) {\n const value = JSON.stringify(unescapeLiteral(quoted[1]!));\n\n return type.valueType.split(\" | \").includes(value) ? value : undefined;\n }\n\n return undefined;\n }\n }\n};\n","/**\n * Declares pulled CHECK constraints, index predicates and computed index keys in\n * the schema DSL: `(score > 0) AND (name <> 'x'::text)` becomes\n * `and(users.score.above(0), users.name.isNot(\"x\"))`. A condition with any part\n * the DSL cannot express (a function call, a cast the DSL would not write) stays\n * `sql` text, as before.\n */\nimport { normalizeSqlType } from \"../migrations/drift\";\nimport { readExpression, type SqlExpression } from \"../migrations/expressions\";\nimport { quoteString } from \"./names\";\n\n/**\n * What a column holds, which decides how its literals are written. Literals are\n * declared only in the form PostgreSQL stored, so the declaration parses back\n * to the same expression: `big < '10'::bigint` is `big.below(10n)`, while a\n * hand-written `big < 10` (an integer literal) stays `sql`.\n */\nexport type ValueKind =\n | {\n readonly kind:\n | \"integer\"\n | \"real\"\n | \"double\"\n | \"bigint\"\n | \"decimal\"\n | \"boolean\"\n | \"other\";\n }\n /** `type` is the column's type without modifiers: `text`, `date`, `uuid`, … */\n | { readonly kind: \"string\" | \"timestamp\"; readonly type: string }\n | { readonly kind: \"enum\"; readonly labels: readonly string[] };\n\nexport type ScopeColumn = {\n /** The column in generated code: `users.score`. */\n readonly source: string;\n readonly sqlType: string;\n readonly value: ValueKind;\n};\n\n/** The columns a condition can name, by SQL name. */\nexport type ConditionScope = ReadonlyMap<string, ScopeColumn>;\n\n/** A condition in the DSL, with the functions it imports (`and`, `or`, `not`). */\nexport type DeclaredCondition = {\n readonly source: string;\n readonly imports: readonly string[];\n};\n\nconst STRING_TYPES =\n /^(text|character varying|date|time without time zone|interval|uuid|inet)$/;\nconst TEXT_TYPES = new Set([\"text\", \"character varying\"]);\n\n/** The kind of a column of the given PostgreSQL type, following the builders pull declares. */\nexport const valueKind = (\n sqlType: string,\n labels?: readonly string[],\n): ValueKind => {\n if (labels) {\n return { kind: \"enum\", labels };\n }\n\n const type = normalizeSqlType(sqlType).replace(/\\(.*?\\)/, \"\");\n const simple = (\n {\n integer: \"integer\",\n smallint: \"integer\",\n real: \"real\",\n \"double precision\": \"double\",\n bigint: \"bigint\",\n numeric: \"decimal\",\n boolean: \"boolean\",\n } as const\n )[type];\n\n if (simple) {\n return { kind: simple };\n }\n\n if (/^timestamp with(out)? time zone$/.test(type)) {\n return { kind: \"timestamp\", type };\n }\n\n return STRING_TYPES.test(type) ? { kind: \"string\", type } : { kind: \"other\" };\n};\n\n/** Columns compare with each other only when TypeScript gives them one type. */\nconst typeOf = (kind: ValueKind): string =>\n kind.kind === \"enum\"\n ? `enum ${JSON.stringify(kind.labels)}`\n : [\"integer\", \"real\", \"double\"].includes(kind.kind)\n ? \"number\"\n : kind.kind;\n\n/** Kinds arithmetic works on; real and double results are double precision. */\nconst NUMERIC_KINDS = new Set([\n \"integer\",\n \"real\",\n \"double\",\n \"bigint\",\n \"decimal\",\n]);\n/** Kinds whose column-to-column arithmetic PostgreSQL stores without casts of its own. */\nconst EXACT_KINDS = new Set([\"integer\", \"bigint\", \"decimal\"]);\nconst COMPARISON_METHODS: Readonly<Record<string, string>> = {\n \"=\": \"is\",\n \"<>\": \"isNot\",\n \">\": \"above\",\n \">=\": \"atLeast\",\n \"<\": \"below\",\n \"<=\": \"atMost\",\n};\nconst ARITHMETIC_METHODS: Readonly<Record<string, string>> = {\n \"+\": \"plus\",\n \"-\": \"minus\",\n \"*\": \"multiply\",\n \"/\": \"divide\",\n};\n\n/** PostgreSQL's timestamp text as a Date, when a Date writes back the same instant. */\nconst timestampLiteral = (text: string): string | undefined => {\n const match =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?)(Z|[+-]\\d{2}(?::?\\d{2})?)?$/.exec(\n text,\n );\n\n if (!match) {\n return undefined;\n }\n\n // Without a zone the value is UTC wall-clock time, as the timestamp codec writes it.\n const zone = match[3]\n ? match[3] === \"Z\"\n ? \"Z\"\n : `${match[3].slice(0, 3)}:${match[3].slice(3).replace(\":\", \"\") || \"00\"}`\n : \"Z\";\n const date = new Date(`${match[1]}T${match[2]}${zone}`);\n\n return Number.isNaN(date.getTime())\n ? undefined\n : `new Date(${quoteString(date.toISOString())})`;\n};\n\nconst INTEGER = /^-?\\d+$/;\n\n/**\n * A literal as TypeScript source for a value of `kind`, or undefined when it\n * does not fit or was stored with another type than the DSL would write.\n */\nconst literal = (node: SqlExpression, kind: ValueKind): string | undefined => {\n if (node.kind === \"boolean\") {\n return kind.kind === \"boolean\" ? String(node.value) : undefined;\n }\n\n if (node.kind !== \"constant\") {\n return undefined;\n }\n\n const { value: text, type } = node;\n\n switch (kind.kind) {\n case \"integer\":\n // PostgreSQL prints integer literals bare, negative ones as '-1'::integer.\n return INTEGER.test(text) &&\n (type === \"integer\" || (type === undefined && node.numeric)) &&\n Math.abs(Number(text)) <= 2147483647\n ? String(Number(text))\n : undefined;\n case \"real\":\n case \"double\":\n return type === (kind.kind === \"real\" ? \"real\" : \"double precision\") &&\n /^-?\\d/.test(text) &&\n String(Number(text)) === text\n ? text\n : undefined;\n case \"bigint\":\n return type === \"bigint\" && INTEGER.test(text)\n ? `${BigInt(text)}n`\n : undefined;\n case \"decimal\":\n return (type === \"numeric\" || (type === undefined && node.numeric)) &&\n /^-?\\d+(\\.\\d+)?$/.test(text)\n ? quoteString(text)\n : undefined;\n case \"string\":\n return type === undefined ||\n type === kind.type ||\n (TEXT_TYPES.has(kind.type) && TEXT_TYPES.has(type))\n ? quoteString(text)\n : undefined;\n case \"enum\":\n return kind.labels.includes(text) ? quoteString(text) : undefined;\n case \"timestamp\":\n return type?.replace(/\\(.*?\\)/, \"\") === kind.type\n ? timestampLiteral(text)\n : undefined;\n default:\n return undefined;\n }\n};\n\n/**\n * The kind of `left` combined with `right`, as plus() and friends type it. Any\n * real or double operand makes a double precision result.\n */\nconst promoted = (left: ValueKind, right: ValueKind): ValueKind => {\n const kinds: string[] = [left.kind, right.kind];\n\n return {\n kind: kinds.includes(\"decimal\")\n ? \"decimal\"\n : kinds.includes(\"real\") || kinds.includes(\"double\")\n ? \"double\"\n : kinds.includes(\"bigint\")\n ? \"bigint\"\n : \"integer\",\n };\n};\n\nconst sameNode = (left: SqlExpression, right: SqlExpression): boolean =>\n JSON.stringify(left) === JSON.stringify(right);\n\nconst renderer = (scope: ConditionScope) => {\n const imports = new Set<string>();\n\n /** A column or arithmetic over columns: `users.score.plus(1)`. */\n const value = (\n node: SqlExpression,\n ): { source: string; kind: ValueKind } | undefined => {\n if (node.kind === \"column\") {\n const column = scope.get(node.name);\n\n return column && { source: column.source, kind: column.value };\n }\n\n if (node.kind !== \"binary\" || !ARITHMETIC_METHODS[node.operator]) {\n return undefined;\n }\n\n // plus() casts a non-decimal operand to numeric when the other one is\n // decimal, the cast PostgreSQL prints, so it is left to plus() again.\n const decimal = (side: SqlExpression, other: SqlExpression) =>\n side.kind === \"cast\" &&\n side.type === \"numeric\" &&\n value(other)?.kind.kind === \"decimal\"\n ? side.value\n : side;\n const left = value(decimal(node.left, node.right));\n\n if (!left || !NUMERIC_KINDS.has(left.kind.kind)) {\n return undefined;\n }\n\n // PostgreSQL widens a literal next to a real to double precision.\n const floating = left.kind.kind === \"real\" || left.kind.kind === \"double\";\n const kind: ValueKind = floating ? { kind: \"double\" } : left.kind;\n const constant = literal(node.right, kind);\n\n if (constant !== undefined) {\n return {\n source: `${left.source}.${ARITHMETIC_METHODS[node.operator]}(${constant})`,\n kind,\n };\n }\n\n const right = value(decimal(node.right, node.left));\n\n return right &&\n EXACT_KINDS.has(left.kind.kind) &&\n EXACT_KINDS.has(right.kind.kind)\n ? {\n source: `${left.source}.${ARITHMETIC_METHODS[node.operator]}(${right.source})`,\n kind: promoted(left.kind, right.kind),\n }\n : undefined;\n };\n\n /** The right side of a comparison with `left`: a literal of its type or a value of the same type. */\n const operand = (\n node: SqlExpression,\n left: { kind: ValueKind },\n ): string | undefined => {\n const constant = literal(node, left.kind);\n\n if (constant !== undefined) {\n return constant;\n }\n\n const right = value(node);\n\n return right && typeOf(right.kind) === typeOf(left.kind)\n ? right.source\n : undefined;\n };\n\n const negated = (call: string, negate: boolean): string => {\n if (!negate) {\n return call;\n }\n\n imports.add(\"not\");\n\n return `not(${call})`;\n };\n\n /** `x >= a AND x <= b`, as PostgreSQL stores BETWEEN, back as `x.between(a, b)`. */\n const between = (\n lower: SqlExpression,\n upper: SqlExpression | undefined,\n ): string | undefined => {\n if (\n lower.kind !== \"binary\" ||\n lower.operator !== \">=\" ||\n upper?.kind !== \"binary\" ||\n upper.operator !== \"<=\" ||\n !sameNode(lower.left, upper.left)\n ) {\n return undefined;\n }\n\n const subject = value(lower.left);\n const from = subject && operand(lower.right, subject);\n const to = subject && operand(upper.right, subject);\n\n return from === undefined || to === undefined\n ? undefined\n : `${subject!.source}.between(${from}, ${to})`;\n };\n\n const predicate = (node: SqlExpression): string | undefined => {\n switch (node.kind) {\n case \"column\": {\n const column = value(node);\n\n return column?.kind.kind === \"boolean\"\n ? `${column.source}.is(true)`\n : undefined;\n }\n case \"logical\": {\n const parts: (string | undefined)[] = [];\n\n for (let position = 0; position < node.values.length; position += 1) {\n const range =\n node.operator === \"AND\"\n ? between(node.values[position]!, node.values[position + 1])\n : undefined;\n\n if (range !== undefined) {\n parts.push(range);\n position += 1;\n } else {\n parts.push(predicate(node.values[position]!));\n }\n }\n\n if (parts.some((part) => part === undefined)) {\n return undefined;\n }\n\n if (parts.length === 1) {\n return parts[0];\n }\n\n const name = node.operator === \"AND\" ? \"and\" : \"or\";\n imports.add(name);\n\n return `${name}(${parts.join(\", \")})`;\n }\n case \"not\": {\n const column =\n node.value.kind === \"column\" ? value(node.value) : undefined;\n\n if (column?.kind.kind === \"boolean\") {\n return `${column.source}.is(false)`;\n }\n\n const inner = predicate(node.value);\n\n return inner === undefined ? undefined : negated(inner, true);\n }\n case \"binary\": {\n const method = COMPARISON_METHODS[node.operator];\n const left = method ? value(node.left) : undefined;\n const right = left && operand(node.right, left);\n\n return right === undefined\n ? undefined\n : `${left!.source}.${method}(${right})`;\n }\n case \"null-test\": {\n const subject = value(node.value);\n\n return subject\n ? `${subject.source}.${node.negated ? \"isNot\" : \"is\"}(null)`\n : undefined;\n }\n case \"in\": {\n const subject = value(node.value);\n const items = subject\n ? node.values.map((entry) => literal(entry, subject.kind))\n : [];\n\n return subject && items.every((item) => item !== undefined)\n ? `${subject.source}.${node.negated ? \"notIn\" : \"in\"}([${items.join(\", \")}])`\n : undefined;\n }\n case \"like\": {\n const subject = value(node.value);\n\n return subject &&\n (subject.kind.kind === \"string\" || subject.kind.kind === \"enum\") &&\n node.pattern.kind === \"constant\"\n ? negated(\n `${subject.source}.${node.operator === \"LIKE\" ? \"like\" : \"ilike\"}(${quoteString(node.pattern.value)})`,\n node.negated,\n )\n : undefined;\n }\n case \"distinct\": {\n const subject = value(node.left);\n const right =\n subject &&\n (node.right.kind === \"null\" ? \"null\" : operand(node.right, subject));\n\n return right === undefined\n ? undefined\n : negated(\n `${subject!.source}.isDistinctFrom(${right})`,\n node.negated,\n );\n }\n default:\n return undefined;\n }\n };\n\n return { value, predicate, imports };\n};\n\nconst columnTypes = (scope: ConditionScope): Map<string, string> =>\n new Map([...scope].map(([name, column]) => [name, column.sqlType]));\n\n/**\n * A CHECK or WHERE condition, as PostgreSQL prints it, declared in the DSL; a\n * boolean column stands alone. Undefined when only `sql` can declare it.\n */\nexport const declaredCondition = (\n sql: string,\n scope: ConditionScope,\n): DeclaredCondition | undefined => {\n const node = readExpression(sql, columnTypes(scope));\n\n if (!node) {\n return undefined;\n }\n\n const { value, predicate, imports } = renderer(scope);\n const column = node.kind === \"column\" ? value(node) : undefined;\n const source =\n column?.kind.kind === \"boolean\" ? column.source : predicate(node);\n\n return source === undefined\n ? undefined\n : { source, imports: [...imports].sort() };\n};\n\n/** An index key computed from columns, `users.score.plus(1)`, or undefined. */\nexport const declaredKey = (\n sql: string,\n scope: ConditionScope,\n): string | undefined => {\n const node = readExpression(sql, columnTypes(scope));\n\n return node?.kind === \"binary\"\n ? renderer(scope).value(node)?.source\n : undefined;\n};\n","import { INDEX_METHODS as RUNTIME_INDEX_METHODS } from \"symmetria/internal\";\nimport type { CatalogConstraint } from \"../migrations/catalog\";\nimport type { IndexDetailRow } from \"./catalog\";\nimport {\n declaredCondition,\n declaredKey,\n valueKind,\n type ConditionScope,\n} from \"./conditions\";\nimport {\n camelKey,\n naturalKey,\n conventionalNames,\n escapeTemplate,\n pascal,\n quoteSql,\n} from \"./names\";\nimport type {\n PullWarning,\n PulledMember,\n IndexKeySource,\n PulledIndex,\n PulledCondition,\n PulledCheck,\n PulledTable,\n} from \"./pulled\";\nimport { type TableFacts, renameFix } from \"./model\";\n\n/** Warns, with a RENAME CONSTRAINT fix, when the primary key is not named `<table>_pkey`. */\nexport const primaryKeyName = (\n table: TableFacts,\n declared: PulledTable,\n warn: (warning: PullWarning) => void,\n) => {\n const constraint = table.primaryKey;\n const expected = conventionalNames.primaryKey(table.sqlName);\n\n if (!constraint || constraint.name === expected) {\n return;\n }\n\n declared.comments.push(\n `primary key \"${constraint.name}\" is named \"${expected}\"`,\n );\n warn({\n code: \"constraint-name\",\n table: table.sqlName,\n object: constraint.name,\n message: `primary key \"${constraint.name}\" will be expected as \"${expected}\"`,\n fix: renameFix(table.sqlName, constraint.name, expected),\n });\n};\n\nexport const primaryKey = (\n table: TableFacts,\n declared: PulledTable,\n warn: (warning: PullWarning) => void,\n) => {\n const constraint = table.primaryKey;\n\n if (!constraint) {\n const id = declared.members.find((member) => member.key === \"id\");\n\n if (id?.kind === \"column\" && id.nullable) {\n // schema() would infer a primary key from \"id\", which must not be nullable.\n declared.members.splice(declared.members.indexOf(id), 1);\n declared.skipped.push({\n sqlName: id.sqlName,\n dataType:\n table.columns.find((column) => column.column_name === id.sqlName)\n ?.data_type ?? \"\",\n reason: 'a nullable \"id\" without a primary key cannot be declared',\n });\n warn({\n code: \"primary-key\",\n table: table.sqlName,\n column: id.sqlName,\n message: `\"${table.sqlName}\" has no primary key and its \"id\" column is nullable; the column is left out because the schema would make it the key`,\n fix: `ALTER TABLE ${quoteSql(table.sqlName)} ALTER COLUMN \"id\" SET NOT NULL, ADD PRIMARY KEY (\"id\");`,\n });\n } else if (id) {\n warn({\n code: \"primary-key\",\n table: table.sqlName,\n message: `\"${table.sqlName}\" has no primary key, but the schema treats its \"id\" column as one`,\n fix: `ALTER TABLE ${quoteSql(table.sqlName)} ADD PRIMARY KEY (\"id\");`,\n });\n } else {\n warn({\n code: \"primary-key\",\n table: table.sqlName,\n message: `\"${table.sqlName}\" has no primary key; other tables cannot reference it`,\n });\n }\n\n return;\n }\n\n primaryKeyName(table, declared, warn);\n\n const members = constraint.columns.map((column) =>\n declared.members.find((member) => member.sqlName === column),\n );\n\n if (members.some((member) => !member)) {\n warn({\n code: \"primary-key\",\n table: table.sqlName,\n object: constraint.name,\n message: `primary key \"${constraint.name}\" includes a column the schema could not declare`,\n });\n\n return;\n }\n\n const [single] = members as PulledMember[];\n\n if (members.length === 1 && single!.kind === \"column\") {\n if (single!.key !== \"id\") {\n single!.primaryKey = true;\n }\n\n return;\n }\n\n declared.primaryKey = (members as PulledMember[]).map((member) =>\n member.kind === \"reference\" ? `${member.key}Id` : member.key,\n );\n};\n\n/** The columns a table's conditions name, with the kind of value each one holds. */\nexport const conditionScope = (\n table: TableFacts,\n declared: PulledTable,\n enumLabels: ReadonlyMap<string, string[]>,\n): ConditionScope => {\n const members = scopeMembers(declared);\n\n return new Map(\n table.columns.flatMap((column) => {\n const member = members.get(column.column_name);\n const labels =\n column.enum_name && column.enum_schema === null\n ? enumLabels.get(column.enum_name)\n : undefined;\n\n return member\n ? [\n [\n column.column_name,\n {\n source: `${declared.binding}.${member}`,\n sqlType: column.data_type,\n value: valueKind(column.data_type, labels),\n },\n ] as const,\n ]\n : [];\n }),\n );\n};\n\n/** A condition as a DSL predicate when it can be one, else as `sql` text. */\nexport const pulledCondition = (\n text: string,\n scope: ConditionScope,\n declared: PulledTable,\n): PulledCondition => {\n const predicate = declaredCondition(text, scope);\n\n return predicate\n ? { kind: \"predicate\", ...predicate }\n : {\n kind: \"sql\",\n template: interpolate(\n withoutTruthComparison(text),\n scopeMembers(declared),\n declared.binding,\n ).template,\n };\n};\n\nexport const checkMember = (\n table: TableFacts,\n constraint: CatalogConstraint,\n warn: (warning: PullWarning) => void,\n taken: Set<string>,\n): Omit<PulledCheck, \"condition\"> => {\n const comments: string[] = [];\n const suffix = `_check`;\n const prefix = `${table.sqlName}_`;\n const conventional =\n constraint.name.startsWith(prefix) && constraint.name.endsWith(suffix)\n ? naturalKey(\n constraint.name.slice(prefix.length, -suffix.length),\n table.casing,\n )\n : undefined;\n let key =\n conventional &&\n !taken.has(conventional) &&\n conventionalNames.check(table.sqlName, conventional, table.casing) ===\n constraint.name\n ? conventional\n : undefined;\n\n if (!key) {\n // A derived name over 63 bytes ends in a hash of the full name, which the key\n // cannot be read back from; the readable part after the table name stands in.\n const hashed = /^(.+)_[0-9a-f]{12}$/.exec(constraint.name);\n const source =\n hashed && hashed[1]!.startsWith(prefix)\n ? hashed[1]!.slice(prefix.length)\n : constraint.name;\n const base =\n camelKey(source) ??\n camelKey(\n source\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .replace(/_(\\d)/g, \"$1\"),\n ) ??\n `check${pascal(String(table.constraints.indexOf(constraint) + 1))}`;\n key = base;\n\n for (let ordinal = 2; taken.has(key); ordinal += 1) {\n key = `${base}${ordinal}`;\n }\n\n const expected = conventionalNames.check(table.sqlName, key, table.casing);\n comments.push(`constraint \"${constraint.name}\" is named \"${expected}\"`);\n warn({\n code: \"constraint-name\",\n table: table.sqlName,\n object: constraint.name,\n message: `check constraint \"${constraint.name}\" will be expected as \"${expected}\"`,\n fix: renameFix(table.sqlName, constraint.name, expected),\n });\n }\n\n if (constraint.no_inherit || !constraint.validated) {\n comments.push(\"declared as a plain CHECK constraint\");\n warn({\n code: \"check\",\n table: table.sqlName,\n object: constraint.name,\n message: `check constraint \"${constraint.name}\" is NO INHERIT or NOT VALID, which the schema cannot declare`,\n });\n }\n\n taken.add(key);\n\n return { key, comments };\n};\n\n/** Whether `text` is one parenthesized expression, `(…)`, quotes and strings respected. */\nexport const parenthesized = (text: string): boolean => {\n if (!text.startsWith(\"(\") || !text.endsWith(\")\")) {\n return false;\n }\n\n let depth = 0;\n\n for (let position = 0; position < text.length; position += 1) {\n const character = text[position]!;\n\n if (character === \"'\" || character === '\"') {\n // A doubled quote inside a literal or identifier continues it.\n let end = position + 1;\n\n while (end < text.length) {\n if (text[end] === character) {\n if (text[end + 1] === character) {\n end += 2;\n continue;\n }\n\n break;\n }\n\n end += 1;\n }\n\n position = end;\n continue;\n }\n\n if (character === \"(\") {\n depth += 1;\n } else if (character === \")\") {\n depth -= 1;\n\n if (depth === 0 && position < text.length - 1) {\n return false;\n }\n }\n }\n\n return depth === 0;\n};\n\n/**\n * `((expr) = true)` is how PostgreSQL prints a condition declared with `.is(true)`.\n * In a CHECK or WHERE clause the comparison changes nothing (NULL stays NULL), so\n * the inner `(expr)` is declared instead: pulling again then produces the same\n * schema, where each cycle used to wrap one more `= true`.\n */\nexport const withoutTruthComparison = (text: string): string => {\n let current = text.trim();\n\n for (;;) {\n let inner = current;\n\n while (parenthesized(inner)) {\n inner = inner.slice(1, -1).trim();\n }\n\n const operand = /^(.*?)\\s*=\\s*true$/is.exec(inner)?.[1]?.trim();\n\n if (!operand || !parenthesized(operand)) {\n return current;\n }\n\n current = operand;\n }\n};\n\nexport type IndexTools = {\n table: TableFacts;\n declared: PulledTable;\n tableNames: Set<string>;\n scope: ConditionScope;\n warn: (warning: PullWarning) => void;\n declare: (index: { exact: boolean; index: PulledIndex }) => void;\n};\n\nexport const INDEX_METHODS: ReadonlySet<string> = new Set(\n RUNTIME_INDEX_METHODS,\n);\nexport const SQL_KEYWORDS = new Set([\n \"and\",\n \"or\",\n \"not\",\n \"is\",\n \"null\",\n \"true\",\n \"false\",\n \"in\",\n \"like\",\n \"ilike\",\n \"between\",\n \"case\",\n \"when\",\n \"then\",\n \"else\",\n \"end\",\n \"distinct\",\n \"from\",\n \"similar\",\n \"to\",\n \"escape\",\n \"collate\",\n \"asc\",\n \"desc\",\n \"nulls\",\n \"first\",\n \"last\",\n \"array\",\n \"any\",\n \"all\",\n \"some\",\n \"exists\",\n \"cast\",\n \"interval\",\n \"current_date\",\n \"current_timestamp\",\n \"current_time\",\n \"localtime\",\n \"localtimestamp\",\n]);\n\n/**\n * Replaces column references in SQL text with `${table.member}` interpolations\n * and escapes the rest for a template literal. Strings, quoted identifiers,\n * function names and type names are left alone.\n */\nexport const interpolate = (\n text: string,\n members: Map<string, string>,\n tableKey: string,\n): { template: string; columns: number } => {\n let template = \"\";\n let columns = 0;\n let position = 0;\n\n while (position < text.length) {\n const character = text[position]!;\n\n if (character === \"'\") {\n let end = position + 1;\n\n while (end < text.length) {\n if (text[end] === \"'\") {\n if (text[end + 1] === \"'\") {\n end += 2;\n continue;\n }\n\n break;\n }\n\n end += 1;\n }\n\n template += escapeTemplate(text.slice(position, end + 1));\n position = end + 1;\n continue;\n }\n\n const identifier =\n character === '\"'\n ? /^\"((?:[^\"]|\"\")+)\"/.exec(text.slice(position))\n : /^[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(position));\n\n if (!identifier) {\n template += escapeTemplate(character);\n position += 1;\n continue;\n }\n\n const token = identifier[0];\n const name =\n character === '\"' ? identifier[1]!.replaceAll('\"\"', '\"') : token;\n const before = text.slice(0, position);\n const after = text.slice(position + token.length);\n const member = members.get(name);\n const isFunction = /^\\s*\\(/.test(after);\n const isTypeName =\n /::\\s*$/.test(before) ||\n /\\.\\s*$/.test(before) ||\n /\\bcollate\\s*$/i.test(before);\n const isKeyword =\n character !== '\"' && SQL_KEYWORDS.has(token.toLowerCase());\n\n if (member && !isFunction && !isTypeName && !isKeyword) {\n template += `\\${${tableKey}.${member}}`;\n columns += 1;\n } else {\n template += escapeTemplate(token);\n }\n\n position += token.length;\n }\n\n return { template, columns };\n};\n\nexport const scopeMembers = (declared: PulledTable): Map<string, string> =>\n new Map(\n declared.members.map((member) => [\n member.sqlName,\n member.kind === \"reference\" ? `${member.key}Id` : member.key,\n ]),\n );\n\n/** Declares one live index through `.indexes()` or, when its name is not derived, the schema-level `indexes` option. */\nexport const declareIndex = (\n row: IndexDetailRow,\n tools: IndexTools,\n options: { exact?: boolean },\n): void => {\n const { table, declared, warn } = tools;\n const skip = (reason: string) =>\n warn({\n code: \"index\",\n table: table.sqlName,\n object: row.index_name,\n message: `index \"${row.index_name}\" is not declared: ${reason} (${row.definition})`,\n });\n\n if (row.nulls_not_distinct) {\n return skip(\"NULLS NOT DISTINCT is not supported\");\n }\n\n if (!INDEX_METHODS.has(row.method)) {\n return skip(`unsupported access method ${row.method}`);\n }\n\n const members = scopeMembers(declared);\n const comments: string[] = [];\n const keys: IndexKeySource[] = [];\n\n for (const [position, rawKey] of row.keys.entries()) {\n const bits = row.options[position] ?? 0;\n const descending = !!(bits & 1);\n const nullsFirst = !!(bits & 2);\n const text = rawKey.trim();\n\n const operatorClass = row.opclasses[position] ?? undefined;\n // A key collation is declared as part of an expression key: `${t.code} COLLATE \"C\"`.\n const collation = row.collations[position] ?? undefined;\n const column =\n /^\"((?:[^\"]|\"\")+)\"$/.exec(text)?.[1]?.replaceAll('\"\"', '\"') ??\n (/^[a-z_][a-z0-9_]*$/.test(text) ? text : undefined);\n const nulls: IndexKeySource[\"nulls\"] | undefined =\n descending && !nullsFirst\n ? \"last\"\n : !descending && nullsFirst\n ? \"first\"\n : undefined;\n\n if (column !== undefined && collation === undefined) {\n const member = members.get(column);\n\n if (!member) {\n return skip(`column \"${column}\" is not declared`);\n }\n\n keys.push({\n kind: \"column\",\n source: member,\n descending,\n ...(nulls ? { nulls } : {}),\n ...(operatorClass ? { opclass: operatorClass } : {}),\n });\n continue;\n }\n\n // Arithmetic over columns is declared with plus() and friends.\n const computed =\n collation === undefined ? declaredKey(text, tools.scope) : undefined;\n\n if (computed !== undefined) {\n keys.push({\n kind: \"value\",\n source: computed,\n descending,\n ...(nulls ? { nulls } : {}),\n ...(operatorClass ? { opclass: operatorClass } : {}),\n });\n continue;\n }\n\n const expression = interpolate(text, members, declared.binding);\n\n if (!expression.columns) {\n return skip(\"expression keys must reference a declared column\");\n }\n\n keys.push({\n kind: \"expression\",\n source:\n collation === undefined\n ? expression.template\n : `${expression.template} COLLATE ${escapeTemplate(quoteSql(collation))}`,\n descending,\n ...(nulls ? { nulls } : {}),\n ...(operatorClass ? { opclass: operatorClass } : {}),\n });\n }\n\n const include: string[] = [];\n\n for (const rawColumn of row.included) {\n const text = rawColumn.trim();\n const column =\n /^\"((?:[^\"]|\"\")+)\"$/.exec(text)?.[1]?.replaceAll('\"\"', '\"') ?? text;\n const member = members.get(column);\n\n if (!member) {\n return skip(`INCLUDE column \"${column}\" is not declared`);\n }\n\n include.push(member);\n }\n\n const ordered = keys.some((key) => key.descending || key.nulls);\n\n if (row.is_unique && row.method !== \"btree\") {\n return skip(\"unique indexes require btree\");\n }\n\n if (\n [\"hash\", \"spgist\", \"hnsw\", \"ivfflat\"].includes(row.method) &&\n keys.length !== 1\n ) {\n return skip(`${row.method} indexes take one key`);\n }\n\n if (include.length && ![\"btree\", \"gist\", \"spgist\"].includes(row.method)) {\n return skip(`${row.method} does not support INCLUDE`);\n }\n\n if (ordered && row.method !== \"btree\") {\n return skip(\"ordered keys require btree\");\n }\n\n const where = row.predicate\n ? pulledCondition(row.predicate, tools.scope, declared)\n : undefined;\n const storage = Object.fromEntries(\n (row.reloptions ?? []).flatMap((entry) => {\n const separator = entry.indexOf(\"=\");\n\n if (separator === -1) {\n return [];\n }\n\n const name = entry.slice(0, separator).trim();\n const raw = entry.slice(separator + 1).trim();\n\n return [[name, /^-?\\d+(?:\\.\\d+)?$/.test(raw) ? Number(raw) : raw]];\n }),\n );\n const index: PulledIndex = {\n key: \"\",\n keys,\n unique: row.is_unique,\n method: row.method,\n include,\n ...(where ? { where } : {}),\n ...(Object.keys(storage).length ? { with: storage } : {}),\n comments,\n };\n const prefix = `${table.sqlName}_`;\n const suffix = \"_idx\";\n const derivedKey =\n !options.exact &&\n row.index_name.startsWith(prefix) &&\n row.index_name.endsWith(suffix)\n ? naturalKey(\n row.index_name.slice(prefix.length, -suffix.length),\n table.casing,\n )\n : undefined;\n\n if (\n derivedKey &&\n conventionalNames.index(table.sqlName, derivedKey, table.casing) ===\n row.index_name &&\n !declared.indexes.some((entry) => entry.key === derivedKey)\n ) {\n tools.declare({ exact: false, index: { ...index, key: derivedKey } });\n\n return;\n }\n\n if (\n table.casing !== \"preserve\" &&\n !/^[a-z_][a-z0-9_]*$/.test(row.index_name)\n ) {\n return skip(\n \"its name contains characters the schema cannot produce; indexes are named <table>_<key>_idx or by a lowercase schema-level key\",\n );\n }\n\n if (tools.tableNames.has(row.index_name)) {\n return skip(\"its name is also a table name\");\n }\n\n comments.push(\"name kept exactly\");\n tools.declare({ exact: true, index: { ...index, key: row.index_name } });\n};\n","/**\n * Turns the live catalog into a declaration model: which builder, modifiers and\n * default each column gets, which foreign keys become relations, which tables are\n * junctions, plus a warning for everything the DSL cannot express faithfully.\n */ import type { Casing } from \"symmetria\";\nimport { normalizeSqlType } from \"../migrations/drift\";\nimport type { CatalogConstraint } from \"../migrations/catalog\";\nimport type { IndexDetailRow, PullCatalog } from \"./catalog\";\nimport {\n chooseCasing,\n keyAllocator,\n keyFor,\n referenceKey,\n conventionalNames,\n isReservedColumnKey,\n isReservedTableKey,\n pascal,\n quoteSql,\n sqlString,\n tableBindings,\n} from \"./names\";\nimport type {\n PullWarning,\n PulledReference,\n PulledMember,\n PulledTable,\n PulledSchema,\n} from \"./pulled\";\nimport { columnMember } from \"./columns\";\nimport {\n primaryKeyName,\n primaryKey,\n conditionScope,\n pulledCondition,\n checkMember,\n type IndexTools,\n declareIndex,\n} from \"./constraints\";\n\nexport type * from \"./pulled\";\nexport { withoutTruthComparison } from \"./constraints\";\n\nexport type CatalogColumn = PullCatalog[\"columns\"][number];\n\nexport type TableFacts = {\n key: string;\n binding: string;\n sqlName: string;\n casing: Casing;\n /** Scalar member key of every column, by SQL name. */\n columnKeys: Map<string, string>;\n columns: CatalogColumn[];\n generated: Set<string>;\n constraints: CatalogConstraint[];\n indexes: IndexDetailRow[];\n primaryKey: CatalogConstraint | undefined;\n /** Eligible foreign keys by column name. */\n references: Map<string, PendingReference>;\n junction: boolean;\n};\n\nexport type PendingReference = {\n constraint: CatalogConstraint;\n key: string;\n targetSql: string;\n by?: string | undefined;\n column?: string | undefined;\n};\n\n/** Prisma's migration history table: reported, never declared. */\nexport const PRISMA_MIGRATIONS = \"_prisma_migrations\";\n\nexport const ON_DELETE: Record<string, PulledReference[\"onDelete\"]> = {\n c: \"cascade\",\n n: \"setNull\",\n a: \"noAction\",\n};\n\nexport const columnIdentifier = (name: string) =>\n /^[a-z_][a-z0-9_]*$/.test(name) ? name : quoteSql(name);\n\n/** JavaScript value type for a PostgreSQL type without a builder, as both drivers deliver it. */\nexport const customValueType = (sqlType: string): string => {\n if (/^(oid|money)$/.test(sqlType) || /^float\\d$/.test(sqlType)) {\n return \"number\";\n }\n\n if (sqlType === \"json\") {\n return \"unknown\";\n }\n\n return \"string\";\n};\n\n/** How many names a warning that covers many objects spells out. */\nexport const LISTED_NAMES = 10;\n\nexport const renameFix = (table: string, from: string, to: string) =>\n `ALTER TABLE ${quoteSql(table)} RENAME CONSTRAINT ${quoteSql(from)} TO ${quoteSql(to)};`;\n\n/**\n * Turns a serial column into `GENERATED BY DEFAULT AS IDENTITY`, what\n * `.auto.byDefault` declares. BY DEFAULT keeps inserts that supply their own id\n * working, as they did with serial. The identity continues after the highest id\n * and after the old sequence, so no id is handed out twice; the old sequence is\n * dropped. `sequence` is the regclass text of the nextval() default, already\n * quoted the way PostgreSQL prints names.\n */\nexport const serialFix = (\n tableName: string,\n columnName: string,\n sequence: string,\n): string => {\n const table = quoteSql(tableName);\n const column = quoteSql(columnName);\n\n return [\n `ALTER TABLE ${table} ALTER COLUMN ${column} DROP DEFAULT;`,\n `ALTER SEQUENCE ${sequence} OWNED BY NONE;`,\n `ALTER TABLE ${table} ALTER COLUMN ${column} ADD GENERATED BY DEFAULT AS IDENTITY;`,\n `SELECT setval(pg_get_serial_sequence(${sqlString(table)}, ${sqlString(columnName)}), GREATEST(COALESCE(MAX(${column}), 0), (SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM ${sequence})) + 1, false) FROM ${table};`,\n `DROP SEQUENCE ${sequence};`,\n ].join(\" \");\n};\n\nexport const buildPulledSchema = (catalog: PullCatalog): PulledSchema => {\n const warnings: PullWarning[] = [];\n const skippedTables: PulledSchema[\"skippedTables\"] = [];\n const schemaIndexes: PulledSchema[\"schemaIndexes\"] = [];\n const warn = (warning: PullWarning) => {\n warnings.push(warning);\n };\n\n // Enums of this schema are declared with oneOf(). A column owns its enum when\n // it is the only user and the type carries the derived `<table>_<column>_enum`\n // name; every other enum keeps its own name through typeName(), on each column\n // that uses it, so a Prisma `\"Role\"` stays `\"Role\"`.\n const enumUsers = new Map<string, CatalogColumn[]>();\n\n for (const column of catalog.columns) {\n if (column.enum_name && column.enum_schema === null) {\n const users = enumUsers.get(column.enum_name) ?? [];\n users.push(column);\n enumUsers.set(column.enum_name, users);\n }\n }\n\n const enumLabels = new Map(\n catalog.enumerations.map((entry) => [entry.name, entry.values]),\n );\n const ownsEnum = (column: CatalogColumn): boolean =>\n !!column.enum_name &&\n column.enum_schema === null &&\n enumUsers.get(column.enum_name)?.length === 1 &&\n column.enum_name ===\n conventionalNames.enumeration(column.table_name, column.column_name);\n\n // Views, materialized views and triggers have no declaration; list each one.\n const quotedList = (names: readonly string[]): string =>\n names.map((name) => `\"${name}\"`).join(\", \");\n const routines: string[] = [];\n\n for (const object of catalog.undeclared ?? []) {\n switch (object.kind) {\n case \"inheritance\":\n warn({\n code: \"inheritance\",\n table: object.name,\n object: object.definition,\n message: `\"${object.name}\" inherits from \"${object.definition}\"; the schema has no inheritance, so both are declared as separate plain tables: a database built from this schema does not show the rows of \"${object.name}\" in \"${object.definition}\"`,\n });\n break;\n case \"row security\": {\n const [state, ...policies] = object.definition.split(\"\\n\");\n const listed = policies.length\n ? ` with ${policies.length === 1 ? \"policy\" : \"policies\"} ${quotedList(policies)}`\n : \" without policies\";\n\n warn({\n code: \"row-security\",\n table: object.name,\n message:\n state === \"enabled\"\n ? `\"${object.name}\" has row-level security enabled${listed}; the schema declares neither, so a database built from this schema leaves every row of the table visible and writable`\n : `\"${object.name}\" has ${policies.length === 1 ? \"policy\" : \"policies\"} ${quotedList(policies)} but row-level security is not enabled; the schema does not declare policies and migrations neither create nor drop them`,\n });\n break;\n }\n case \"function\":\n routines.push(object.name);\n break;\n default:\n warn({\n code: object.kind === \"trigger\" ? \"trigger\" : \"view\",\n table: object.table_name ?? object.name,\n object: object.name,\n message:\n object.kind === \"trigger\"\n ? `trigger \"${object.name}\" on \"${object.table_name}\" is not declared; the schema does not manage triggers, so migrations neither create nor drop it`\n : `${object.kind} \"${object.name}\" is not declared; queries cannot reach it through the schema and migrations neither create nor drop it`,\n });\n }\n }\n\n // One entry for all routines: a schema can hold hundreds.\n const listedNames = (names: readonly string[]): string =>\n names.length > LISTED_NAMES\n ? `${quotedList(names.slice(0, LISTED_NAMES))} and ${names.length - LISTED_NAMES} more`\n : quotedList(names);\n const uniqueRoutines = [...new Set(routines)];\n\n if (uniqueRoutines.length) {\n warn({\n code: \"function\",\n message: `${uniqueRoutines.length === 1 ? \"function or procedure\" : `${uniqueRoutines.length} functions and procedures`} ${listedNames(uniqueRoutines)} ${uniqueRoutines.length === 1 ? \"is\" : \"are\"} not declared; the schema does not manage routines, so migrations neither create nor drop them and a database built from this schema lacks them`,\n });\n }\n\n // A serial column owns its sequence and an identity column hides its own;\n // any other sequence exists only in the database.\n const standalone = (catalog.sequences ?? [])\n .filter((sequence) => sequence.owner_table === null)\n .map((sequence) => sequence.name);\n\n if (standalone.length) {\n warn({\n code: \"sequence\",\n message: `${standalone.length === 1 ? \"sequence\" : `${standalone.length} sequences`} ${listedNames(standalone)} ${standalone.length === 1 ? \"is\" : \"are\"} not owned by a column and not declared; migrations neither create nor drop ${standalone.length === 1 ? \"it\" : \"them\"} and a database built from this schema lacks ${standalone.length === 1 ? \"it\" : \"them\"}`,\n });\n }\n\n const otherSchemas = catalog.otherSchemas ?? [];\n\n if (otherSchemas.length) {\n const total = otherSchemas.reduce((sum, entry) => sum + entry.tables, 0);\n\n warn({\n code: \"other-schema\",\n message: `${total} ${total === 1 ? \"table\" : \"tables\"} in ${otherSchemas.length === 1 ? \"another schema was\" : \"other schemas were\"} not read: ${otherSchemas\n .slice(0, LISTED_NAMES)\n .map((entry) => `\"${entry.schema}\" (${entry.tables})`)\n .join(\n \", \",\n )}${otherSchemas.length > LISTED_NAMES ? ` and ${otherSchemas.length - LISTED_NAMES} more` : \"\"}; pull reads one schema, here \"${catalog.schemaName}\"`,\n });\n }\n\n /**\n * The sequence a nextval() default names, when the column owns it and no\n * other default draws from it: only then can the column become an identity\n * and the sequence be dropped.\n */\n const serialSequence = (\n column: CatalogColumn,\n reference: string,\n ): { exclusive: boolean; reason: string } => {\n const sequence = (catalog.sequences ?? []).find(\n (entry) => entry.reference === reference || entry.name === reference,\n );\n\n if (\n sequence?.owner_table !== column.table_name ||\n sequence.owner_column !== column.column_name\n ) {\n return {\n exclusive: false,\n reason: \"is not owned by the column\",\n };\n }\n\n return {\n exclusive: sequence.defaults <= 1,\n reason: `is also the default of ${sequence.defaults - 1} other ${sequence.defaults === 2 ? \"column\" : \"columns\"}`,\n };\n };\n\n // -- pass 1: tables that can be declared, with their catalog facts ----------\n const facts = new Map<string, TableFacts>();\n const declarable = catalog.tables.filter(\n (table) =>\n !catalog.details.find((entry) => entry.name === table.name)?.partition &&\n table.name !== PRISMA_MIGRATIONS,\n );\n const casing = chooseCasing([\n ...declarable.map((table) => table.name),\n ...catalog.columns\n .filter((column) =>\n declarable.some((table) => table.name === column.table_name),\n )\n .map((column) => column.column_name),\n ]);\n const allocateTableKey = keyAllocator(isReservedTableKey);\n\n for (const table of catalog.tables) {\n const details = catalog.details.find((entry) => entry.name === table.name);\n\n if (table.name === PRISMA_MIGRATIONS) {\n skippedTables.push({\n sqlName: table.name,\n reason: \"Prisma's migration history; Symmetria keeps its own\",\n });\n warn({\n code: \"migration-table\",\n table: table.name,\n message: `\"${table.name}\" is Prisma's migration history and is not declared; drop it once Symmetria manages the migrations`,\n });\n continue;\n }\n\n if (details?.partition) {\n skippedTables.push({\n sqlName: table.name,\n reason: \"partitions are declared through their parent table\",\n });\n warn({\n code: \"partition\",\n table: table.name,\n message: `\"${table.name}\" is a partition; only the parent table is declared`,\n });\n continue;\n }\n\n // Names the key cannot produce are declared with `.named()`.\n const key = allocateTableKey(keyFor(table.name, casing));\n\n const layout = catalog.layout.filter(\n (entry) => entry.table_name === table.name,\n );\n const columns = catalog.columns\n .filter((entry) => entry.table_name === table.name)\n .sort((left, right) => {\n const position = (column: CatalogColumn) =>\n layout.find((entry) => entry.column_name === column.column_name)\n ?.position ?? Number.MAX_SAFE_INTEGER;\n\n return position(left) - position(right);\n });\n const constraints = catalog.constraints.filter(\n (entry) => entry.table_name === table.name,\n );\n\n if (details?.kind === \"p\") {\n warn({\n code: \"partition\",\n table: table.name,\n message: `\"${table.name}\" is partitioned; the declaration describes a plain table`,\n });\n }\n\n const allocateColumnKey = keyAllocator();\n\n facts.set(table.name, {\n key,\n binding: key,\n sqlName: table.name,\n casing,\n columnKeys: new Map(\n columns.map((column) => [\n column.column_name,\n allocateColumnKey(keyFor(column.column_name, casing)),\n ]),\n ),\n columns,\n generated: new Set(\n layout\n .filter((entry) => entry.generated !== \"\")\n .map((entry) => entry.column_name),\n ),\n constraints,\n indexes: catalog.indexDetails.filter(\n (entry) => entry.table_name === table.name,\n ),\n primaryKey: constraints.find((entry) => entry.kind === \"p\"),\n references: new Map(),\n junction: false,\n });\n }\n\n // Tables keyed like an import (`date`, `sql`) get another name in callbacks.\n const bindings = tableBindings([...facts.values()].map((table) => table.key));\n\n for (const table of facts.values()) {\n table.binding = bindings.get(table.key)!;\n }\n\n // -- pass 2: foreign keys that can become relations -------------------------\n for (const table of facts.values()) {\n const columnKeys = new Set(table.columnKeys.values());\n\n for (const constraint of table.constraints.filter(\n (entry) => entry.kind === \"f\",\n )) {\n const reason = (() => {\n const [columnName] = constraint.columns;\n const column = table.columns.find(\n (entry) => entry.column_name === columnName,\n );\n\n if (constraint.columns.length !== 1 || !column) {\n return \"composite foreign keys are not supported\";\n }\n\n if (constraint.reference_schema !== null) {\n return \"references a table in another schema\";\n }\n\n if (![\"a\", \"c\", \"r\"].includes(constraint.on_update)) {\n return \"ON UPDATE SET NULL / SET DEFAULT are not supported\";\n }\n\n if (constraint.match !== \"s\") {\n return \"MATCH FULL / PARTIAL are not supported\";\n }\n\n if (constraint.deferrable) {\n return \"deferrable constraints are not supported\";\n }\n\n if (!constraint.validated) {\n return \"the constraint is NOT VALID\";\n }\n\n if (constraint.on_delete === \"d\") {\n return \"ON DELETE SET DEFAULT is not supported\";\n }\n\n // `<relation>_id` (or `<relation>Id` when names are preserved) keeps the\n // convention; any other name becomes `.column(\"<name>\")`.\n const { key, column: explicitColumn } = referenceKey(\n columnName!,\n casing,\n );\n const conventional = explicitColumn === undefined;\n\n if (isReservedColumnKey(key)) {\n return `\"${columnName}\" does not map to a relation key`;\n }\n\n if (columnKeys.has(key) && key !== table.columnKeys.get(columnName!)) {\n return `a column already uses the key \"${key}\"`;\n }\n\n if (\n !conventional &&\n columnKeys.has(`${key}Id`) &&\n `${key}Id` !== table.columnKeys.get(columnName!)\n ) {\n return `a column already uses the key \"${key}Id\"`;\n }\n\n const target = facts.get(constraint.reference_table ?? \"\");\n\n if (!target) {\n return catalog.ignored?.includes(constraint.reference_table ?? \"\")\n ? `the referenced table \"${constraint.reference_table}\" is ignored (ignoreTables)`\n : `the referenced table \"${constraint.reference_table}\" is not declared`;\n }\n\n const [referencedName] = constraint.reference_columns;\n const targetKey = target.primaryKey?.columns;\n const isPrimary =\n targetKey?.length === 1 && targetKey[0] === referencedName;\n const isUnique = target.constraints.some(\n (entry) =>\n entry.kind === \"u\" &&\n entry.columns.length === 1 &&\n entry.columns[0] === referencedName,\n );\n\n if (!isPrimary && !isUnique) {\n return \"relations must reference a single-column primary key or UNIQUE constraint\";\n }\n\n const targetColumn = target.columns.find(\n (entry) => entry.column_name === referencedName,\n )!;\n\n if (\n normalizeSqlType(column.data_type) !==\n normalizeSqlType(targetColumn.data_type)\n ) {\n return `its type ${column.data_type} differs from the referenced key ${targetColumn.data_type}`;\n }\n\n if (column.default !== null || column.identity !== \"\") {\n return \"relation columns cannot carry a default\";\n }\n\n if (table.generated.has(columnName!)) {\n return \"generated columns cannot be relations\";\n }\n\n table.references.set(columnName!, {\n constraint,\n key,\n targetSql: target.sqlName,\n ...(isPrimary ? {} : { by: target.columnKeys.get(referencedName!)! }),\n ...(conventional ? {} : { column: columnName! }),\n });\n\n return undefined;\n })();\n\n if (reason) {\n warn({\n code: \"foreign-key\",\n table: table.sqlName,\n column: constraint.columns.join(\", \"),\n object: constraint.name,\n message: `foreign key \"${constraint.name}\" is kept as a plain column: ${reason}`,\n });\n }\n }\n }\n\n // -- pass 3: junctions and the relation namespace ---------------------------\n for (const table of facts.values()) {\n const keyColumns = table.primaryKey?.columns ?? [];\n\n table.junction =\n keyColumns.length === 2 &&\n keyColumns.every((column) => table.references.has(column)) &&\n !table.columns.some((column) => column.column_name === \"id\");\n }\n\n const relationNames = new Map<string, Set<string>>(\n [...facts.values()].map((table) => [table.sqlName, new Set<string>()]),\n );\n const claim = (tableSql: string, name: string): boolean => {\n const names = relationNames.get(tableSql)!;\n\n if (names.has(name)) {\n return false;\n }\n\n names.add(name);\n\n return true;\n };\n\n for (const table of facts.values()) {\n for (const reference of table.references.values()) {\n claim(table.sqlName, reference.key);\n }\n }\n\n for (const table of facts.values()) {\n if (!table.junction) {\n continue;\n }\n\n const [first, second] = table.primaryKey!.columns.map(\n (column) => table.references.get(column)!,\n ) as [PendingReference, PendingReference];\n const firstTarget = facts.get(first.targetSql)!;\n const secondTarget = facts.get(second.targetSql)!;\n\n if (\n first.targetSql === second.targetSql ||\n relationNames.get(first.targetSql)!.has(secondTarget.key) ||\n relationNames.get(second.targetSql)!.has(firstTarget.key)\n ) {\n table.junction = false;\n warn({\n code: \"foreign-key\",\n table: table.sqlName,\n message: `\"${table.sqlName}\" links ${first.targetSql} and ${second.targetSql} but is declared as a plain table: its many-to-many relation names would clash with existing relations`,\n });\n continue;\n }\n\n claim(first.targetSql, secondTarget.key);\n claim(second.targetSql, firstTarget.key);\n }\n\n const inverses = new Map<PendingReference, string>();\n\n for (const table of facts.values()) {\n const ordered = table.columns\n .map((column) => table.references.get(column.column_name))\n .filter((reference): reference is PendingReference => !!reference);\n\n for (const reference of ordered) {\n const self = reference.targetSql === table.sqlName;\n\n if (!self && claim(reference.targetSql, table.key)) {\n continue;\n }\n\n let name = `${table.key}By${pascal(reference.key)}`;\n let attempt = 2;\n\n while (!claim(reference.targetSql, name)) {\n name = `${table.key}By${pascal(reference.key)}${attempt}`;\n attempt += 1;\n }\n\n inverses.set(reference, name);\n }\n }\n\n // -- pass 4: declarations ---------------------------------------------------\n const tables: PulledTable[] = [];\n\n for (const table of facts.values()) {\n const declared: PulledTable = {\n key: table.key,\n binding: table.binding,\n sqlName: table.sqlName,\n junction: table.junction,\n members: [],\n indexes: [],\n checks: [],\n comments: [],\n skipped: [],\n };\n const uniqueConstraints = table.constraints.filter(\n (entry) => entry.kind === \"u\",\n );\n const primaryKeyColumns = table.primaryKey?.columns ?? [];\n const consumedIndexes = new Set<string>();\n\n const uniqueFor = (\n columnName: string,\n ): { unique: boolean; comments: string[] } => {\n const constraint = uniqueConstraints.find(\n (entry) =>\n entry.columns.length === 1 && entry.columns[0] === columnName,\n );\n\n if (!constraint) {\n // Prisma enforces uniqueness with a unique index named like the\n // constraint (`User_email_key`); the schema declares `.unique` and the\n // fix turns the index into that constraint in place, without a rebuild.\n // Other unique indexes keep their exact index declarations.\n const expected = conventionalNames.unique(table.sqlName, columnName);\n const uniqueIndex = table.indexes.find(\n (entry) =>\n entry.index_name === expected &&\n entry.is_unique &&\n entry.keys.length === 1 &&\n entry.keys[0] === columnIdentifier(columnName) &&\n entry.method === \"btree\" &&\n entry.predicate === null &&\n entry.included.length === 0 &&\n !entry.nulls_not_distinct &&\n entry.opclasses.every((opclass) => opclass === null) &&\n entry.options.every((option) => option === 0) &&\n !table.constraints.some(\n (constraint) => constraint.name === entry.index_name,\n ),\n );\n\n if (!uniqueIndex) {\n return { unique: false, comments: [] };\n }\n\n consumedIndexes.add(uniqueIndex.index_name);\n warn({\n code: \"unique-index\",\n table: table.sqlName,\n column: columnName,\n object: uniqueIndex.index_name,\n message: `\"${table.sqlName}.${columnName}\" is unique through the index \"${expected}\", not a UNIQUE constraint of that name`,\n fix: `ALTER TABLE ${quoteSql(table.sqlName)} ADD CONSTRAINT ${quoteSql(expected)} UNIQUE USING INDEX ${quoteSql(expected)};`,\n });\n\n return {\n unique: true,\n comments: [`unique index \"${expected}\" becomes a constraint`],\n };\n }\n\n const comments: string[] = [];\n const expected = conventionalNames.unique(table.sqlName, columnName);\n\n if (constraint.name !== expected) {\n comments.push(`constraint \"${constraint.name}\" is named \"${expected}\"`);\n warn({\n code: \"constraint-name\",\n table: table.sqlName,\n column: columnName,\n object: constraint.name,\n message: `unique constraint \"${constraint.name}\" will be expected as \"${expected}\"`,\n fix: renameFix(table.sqlName, constraint.name, expected),\n });\n }\n\n if (\n constraint.deferrable ||\n constraint.nulls_not_distinct ||\n !constraint.validated\n ) {\n comments.push(\"declared as a plain UNIQUE constraint\");\n warn({\n code: \"unique-constraint\",\n table: table.sqlName,\n column: columnName,\n object: constraint.name,\n message: `unique constraint \"${constraint.name}\" uses options the schema cannot declare (deferrable, NULLS NOT DISTINCT or NOT VALID)`,\n });\n }\n\n return { unique: true, comments };\n };\n\n // What `.index` creates: one ascending key with default operator class and\n // collation, no storage parameters. Anything else is declared through\n // `.indexes()` with its options.\n const plainIndexOn = (columnName: string) =>\n table.indexes.find(\n (entry) =>\n entry.keys.length === 1 &&\n entry.keys[0] === columnIdentifier(columnName) &&\n !entry.is_unique &&\n entry.method === \"btree\" &&\n entry.predicate === null &&\n entry.included.length === 0 &&\n !entry.nulls_not_distinct &&\n entry.options.every((option) => option === 0) &&\n entry.opclasses.every((opclass) => opclass === null) &&\n entry.collations.every((collation) => collation === null) &&\n !entry.reloptions?.length,\n );\n\n const indexFor = (columnName: string, unique: boolean): boolean => {\n if (unique || primaryKeyColumns.includes(columnName)) {\n return false;\n }\n\n const candidate = plainIndexOn(columnName);\n\n if (\n candidate &&\n candidate.index_name ===\n conventionalNames.columnIndex(table.sqlName, columnName)\n ) {\n consumedIndexes.add(candidate.index_name);\n\n return true;\n }\n\n return false;\n };\n\n for (const column of table.columns) {\n const reference = table.references.get(column.column_name);\n\n if (reference) {\n const { unique, comments } = uniqueFor(column.column_name);\n const member: PulledReference = {\n kind: \"reference\",\n key: reference.key,\n sqlName: column.column_name,\n target: facts.get(reference.targetSql)!.key,\n ...(reference.by === undefined ? {} : { by: reference.by }),\n ...(reference.column === undefined\n ? {}\n : { column: reference.column }),\n nullable: !column.not_null,\n unique,\n index: indexFor(column.column_name, unique),\n comments,\n };\n const onDelete = ON_DELETE[reference.constraint.on_delete];\n\n if (onDelete) {\n member.onDelete = onDelete;\n }\n\n if (reference.constraint.on_update === \"c\") {\n member.onUpdate = \"cascade\";\n } else if (reference.constraint.on_update === \"r\") {\n member.onUpdate = \"restrict\";\n }\n\n const inverse = inverses.get(reference);\n\n if (inverse) {\n member.inverse = inverse;\n }\n\n // A relation column takes the referenced key's type and collation.\n const targetCollation =\n facts\n .get(reference.targetSql)!\n .columns.find(\n (entry) =>\n entry.column_name === reference.constraint.reference_columns[0],\n )?.collation ?? null;\n\n if (column.collation !== targetCollation) {\n member.comments.push(\n `collation ${column.collation ? `\"${column.collation}\"` : \"default\"} differs from the referenced key's`,\n );\n warn({\n code: \"collation\",\n table: table.sqlName,\n column: column.column_name,\n object: column.collation ?? \"default\",\n message: `\"${table.sqlName}.${column.column_name}\" uses ${column.collation ? `collation \"${column.collation}\"` : \"the default collation\"}; a relation column takes the referenced key's ${targetCollation ? `\"${targetCollation}\"` : \"default collation\"}`,\n });\n }\n\n const expected = conventionalNames.foreignKey(\n table.sqlName,\n column.column_name,\n );\n\n if (reference.constraint.name !== expected) {\n member.comments.push(\n `constraint \"${reference.constraint.name}\" is named \"${expected}\"`,\n );\n warn({\n code: \"constraint-name\",\n table: table.sqlName,\n column: column.column_name,\n object: reference.constraint.name,\n message: `foreign key \"${reference.constraint.name}\" will be expected as \"${expected}\"`,\n fix: renameFix(table.sqlName, reference.constraint.name, expected),\n });\n }\n\n declared.members.push(member);\n continue;\n }\n\n const key = table.columnKeys.get(column.column_name)!;\n\n const member = columnMember(column, key, table, {\n ownsEnum,\n enumValues: (name) => enumLabels.get(name),\n serialSequence,\n warn,\n uniqueFor,\n indexFor,\n });\n declared.members.push(member);\n }\n\n // Junctions declare their two relations first, in primary-key order.\n if (table.junction) {\n const keyOrder = primaryKeyColumns;\n declared.members.sort((left, right) => {\n const rank = (member: PulledMember) => {\n const position = keyOrder.indexOf(member.sqlName);\n\n return position === -1 ? keyOrder.length : position;\n };\n\n return rank(left) - rank(right);\n });\n\n const second = declared.members[1] as PulledReference;\n second.index = false;\n const leading = table.indexes.find(\n (entry) =>\n entry.keys[0] === columnIdentifier(second.sqlName) ||\n entry.keys[0]?.startsWith(`${columnIdentifier(second.sqlName)} `),\n );\n const expected = conventionalNames.columnIndex(\n table.sqlName,\n second.sqlName,\n );\n\n // Prisma names a junction's key `_AToB_AB_pkey`; the schema derives `_AToB_pkey`.\n primaryKeyName(table, declared, warn);\n\n if (leading && plainIndexOn(second.sqlName)?.index_name === expected) {\n consumedIndexes.add(expected);\n } else if (!leading) {\n warn({\n code: \"junction-index\",\n table: table.sqlName,\n column: second.sqlName,\n object: expected,\n message: `junction \"${table.sqlName}\" gets an automatic index \"${expected}\" on its second key, which the database does not have`,\n fix: `CREATE INDEX ${quoteSql(expected)} ON ${quoteSql(table.sqlName)} (${quoteSql(second.sqlName)});`,\n });\n }\n } else {\n primaryKey(table, declared, warn);\n }\n\n const tableNames = new Set([...facts.keys()]);\n const indexTools: IndexTools = {\n table,\n declared,\n tableNames,\n scope: conditionScope(table, declared, enumLabels),\n warn,\n declare: (index) => {\n if (index.exact) {\n schemaIndexes.push({\n table: declared.key,\n binding: declared.binding,\n index: index.index,\n });\n } else {\n declared.indexes.push(index.index);\n }\n },\n };\n\n for (const constraint of uniqueConstraints.filter(\n (entry) => entry.columns.length !== 1,\n )) {\n const row = table.indexes.find(\n (entry) => entry.index_name === constraint.name,\n );\n const columns = constraint.columns.map(quoteSql).join(\", \");\n warn({\n code: \"unique-constraint\",\n table: table.sqlName,\n object: constraint.name,\n message: `multi-column unique constraint \"${constraint.name}\" (${constraint.columns.join(\", \")}) is declared as a unique index of the same name; the constraint itself stays undeclared`,\n fix: `ALTER TABLE ${quoteSql(table.sqlName)} DROP CONSTRAINT ${quoteSql(constraint.name)}; CREATE UNIQUE INDEX ${quoteSql(constraint.name)} ON ${quoteSql(table.sqlName)} (${columns});`,\n });\n\n if (row) {\n declareIndex(row, indexTools, { exact: true });\n }\n }\n\n const checkKeys = new Set<string>();\n\n for (const constraint of table.constraints.filter(\n (entry) => entry.kind === \"c\",\n )) {\n declared.checks.push({\n ...checkMember(table, constraint, warn, checkKeys),\n condition: pulledCondition(\n constraint.expression ?? \"TRUE\",\n indexTools.scope,\n declared,\n ),\n });\n }\n\n for (const constraint of table.constraints.filter(\n (entry) => entry.kind === \"x\",\n )) {\n warn({\n code: \"exclusion\",\n table: table.sqlName,\n object: constraint.name,\n message: `exclusion constraint \"${constraint.name}\" cannot be declared`,\n });\n }\n\n for (const index of table.indexes) {\n const owned = catalog.indexes.some(\n (entry) =>\n entry.table_name === table.sqlName &&\n entry.name === index.index_name &&\n entry.constraint,\n );\n\n if (owned || consumedIndexes.has(index.index_name)) {\n continue;\n }\n\n declareIndex(index, indexTools, {});\n }\n\n tables.push(declared);\n }\n\n // Enums used by a declared column are declared through it; the rest are listed.\n const declaredTables = new Set(facts.keys());\n const enumerations: string[] = [];\n\n for (const enumeration of catalog.enumerations) {\n const users = (enumUsers.get(enumeration.name) ?? []).filter((column) =>\n declaredTables.has(column.table_name),\n );\n\n if (users.length) {\n enumerations.push(enumeration.name);\n continue;\n }\n\n warn({\n code: \"enum\",\n object: enumeration.name,\n message: `enum \"${enumeration.name}\" is not used by a declared column and is not declared`,\n });\n }\n\n for (const extension of catalog.extensions) {\n if (\n extension.schema !== catalog.schemaName &&\n extension.schema !== \"public\"\n ) {\n warn({\n code: \"extension\",\n object: extension.name,\n message: `extension \"${extension.name}\" is installed in schema \"${extension.schema}\"; a migration generated from this schema would create it on the search_path instead`,\n });\n }\n }\n\n return {\n schemaName: catalog.schemaName,\n casing,\n tables,\n schemaIndexes,\n enumerations,\n extensions: catalog.extensions.map((extension) => extension.name),\n skippedTables,\n warnings,\n };\n};\n","/**\n * Renders a pulled schema as TypeScript source in the keyed-callback schema() form,\n * importing only the builders it uses and marking approximations with `// pull:`.\n * A foreign key is `one(users)` or `maybe(users)` on the table that holds it\n * and a slot (`posts: many`) on the table it points to.\n */\nimport { sqlKey, type Casing } from \"symmetria\";\nimport { escapeTemplate, quoteString } from \"./names\";\nimport type {\n ColumnType,\n IndexKeySource,\n PulledColumn,\n PulledCondition,\n PulledIndex,\n PulledMember,\n PulledReference,\n PulledSchema,\n PulledTable,\n} from \"./model\";\n\nexport type RenderOptions = {\n /** Name of the exported schema constant (default: appSchema). */\n readonly exportName?: string;\n /** Module specifier for the runtime import (default: symmetria). */\n readonly module?: string;\n /** Comment lines placed at the top of the file. */\n readonly header?: readonly string[];\n /** Module specifier for the pgvector entry (default: `${module}/vector`). */\n readonly vectorModule?: string;\n};\n\nconst PASSTHROUGH = `/** Driver-native values for types without a builder; replace with real codecs when convenient. */\nconst passthrough = <Value>() => ({\n encode: (value: Value): unknown => value,\n decode: (value: unknown): Value => value as Value,\n});`;\n\nconst IMPORT_ORDER = [\n \"and\",\n \"bigint\",\n \"bool\",\n \"bytea\",\n \"customType\",\n \"date\",\n \"doublePrecision\",\n \"index\",\n \"inet\",\n \"int\",\n \"interval\",\n \"jsonb\",\n \"junction\",\n \"link\",\n \"many\",\n \"maybe\",\n \"not\",\n \"numeric\",\n \"one\",\n \"oneOf\",\n \"operatorClass\",\n \"or\",\n \"real\",\n \"schema\",\n \"smallint\",\n \"sql\",\n \"table\",\n \"text\",\n \"time\",\n \"timestamp\",\n \"timestamptz\",\n \"tsvector\",\n \"uuid\",\n \"varchar\",\n];\n\nconst typeSource = (type: ColumnType, imports: Set<string>): string => {\n switch (type.kind) {\n case \"builder\":\n imports.add(type.name);\n\n return type.name === \"jsonb\"\n ? \"jsonb<unknown>()\"\n : type.precision === undefined\n ? type.name\n : `${type.name}(${type.precision})`;\n case \"varchar\":\n imports.add(\"varchar\");\n\n return type.length === undefined ? \"varchar\" : `varchar(${type.length})`;\n case \"numeric\": {\n imports.add(\"numeric\");\n const arguments_ = [type.precision, type.scale].filter(\n (part) => part !== undefined,\n );\n\n return arguments_.length\n ? `numeric(${arguments_.join(\", \")})`\n : \"numeric\";\n }\n case \"enum\":\n imports.add(\"oneOf\");\n\n return `oneOf(${type.values.map(quoteString).join(\", \")})${type.name === undefined ? \"\" : `.typeName(${quoteString(type.name)})`}`;\n case \"vector\":\n imports.add(type.half ? \"halfvec\" : \"vector\");\n\n return `${type.half ? \"halfvec\" : \"vector\"}(${type.dimensions ?? \"\"})`;\n case \"custom\":\n imports.add(\"customType\");\n\n return `customType<${type.valueType}>(${quoteString(type.sqlType)}, passthrough<${type.valueType}>())`;\n }\n};\n\nconst columnSource = (\n column: PulledColumn,\n imports: Set<string>,\n casing: Casing,\n): string => {\n let source = typeSource(column.type, imports);\n\n if (column.collation !== undefined) {\n source += `.collate(${quoteString(column.collation)})`;\n }\n\n if (column.array) {\n source += \".array\";\n }\n\n if (sqlKey(column.key, casing) !== column.sqlName) {\n source += `.named(${quoteString(column.sqlName)})`;\n }\n\n switch (column.default?.kind) {\n case \"auto\":\n source += column.default.byDefault ? \".auto.byDefault\" : \".auto\";\n break;\n case \"now\":\n source += \".now\";\n break;\n case \"v4\":\n source += \".v4\";\n break;\n case \"v7\":\n source += \".v7\";\n break;\n case \"identity\":\n imports.add(\"sql\");\n source += \".default(sql`identity`)\";\n break;\n case \"value\":\n source += `.default(${column.default.source})`;\n break;\n case \"sql\":\n imports.add(\"sql\");\n source += `.default(sql\\`${escapeTemplate(column.default.sql)}\\`)`;\n break;\n default:\n }\n\n if (column.nullable) {\n source += \".nullable\";\n }\n\n if (column.unique) {\n source += \".unique\";\n }\n\n if (column.index) {\n source += \".index\";\n }\n\n if (column.primaryKey) {\n source += \".primaryKey\";\n }\n\n return source;\n};\n\n/** Names a table handle answers to by itself; a slot cannot take one. */\nconst HANDLE_KEYS = new Set([\n \"indexes\",\n \"checks\",\n \"computed\",\n \"relations\",\n \"named\",\n \"primaryKey\",\n \"nullable\",\n \"unique\",\n \"index\",\n \"onDelete\",\n \"onUpdate\",\n \"inverse\",\n \"by\",\n \"column\",\n]);\n\n/**\n * `one(users)` / `maybe(users)`: a foreign key with its index. What decides\n * the column and the names goes inside (`users.by(\"email\").inverse(\"x\")`),\n * what the key does goes after (`.unique`, `.noIndex`, `.cascade`).\n */\nconst claimSource = (\n reference: PulledReference,\n bindings: ReadonlyMap<string, string>,\n imports: Set<string>,\n): string => {\n let target = bindings.get(reference.target) ?? reference.target;\n\n if (reference.by) {\n target += `.by(${quoteString(reference.by)})`;\n }\n\n if (reference.column) {\n target += `.column(${quoteString(reference.column)})`;\n }\n\n if (reference.inverse) {\n target += `.inverse(${quoteString(reference.inverse)})`;\n }\n\n const claim = reference.nullable ? \"maybe\" : \"one\";\n imports.add(claim);\n let source = `${claim}(${target})`;\n\n if (reference.unique) {\n source += \".unique\";\n } else if (!reference.index) {\n source += \".noIndex\";\n }\n\n if (reference.onDelete === \"cascade\" || reference.onDelete === \"setNull\") {\n source += `.${reference.onDelete}`;\n } else if (reference.onDelete) {\n source += `.onDelete.${reference.onDelete}`;\n }\n\n if (reference.onUpdate) {\n source += `.onUpdate.${reference.onUpdate}`;\n }\n\n return source;\n};\n\n/** The reverse sides a table gets from the tables that reference it, as slots. */\ntype Slots = ReadonlyMap<\n string,\n readonly { key: string; kind: \"many\" | \"one\" }[]\n>;\n\nconst tableSlots = (model: PulledSchema): Slots => {\n const slots = new Map<string, { key: string; kind: \"many\" | \"one\" }[]>();\n const members = new Map(\n model.tables.map((table) => [\n table.key,\n new Set(\n table.members.flatMap((member) =>\n member.kind === \"reference\"\n ? [member.key, `${member.key}Id`]\n : [member.key],\n ),\n ),\n ]),\n );\n\n for (const table of model.tables) {\n // A junction's references name many-to-many relations, not slots.\n if (table.junction) {\n continue;\n }\n\n for (const member of table.members) {\n if (member.kind !== \"reference\") {\n continue;\n }\n\n const key = member.inverse ?? table.key;\n const taken = slots.get(member.target) ?? [];\n\n // A slot is optional: without one the relation is still declared.\n if (\n HANDLE_KEYS.has(key) ||\n members.get(member.target)?.has(key) ||\n taken.some((slot) => slot.key === key)\n ) {\n continue;\n }\n\n taken.push({ key, kind: member.unique ? \"one\" : \"many\" });\n slots.set(member.target, taken);\n }\n }\n\n return slots;\n};\n\n/** A junction's reference: the table, then what differs from the junction's defaults. */\nconst referenceSource = (\n reference: PulledReference,\n bindings: ReadonlyMap<string, string>,\n defaultDelete?: PulledReference[\"onDelete\"],\n): string => {\n let source = bindings.get(reference.target) ?? reference.target;\n\n if (reference.by) {\n source += `.by(${quoteString(reference.by)})`;\n }\n\n if (reference.column) {\n source += `.column(${quoteString(reference.column)})`;\n }\n\n if (reference.nullable) {\n source += \".nullable\";\n }\n\n if (reference.unique) {\n source += \".unique\";\n }\n\n if (reference.index) {\n source += \".index\";\n }\n\n if (reference.onDelete && reference.onDelete !== defaultDelete) {\n source += `.onDelete.${reference.onDelete}`;\n }\n\n if (reference.onUpdate) {\n source += `.onUpdate.${reference.onUpdate}`;\n }\n\n if (reference.inverse) {\n source += `.inverse(${quoteString(reference.inverse)})`;\n }\n\n return source;\n};\n\nconst comment = (notes: readonly string[]): string =>\n notes.length ? ` // pull: ${notes.join(\"; \")}` : \"\";\n\nconst memberLine = (\n member: PulledMember,\n imports: Set<string>,\n casing: Casing,\n bindings: ReadonlyMap<string, string>,\n junction: \"junction\" | \"link\" | undefined,\n): string =>\n `${member.key}: ${\n member.kind === \"column\"\n ? columnSource(member, imports, casing)\n : junction\n ? referenceSource(\n member,\n bindings,\n junction === \"link\" ? \"cascade\" : undefined,\n )\n : claimSource(member, bindings, imports)\n },${comment(member.comments)}`;\n\n/** `{ users, date: dateTable }`: tables destructured by key under their bindings. */\nconst destructure = (\n keys: readonly string[],\n bindings: ReadonlyMap<string, string>,\n): string =>\n `{ ${keys\n .map((key) => {\n const binding = bindings.get(key) ?? key;\n\n return binding === key ? key : `${key}: ${binding}`;\n })\n .join(\", \")} }`;\n\nconst keySource = (\n key: IndexKeySource,\n tableKey: string,\n imports: Set<string>,\n): string => {\n let source =\n key.kind === \"column\"\n ? `${tableKey}.${key.source}`\n : key.kind === \"value\"\n ? key.source\n : `sql<string>\\`${key.source}\\``;\n\n if (key.descending) {\n source += \".descending\";\n } else if (key.nulls) {\n source += \".ascending\";\n }\n\n if (key.nulls) {\n source += key.nulls === \"first\" ? \".nullsFirst\" : \".nullsLast\";\n }\n\n if (key.opclass) {\n imports.add(\"operatorClass\");\n\n return `operatorClass(${source}, ${quoteString(key.opclass)})`;\n }\n\n return source;\n};\n\nconst storageSource = (options: Record<string, string | number>): string =>\n `{ ${Object.entries(options)\n .map(\n ([name, value]) =>\n `${/^[a-z_][a-z0-9_]*$/i.test(name) ? name : quoteString(name)}: ${typeof value === \"number\" ? value : quoteString(value)}`,\n )\n .join(\", \")} }`;\n\n/**\n * A CHECK or WHERE condition: a predicate as it is, or a boolean `sql`\n * expression, which is a condition by itself (`.is(true)` would add `= true`).\n */\nconst conditionSource = (\n condition: PulledCondition,\n imports: Set<string>,\n): string => {\n if (condition.kind === \"predicate\") {\n for (const name of condition.imports) {\n imports.add(name);\n }\n\n return condition.source;\n }\n\n imports.add(\"sql\");\n\n return `sql<boolean>\\`${condition.template}\\``;\n};\n\nconst indexSource = (\n index: PulledIndex,\n tableKey: string,\n imports: Set<string>,\n): string => {\n imports.add(\"index\");\n\n if (index.keys.some((key) => key.kind === \"expression\")) {\n imports.add(\"sql\");\n }\n\n let source = `index(${index.keys.map((key) => keySource(key, tableKey, imports)).join(\", \")})`;\n\n if (index.unique) {\n source += \".unique\";\n }\n\n if (index.method !== \"btree\") {\n source += `.using(${quoteString(index.method)})`;\n }\n\n if (index.include.length) {\n source += `.include(${index.include.map((member) => `${tableKey}.${member}`).join(\", \")})`;\n }\n\n if (index.with) {\n source += `.with(${storageSource(index.with)})`;\n }\n\n if (index.where) {\n source += `.where(${conditionSource(index.where, imports)})`;\n }\n\n return source;\n};\n\nconst tableSource = (\n table: PulledTable,\n imports: Set<string>,\n casing: Casing,\n bindings: ReadonlyMap<string, string>,\n slots: Slots,\n): string[] => {\n const targets = [\n ...new Set(\n table.members\n .filter(\n (member): member is PulledReference => member.kind === \"reference\",\n )\n .map((member) => member.target),\n ),\n ].sort();\n const callback = targets.length > 0;\n const indent = callback ? \" \" : \" \";\n // link() is a junction whose rows go with either side: both keys cascade.\n const junction = !table.junction\n ? undefined\n : table.members.every(\n (member) =>\n member.kind !== \"reference\" || member.onDelete === \"cascade\",\n )\n ? \"link\"\n : \"junction\";\n const constructor = junction ?? \"table\";\n imports.add(constructor);\n const declared = slots.get(table.key) ?? [];\n\n for (const slot of declared) {\n imports.add(slot.kind);\n }\n\n const body = [\n ...table.comments.map((note) => `${indent}// pull: ${note}`),\n ...table.members.map(\n (member) =>\n `${indent}${memberLine(member, imports, casing, bindings, junction)}`,\n ),\n ...declared.map((slot) => `${indent}${slot.key}: ${slot.kind},`),\n ...table.skipped.map(\n (column) =>\n `${indent}// ${column.sqlName} ${column.dataType}: pull: ${column.reason}`,\n ),\n ];\n // Chain links are rendered as line arrays so outer indentation applies to every line.\n const chain: string[][] = [];\n\n if (sqlKey(table.key, casing) !== table.sqlName) {\n chain.push([`.named(${quoteString(table.sqlName)})`]);\n }\n\n if (table.primaryKey) {\n chain.push([\n `.primaryKey((${table.binding}) => [${table.primaryKey.map((key) => `${table.binding}.${key}`).join(\", \")}])`,\n ]);\n }\n\n if (table.indexes.length) {\n chain.push([\n `.indexes((${table.binding}) => ({`,\n ...table.indexes.map(\n (index) =>\n ` ${index.key}: ${indexSource(index, table.binding, imports)},${comment(index.comments)}`,\n ),\n \"}))\",\n ]);\n }\n\n if (table.checks.length) {\n chain.push([\n `.checks((${table.binding}) => ({`,\n ...table.checks.map(\n (check) =>\n ` ${check.key}: ${conditionSource(check.condition, imports)},${comment(check.comments)}`,\n ),\n \"}))\",\n ]);\n }\n\n const chainIndent = callback ? \" \" : \" \";\n const chainLines = chain.flatMap((link, position) =>\n link.map((line, lineIndex) =>\n position === chain.length - 1 && lineIndex === link.length - 1\n ? `${chainIndent}${line},`\n : `${chainIndent}${line}`,\n ),\n );\n const closing = chainLines.length\n ? [`${indent.slice(2)}})`, ...chainLines]\n : [`${indent.slice(2)}}),`];\n\n if (!callback) {\n return [` ${table.key}: ${constructor}({`, ...body, ...closing];\n }\n\n return [\n ` ${table.key}: (${destructure(targets, bindings)}) =>`,\n ` ${constructor}({`,\n ...body,\n ...closing,\n ];\n};\n\nconst importLine = (names: readonly string[], module: string): string => {\n const single = `import { ${names.join(\", \")} } from ${quoteString(module)};`;\n\n return single.length <= 80\n ? single\n : `import {\\n${names.map((name) => ` ${name},`).join(\"\\n\")}\\n} from ${quoteString(module)};`;\n};\n\nexport const renderSchema = (\n model: PulledSchema,\n options: RenderOptions = {},\n): string => {\n const exportName = options.exportName ?? \"appSchema\";\n const module = options.module ?? \"symmetria\";\n const imports = new Set<string>([\"schema\"]);\n const bindings = new Map(\n model.tables.map((table) => [table.key, table.binding]),\n );\n const slots = tableSlots(model);\n const tables = model.tables.flatMap((table) =>\n tableSource(table, imports, model.casing, bindings, slots),\n );\n // Schema-level indexes contribute imports too, so render them before the import line.\n for (const { binding, index } of model.schemaIndexes) {\n indexSource(index, binding, imports);\n }\n const passthrough = model.tables.some((table) =>\n table.members.some(\n (member) => member.kind === \"column\" && member.type.kind === \"custom\",\n ),\n );\n const header = options.header ?? [\n `Generated by symmetria pull from schema ${quoteString(model.schemaName)}.`,\n \"Lines marked `pull:` are approximations; the command lists every warning.\",\n ];\n const schemaIndexLines = model.schemaIndexes.map(\n ({ binding, index }) =>\n ` ${/^[a-z_][a-z0-9_]*$/i.test(index.key) ? index.key : quoteString(index.key)}: ${indexSource(index, binding, imports)},${comment(index.comments)}`,\n );\n const optionLines = [\n ...(model.casing === \"preserve\" ? [` casing: \"preserve\",`] : []),\n ...(model.extensions.length\n ? [` extensions: [${model.extensions.map(quoteString).join(\", \")}],`]\n : []),\n ...(schemaIndexLines.length\n ? [\n ` indexes: (${destructure([...new Set(model.schemaIndexes.map((entry) => entry.table))].sort(), bindings)}) => ({`,\n ...schemaIndexLines,\n \" }),\",\n ]\n : []),\n ];\n const vectorBuilders = [\"halfvec\", \"vector\"].filter((name) =>\n imports.has(name),\n );\n const vectorImport = vectorBuilders.length\n ? [\n `import { ${vectorBuilders.join(\", \")} } from ${quoteString(options.vectorModule ?? `${module}/vector`)};`,\n ]\n : [];\n const sections = [\n header.map((line) => `// ${line}`).join(\"\\n\"),\n [\n importLine(\n IMPORT_ORDER.filter((name) => imports.has(name)),\n module,\n ),\n ...vectorImport,\n ].join(\"\\n\"),\n ...(passthrough ? [PASSTHROUGH] : []),\n ...(model.skippedTables.length\n ? [\n model.skippedTables\n .map(\n (table) =>\n `// pull: table \"${table.sqlName}\" skipped: ${table.reason}`,\n )\n .join(\"\\n\"),\n ]\n : []),\n optionLines.length\n ? `export const ${exportName} = schema(\\n {\\n${tables.map((line) => (line ? ` ${line}` : line)).join(\"\\n\")}\\n },\\n {\\n${optionLines.join(\"\\n\")}\\n },\\n);`\n : `export const ${exportName} = schema({\\n${tables.join(\"\\n\")}\\n});`,\n ];\n\n return `${sections.join(\"\\n\\n\")}\\n`;\n};\n","/**\n * `pullSchema()`: introspect an existing PostgreSQL schema and render it as a\n * Symmetria schema module, reporting everything that needed an approximation.\n */\nimport type { QueryExecutor } from \"symmetria\";\nimport { readPullCatalog } from \"./catalog\";\nimport { buildPulledSchema, type PullWarning } from \"./model\";\nimport { renderSchema, type RenderOptions } from \"./render\";\n\nexport type PullOptions = RenderOptions & {\n readonly execute: QueryExecutor;\n /** Schema to introspect; defaults to the connection's current_schema(). */\n readonly schemaName?: string;\n /** Location of the migration journal, which is never part of the declared schema. */\n readonly metadataSchema?: string;\n readonly metadataTable?: string;\n /**\n * Tables to leave out, such as another service's tables or PostGIS\n * `spatial_ref_sys`: they are not declared and not reviewed, and foreign keys\n * pointing to them stay plain columns, with a warning.\n */\n readonly ignoreTables?: readonly string[];\n};\n\nexport type PullResult = {\n /** The generated schema module. */\n readonly source: string;\n readonly schemaName: string;\n /** SQL names of the declared tables. */\n readonly tables: string[];\n /** Enum types declared with oneOf(), by their SQL names. */\n readonly enumerations: string[];\n /** Extensions declared through the schema options. */\n readonly extensions: string[];\n readonly warnings: PullWarning[];\n};\n\nexport const pullSchema = async (options: PullOptions): Promise<PullResult> => {\n const catalog = await readPullCatalog(options);\n const model = buildPulledSchema(catalog);\n\n return {\n source: renderSchema(model, options),\n schemaName: model.schemaName,\n tables: model.tables.map((table) => table.sqlName),\n enumerations: model.enumerations,\n extensions: model.extensions,\n warnings: model.warnings,\n };\n};\n\nexport type { PullWarning, PullWarningCode } from \"./model\";\n","/**\n * Entity-relationship graph of a schema and its Mermaid `erDiagram` rendering,\n * for README files, pull requests and documentation.\n */\nimport type { SchemaSnapshot } from \"symmetria\";\nimport {\n migrationSnapshot,\n parseMigrationSnapshot,\n type MigrationSnapshot,\n} from \"../migrations/snapshot\";\n\nexport type GraphColumn = {\n readonly name: string;\n readonly type: string;\n readonly primaryKey: boolean;\n readonly foreignKey: boolean;\n readonly unique: boolean;\n readonly nullable: boolean;\n readonly identity: boolean;\n};\n\nexport type GraphTable = {\n readonly name: string;\n readonly columns: readonly GraphColumn[];\n /** A table whose primary key is exactly its two foreign keys. */\n readonly junction: boolean;\n};\n\nexport type GraphEdge = {\n /** The referenced (parent) table. */\n readonly from: string;\n /** The referencing (child) table. */\n readonly to: string;\n readonly column: string;\n /** Relation name shown on the edge: the column without its `_id` suffix. */\n readonly label: string;\n /** The foreign key is nullable, so a child may have no parent. */\n readonly optional: boolean;\n /** The foreign key is unique, so the relation is one-to-one. */\n readonly one: boolean;\n /** The foreign key is part of the child's primary key. */\n readonly identifying: boolean;\n};\n\nexport type SchemaGraph = {\n readonly tables: readonly GraphTable[];\n readonly edges: readonly GraphEdge[];\n};\n\nexport type MermaidOptions = {\n /** Wrap the diagram in a ```mermaid fence for Markdown. */\n readonly fenced?: boolean;\n /** Leave out column lists and show only entities and relations. */\n readonly compact?: boolean;\n};\n\nconst relationLabel = (column: string): string =>\n column.endsWith(\"_id\") && column.length > 3 ? column.slice(0, -3) : column;\n\n/** Tables, columns and foreign-key edges of a declared schema or a migration snapshot. */\nexport const schemaGraph = (\n snapshot: SchemaSnapshot | MigrationSnapshot,\n): SchemaGraph => {\n const expected =\n \"version\" in snapshot\n ? parseMigrationSnapshot(snapshot)\n : migrationSnapshot(snapshot);\n // A declared schema knows its relation names; migration snapshots fall back to the column name.\n const relationNames = new Map<string, string>();\n\n if (!(\"version\" in snapshot)) {\n for (const table of snapshot.tables) {\n for (const relation of table.relations) {\n const column =\n relation.kind === \"one\" && !relation.reverse\n ? table.columns.find((entry) => entry.name === relation.foreignKey)\n : undefined;\n\n if (column) {\n relationNames.set(\n `${table.sqlName}.${column.sqlName}`,\n relation.name,\n );\n }\n }\n }\n }\n\n const edges: GraphEdge[] = [];\n const tables = expected.tables.map((table): GraphTable => {\n const primaryKey = new Set(table.primaryKey);\n const ordered = table.columns;\n const columns = ordered.map(\n (column): GraphColumn => ({\n name: column.name,\n type: column.enumeration ?? column.sqlType,\n primaryKey: primaryKey.has(column.name),\n foreignKey: !!column.references,\n unique: column.unique,\n nullable: !column.notNull,\n identity: column.identity,\n }),\n );\n\n for (const column of ordered) {\n if (column.references) {\n edges.push({\n from: column.references.table,\n to: table.name,\n column: column.name,\n label:\n relationNames.get(`${table.name}.${column.name}`) ??\n relationLabel(column.name),\n optional: !column.notNull,\n one: column.unique,\n identifying: primaryKey.has(column.name),\n });\n }\n }\n\n const keyColumns = table.columns.filter((column) =>\n primaryKey.has(column.name),\n );\n\n return {\n name: table.name,\n columns,\n junction:\n keyColumns.length === 2 &&\n keyColumns.every((column) => column.references),\n };\n });\n\n return { tables, edges };\n};\n\nconst entityName = (name: string): string =>\n /^[A-Za-z_][A-Za-z0-9_-]*$/.test(name)\n ? name\n : `\"${name.replaceAll('\"', \"#quot;\")}\"`;\n\n/** Mermaid attribute types allow letters, digits, `_`, `-`, brackets and parentheses. */\nconst attributeType = (type: string): string =>\n type.replace(/[^A-Za-z0-9_()[\\]-]/g, \"_\");\n\nconst attributeKeys = (column: GraphColumn): string => {\n const keys = [\n ...(column.primaryKey ? [\"PK\"] : []),\n ...(column.foreignKey ? [\"FK\"] : []),\n ...(column.unique && !column.primaryKey ? [\"UK\"] : []),\n ];\n\n return keys.length ? ` ${keys.join(\", \")}` : \"\";\n};\n\nconst attributeComment = (column: GraphColumn): string => {\n const notes = [\n ...(column.nullable ? [\"nullable\"] : []),\n ...(column.identity ? [\"identity\"] : []),\n ];\n\n return notes.length ? ` \"${notes.join(\", \")}\"` : \"\";\n};\n\nconst cardinality = (edge: GraphEdge): string => {\n const parent = edge.optional ? \"|o\" : \"||\";\n const child = edge.one ? \"o|\" : \"o{\";\n const line = edge.identifying ? \"--\" : \"..\";\n\n return `${parent}${line}${child}`;\n};\n\nexport const renderMermaid = (\n graph: SchemaGraph,\n options: MermaidOptions = {},\n): string => {\n const lines = [\"erDiagram\"];\n\n for (const table of graph.tables) {\n if (options.compact || !table.columns.length) {\n lines.push(` ${entityName(table.name)}`);\n continue;\n }\n\n lines.push(` ${entityName(table.name)} {`);\n\n for (const column of table.columns) {\n lines.push(\n ` ${attributeType(column.type)} ${column.name}${attributeKeys(column)}${attributeComment(column)}`,\n );\n }\n\n lines.push(\" }\");\n }\n\n if (graph.edges.length) {\n lines.push(\"\");\n }\n\n for (const edge of graph.edges) {\n lines.push(\n ` ${entityName(edge.from)} ${cardinality(edge)} ${entityName(edge.to)} : ${edge.label}`,\n );\n }\n\n const diagram = `${lines.join(\"\\n\")}\\n`;\n\n return options.fenced ? `\\`\\`\\`mermaid\\n${diagram}\\`\\`\\`\\n` : diagram;\n};\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,qBAAqB,UACzB,MAAM,OAAO,aACZ,CAAC,YAAY,WAAW,CAAC,CAAC,SAAS,MAAM,MAAM,EAAE,KAC/C,MAAM,OAAO,QACZ,MAAM,OAAO,aACb,CAAC,YAAY,WAAW,CAAC,CAAC,SAAS,MAAM,MAAM,EAAE;AAEvD,MAAa,qBAAqB,WAAsC;CACtE,MAAM,aAAgC,CAAC;CACvC,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,UAAU;CACd,IAAI,QAAkB,CAAC;CACvB,IAAI,OAAO;CAEX,IAAI,cAAc;CAClB,IAAI,SAAS;CAEb,MAAM,UAAU,QAAsB;EACpC,IAAI,SAAS;GACX,MAAM,QAAQ,MAAM;GAEpB,IACE,oBAAoB,SAAS,SAAS,EAAE,KACvC,UAAU,WAAW,MAAM,OAAO,iBAClC,UAAU,aAAa,MAAM,OAAO,eAErC,MAAM,IAAI,MACR,uEACF;GAGF,IAAI,UAAU,UAAU,MAAM,SAAS,OAAO,GAC5C,MAAM,IAAI,MACR,oEACF;GAGF,IAAI,UAAU,SAAS,MAAM,SAAS,6BAA6B,GACjE,MAAM,IAAI,MACR,iEACF;GAGF,WAAW,KAAK;IACd,KAAK,OAAO,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK;IACnC;IACA,MAAM,KAAK,KAAK;GACl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