symmetria-kit 1.0.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.
- package/LICENSE +21 -0
- package/README.md +254 -0
- package/dist/cli/query-inspect.d.ts +7 -0
- package/dist/cli/query-inspect.js +283 -0
- package/dist/cli/query-inspect.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +1656 -0
- package/dist/cli.js.map +1 -0
- package/dist/ddl-BpRIXfCw.js +284 -0
- package/dist/ddl-BpRIXfCw.js.map +1 -0
- package/dist/diff-ConfLt63.js +380 -0
- package/dist/diff-ConfLt63.js.map +1 -0
- package/dist/index.d.ts +372 -0
- package/dist/index.js +4 -0
- package/dist/schema-browser-data-BVymL_xf.js +470 -0
- package/dist/schema-browser-data-BVymL_xf.js.map +1 -0
- package/dist/src-C2mBlLSB.js +2797 -0
- package/dist/src-C2mBlLSB.js.map +1 -0
- package/dist/testing.d.ts +39 -0
- package/dist/testing.js +69 -0
- package/dist/testing.js.map +1 -0
- package/package.json +65 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-C2mBlLSB.js","names":["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/catalog.ts","../src/introspection/catalog.ts","../src/migrations/drift-expressions.ts","../src/migrations/drift-constraints.ts","../src/migrations/drift.ts","../src/migrations/execution.ts","../src/migrations/runner.ts","../src/migrations/verify.ts","../src/migrations/config.ts","../src/introspection/names.ts","../src/introspection/model.ts","../src/introspection/render.ts","../src/introspection/index.ts","../src/graph/mermaid.ts"],"sourcesContent":["/** Split PostgreSQL scripts without splitting quoted strings or function bodies. */\nexport const parseMigrationSQL = (\n script: string,\n): { sql: string; words: string[] }[] => {\n const statements: { sql: string; words: string[] }[] = [];\n let start = 0;\n let position = 0;\n let hasCode = false;\n let words: string[] = [];\n\n const finish = (end: number): void => {\n if (hasCode) {\n const first = words[0];\n\n if (\n [\n \"BEGIN\",\n \"COMMIT\",\n \"END\",\n \"ROLLBACK\",\n \"ABORT\",\n \"SAVEPOINT\",\n \"RELEASE\",\n ].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({ sql: script.slice(start, end).trim(), words });\n }\n\n hasCode = false;\n words = [];\n start = end + 1;\n };\n\n while (position < script.length) {\n const character = script[position]!;\n\n if (/\\s/.test(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 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 continue;\n }\n\n if (character === \";\") {\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 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 continue;\n }\n\n if (character === \"$\") {\n const tag = script\n .slice(position)\n .match(\n /^\\$(?:[A-Za-z_\\u0080-\\uFFFF][A-Za-z_0-9\\u0080-\\uFFFF]*)?\\$/,\n )?.[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 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 words.push(word.toUpperCase());\n position += word.length;\n } else {\n position += 1;\n }\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","import type { MigrationPlan, RenameHints } from \"./diff\";\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 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 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 (renamedTo) {\n report(\n \"caution\",\n after.name,\n `Column \"${column.name}\" is renamed to \"${renamedTo}\".`,\n \"Deploy code that tolerates both names, or add the new column and backfill it before removing the old one.\",\n renamedTo,\n );\n }\n\n compareColumn(after, column, next);\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.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 (\n before.indexes.some(\n (existing) =>\n existing.sqlName === definition.sqlName &&\n JSON.stringify(existing) === JSON.stringify(definition),\n )\n ) {\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 ): void => {\n if (\n before.sqlType !== after.sqlType ||\n before.enumeration !== after.enumeration\n ) {\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 if (renamedTo) {\n report(\n \"caution\",\n next.name,\n `Table \"${table.name}\" is renamed to \"${renamedTo}\".`,\n \"Deploy code that tolerates both names, or create a view with the old name until every deployment is updated.\",\n );\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 report(\n \"caution\",\n enumeration.name,\n `Enum \"${enumeration.name}\" is rebuilt to change its labels.`,\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/** Recover a process crash without discarding a live writer or guessing at incomplete metadata. */\nexport const recoverMigrationFiles = async (\n directory: string,\n): Promise<void> => {\n directory = resolve(directory);\n const lock = join(directory, generationLockName);\n const owner = JSON.parse(\n await readFile(join(lock, \"owner.json\"), \"utf8\"),\n ) as { pid: number; host: string };\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","/**\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 rename,\n rm,\n writeFile,\n access,\n} from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\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};\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};\ntype MigrationJournal = {\n version: 1;\n migrations: MigrationManifest[];\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\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): Promise<MigrationState> => {\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 = JSON.parse(journalText!) as MigrationJournal;\n const snapshot = parseMigrationSnapshot(JSON.parse(snapshotText!));\n\n if (\n !journal ||\n journal.version !== 1 ||\n !Array.isArray(journal.migrations) ||\n journal.migrations.length !== directories.length\n ) {\n throw new Error(\n \"symmetria: migration journal does not match SQL directories\",\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 ) {\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: checksum(canonicalJSON({ manifest, up, down })),\n });\n previousHash = manifest.after;\n previousOrdinal = Number(id.slice(0, 6));\n }\n\n if (snapshotHash(snapshot) !== previousHash) {\n throw new Error(\n \"symmetria: latest snapshot checksum does not match the migration journal\",\n );\n }\n\n return { migrations, snapshot };\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\nconst writeMigrationFiles = async (\n directory: string,\n migration: GeneratedMigration,\n manifests: MigrationManifest[],\n replaced: string[] = [],\n): Promise<void> => {\n if (\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 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 = { version: 1, migrations: manifests };\n await Promise.all([\n writeFile(join(staged, migration.id, \"up.sql\"), migration.up),\n writeFile(join(staged, migration.id, \"down.sql\"), migration.down),\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 join(staged, migration.id, \"up.sql\"),\n join(staged, migration.id, \"down.sql\"),\n ...metadataFiles.map((name) => join(staged, \"meta\", name)),\n 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 await move(join(staged, migration.id), join(directory, migration.id));\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 const plan = diffSchemas(emptySnapshot(), snapshot);\n const id = `000001_${name}`;\n const manifest: MigrationManifest = {\n version: 1,\n id,\n parent: null,\n before: snapshotHash(emptySnapshot()),\n after: snapshotHash(snapshot),\n };\n const up = formatMigrationSQL(plan.up);\n const down = formatMigrationSQL(plan.down);\n const squashed: GeneratedMigration = {\n id,\n manifest,\n snapshot,\n up,\n down,\n checksum: checksum(canonicalJSON({ 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 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 };\n const up = formatMigrationSQL(plan.up);\n const down = formatMigrationSQL(plan.down);\n const migration: GeneratedMigration = {\n id,\n manifest,\n snapshot: after,\n up,\n down,\n checksum: checksum(canonicalJSON({ manifest, up, down })),\n };\n await writeMigrationFiles(directory, migration, [\n ...migrations.map((entry) => entry.manifest),\n manifest,\n ]);\n\n return migration;\n });\n};\n","/**\n * Lints migration SQL for statements that lock or rewrite large tables, anonymous constraints and\n * volatile defaults, with safer rewrites.\n */\nimport { parseMigrationSQL } from \"./sql\";\nimport type { LintFinding } from \"./lint\";\n\nexport type SQLFinding = LintFinding & { readonly statement: number };\n\nconst LEADING_COMMENTS = String.raw`^\\s*(?:(?:--[^\\n]*(?:\\n|$)|/\\*[\\s\\S]*?\\*/)\\s*)*`;\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`${LEADING_COMMENTS}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`${LEADING_COMMENTS}(?: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);\n\nconst RECREATED_OBJECT = new RegExp(\n String.raw`(?:\\bADD\\s+CONSTRAINT\\s+(${IDENTIFIER})|\\bCREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?(${IDENTIFIER})\\s+ON\\b)`,\n \"gi\",\n);\nconst DROPPED_OBJECT = new RegExp(\n String.raw`${LEADING_COMMENTS}(?:ALTER\\s+TABLE\\b[^;]*?\\bDROP\\s+CONSTRAINT\\s+(?:IF\\s+EXISTS\\s+)?(${IDENTIFIER})|DROP\\s+INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+EXISTS\\s+)?(${IDENTIFIER}))\\s*$`,\n \"i\",\n);\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\")) ?? [])\n .map((part) =>\n part.startsWith('\"')\n ? part.slice(1, -1).replaceAll('\"\"', '\"')\n : part.toLowerCase(),\n )\n .join(\".\");\n\n/** Inspect the SQL that will execute, ignoring comments, strings and function bodies. */\nexport const lintMigrationSQL = (sql: string, name = \"SQL\"): SQLFinding[] => {\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 const statements = parseMigrationSQL(sql);\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(({ sql: statement }) =>\n [...statement.matchAll(RECREATED_OBJECT)].map(\n (match) => match[1] ?? match[2]!,\n ),\n ),\n );\n\n return statements.flatMap(\n ({ words, sql: statement }, position): SQLFinding[] => {\n const text = words.join(\" \");\n const createdTable = statement.match(CREATED_TABLE)?.[1];\n\n if (createdTable) {\n created.add(tableKey(createdTable));\n }\n\n const target = statement.match(TARGET_TABLE)?.[1];\n const newTable = target !== undefined && created.has(tableKey(target));\n\n const finding = (\n level: SQLFinding[\"level\"],\n message: string,\n advice: string,\n ): SQLFinding[] => [\n {\n level,\n table: name,\n statement: position + 1,\n message: `Statement ${position + 1}: ${message}`,\n advice,\n },\n ];\n\n // Renames change the catalog only, under a brief ACCESS EXCLUSIVE lock.\n if (\n /^ALTER (?:TABLE|INDEX|TYPE)\\b(?! .*\\bDROP\\b).*\\bRENAME\\b/.test(text)\n ) {\n return [];\n }\n\n const dropped = statement.match(DROPPED_OBJECT);\n const droppedName = dropped?.[1] ?? dropped?.[2];\n\n if (droppedName !== undefined && recreated.has(droppedName)) {\n return 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 }\n\n if (\n /^(DROP|TRUNCATE|DELETE)\\b/.test(text) ||\n /^ALTER TABLE\\b.*\\bDROP(?:$| (?!DEFAULT\\b|NOT\\b|IDENTITY\\b))/.test(\n text,\n ) ||\n /^WITH\\b.*\\bDELETE\\b/.test(text)\n ) {\n return finding(\n \"destructive\",\n \"Removes data or a database object.\",\n \"Review the exact SQL and deploy dependent application changes first.\",\n );\n }\n\n if (newTable) {\n return [];\n }\n\n // `words` holds keywords and unquoted identifiers; each ADD clause is\n // what follows its ADD. Table constraints may be named (ADD CONSTRAINT …)\n // or anonymous (ADD PRIMARY KEY …); everything else adds a column.\n const addedClauses = /^ALTER TABLE\\b/.test(text)\n ? text.split(/\\bADD\\b/).slice(1)\n : [];\n\n const isConstraint = (clause: string) =>\n /^\\s*(?:CONSTRAINT|PRIMARY KEY|UNIQUE|CHECK|FOREIGN KEY|EXCLUDE)\\b/.test(\n clause,\n );\n\n const addedConstraints = addedClauses.filter(isConstraint);\n const addedColumns = addedClauses.filter(\n (clause) => !isConstraint(clause),\n );\n\n if (\n /^ALTER TABLE\\b.*\\bSET NOT NULL\\b/.test(text) ||\n addedColumns.some(\n (clause) =>\n /\\bNOT NULL\\b/.test(clause) && !/\\bDEFAULT\\b/.test(clause),\n )\n ) {\n return finding(\n \"blocking\",\n \"Requires non-null values in existing rows.\",\n \"Backfill first, then validate the constraint.\",\n );\n }\n\n if (\n /^CREATE UNIQUE INDEX\\b/.test(text) ||\n addedConstraints.some(\n (clause) =>\n /\\b(?:UNIQUE|PRIMARY KEY)\\b/.test(clause) &&\n !/\\bUSING INDEX\\b/.test(clause),\n )\n ) {\n return finding(\n \"blocking\",\n \"Requires unique existing values.\",\n \"Check and resolve duplicates before applying.\",\n );\n }\n\n if (\n addedColumns.some((clause) =>\n /\\b(?:GENERATED\\b.*\\b(?:IDENTITY|STORED)|(?:SMALL|BIG)?SERIAL)\\b/.test(\n clause,\n ),\n )\n ) {\n return 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 if (addedColumns.length) {\n // Adding a column is a catalog change. PostgreSQL 11+ stores constant\n // and STABLE defaults (now(), transaction_timestamp()) without a rewrite;\n // only VOLATILE defaults fill every existing row.\n return addedColumns.some((clause) =>\n /\\bDEFAULT\\b.*\\b(?:CLOCK_TIMESTAMP|TIMEOFDAY|RANDOM|GEN_RANDOM_UUID|UUID_GENERATE_V\\d|NEXTVAL)\\b/.test(\n clause,\n ),\n )\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 : addedConstraints.length\n ? finding(\n \"caution\",\n \"Adds a constraint that is validated against existing rows under a lock.\",\n \"Add it NOT VALID, then VALIDATE CONSTRAINT separately on large tables.\",\n )\n : [];\n }\n\n if (/^ALTER TABLE\\b.*\\bALTER COLUMN\\b.*\\bTYPE\\b/.test(text)) {\n return 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 if (/^CREATE INDEX\\b/.test(text) && !words.includes(\"CONCURRENTLY\")) {\n return 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 if (\n /^(ALTER|UPDATE|INSERT|DO|CALL|WITH|SELECT)\\b/.test(text) ||\n /^CREATE (?:OR REPLACE )?(?:FUNCTION|PROCEDURE|TRIGGER)\\b/.test(text)\n ) {\n return 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 }\n\n if (!/^(CREATE|COMMENT|GRANT|REVOKE)\\b/.test(text)) {\n return finding(\n \"caution\",\n \"SQL is outside the static migration checks.\",\n \"Review this statement and exercise it with verify.\",\n );\n }\n\n return [];\n },\n );\n};\n","/**\n * Reads the live PostgreSQL catalog (tables, columns, constraints, indexes, enums) into a stable shape\n * used by drift detection, replay verification and rollback checks.\n */\nimport type { QueryExecutor } from \"symmetria\";\nimport { normalizeResult } from \"symmetria/internal\";\n\nexport type CatalogOptions = {\n execute: QueryExecutor;\n schemaName?: string;\n metadataSchema?: string;\n metadataTable?: string;\n};\nexport type CatalogConstraint = {\n table_name: string;\n name: string;\n kind: string;\n columns: string[];\n reference_table: string | null;\n reference_schema: string | null;\n reference_columns: string[];\n on_delete: string;\n on_update: string;\n match: string;\n deferrable: boolean;\n initially_deferred: boolean;\n no_inherit: boolean;\n nulls_not_distinct: boolean;\n validated: boolean;\n expression: string | null;\n definition: string;\n};\n\n/**\n * Installed extensions other than plpgsql. Kept out of readCatalog, whose rows are\n * compared between databases by verification.\n */\nexport const readExtensions = async (\n options: Pick<CatalogOptions, \"execute\">,\n): Promise<{ name: string; schema: string }[]> =>\n normalizeResult(\n await options.execute({\n sql: `SELECT extension.extname AS name, namespace.nspname AS schema\n FROM pg_extension extension JOIN pg_namespace namespace ON namespace.oid = extension.extnamespace\n WHERE extension.extname <> 'plpgsql' ORDER BY extension.extname COLLATE \"C\"`,\n parameters: [],\n }),\n ).rows as { name: string; schema: string }[];\n\n/** Stable catalog representation for drift, replay verification and rollback checks. */\nexport const readCatalog = async (options: CatalogOptions) => {\n const query = async <Row>(sql: string): Promise<Row[]> =>\n normalizeResult(\n await options.execute({\n sql,\n parameters: [\n options.schemaName ?? null,\n options.metadataSchema ?? \"public\",\n options.metadataTable ?? \"_symmetria_migrations\",\n ],\n }),\n ).rows as Row[];\n\n const filter =\n \"namespace.nspname = COALESCE($1, current_schema()) AND NOT (namespace.nspname = $2 AND relation.relname = $3)\";\n const tables = await query<{ name: string }>(\n `SELECT relation.relname AS name FROM pg_class relation JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace WHERE ${filter} AND relation.relkind IN ('r', 'p') ORDER BY relation.relname COLLATE \"C\"`,\n );\n const columns = await query<{\n table_name: string;\n column_name: string;\n data_type: string;\n enum_name: string | null;\n enum_schema: string | null;\n not_null: boolean;\n identity: string;\n default: string | null;\n }>(`\n SELECT relation.relname AS table_name, attribute.attname AS column_name,\n format_type(attribute.atttypid, attribute.atttypmod) AS data_type,\n CASE WHEN typ.typtype = 'e' THEN typ.typname ELSE NULL END AS enum_name,\n CASE WHEN typ.typtype = 'e' AND typ.typnamespace <> relation.relnamespace THEN typ_namespace.nspname ELSE NULL END AS enum_schema,\n attribute.attnotnull AS not_null, attribute.attidentity AS identity,\n pg_get_expr(definition.adbin, definition.adrelid) AS default\n FROM pg_attribute attribute JOIN pg_class relation ON relation.oid = attribute.attrelid\n JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace\n JOIN pg_type typ ON typ.oid = attribute.atttypid\n JOIN pg_namespace typ_namespace ON typ_namespace.oid = typ.typnamespace\n LEFT JOIN pg_attrdef definition ON definition.adrelid = relation.oid AND definition.adnum = attribute.attnum\n WHERE ${filter} AND relation.relkind IN ('r', 'p') AND attribute.attnum > 0 AND NOT attribute.attisdropped\n ORDER BY relation.relname COLLATE \"C\", attribute.attname COLLATE \"C\"`);\n // JSON lookup also works before PostgreSQL 15 added indnullsnotdistinct.\n const constraints = await query<CatalogConstraint>(`\n SELECT relation.relname AS table_name, con.conname AS name, con.contype AS kind,\n ARRAY(SELECT att.attname FROM unnest(con.conkey) WITH ORDINALITY k(num, pos) JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = k.num ORDER BY pos) AS columns,\n target.relname AS reference_table,\n CASE WHEN target.relnamespace = relation.relnamespace THEN NULL ELSE target_namespace.nspname END AS reference_schema,\n ARRAY(SELECT att.attname FROM unnest(con.confkey) WITH ORDINALITY k(num, pos) JOIN pg_attribute att ON att.attrelid = con.confrelid AND att.attnum = k.num ORDER BY pos) AS reference_columns,\n con.confdeltype AS on_delete, con.confupdtype AS on_update, con.confmatchtype AS match,\n con.condeferrable AS deferrable, con.condeferred AS initially_deferred, con.convalidated AS validated,\n con.connoinherit AS no_inherit, COALESCE((SELECT (to_jsonb(i)->>'indnullsnotdistinct')::boolean FROM pg_index i WHERE i.indexrelid = con.conindid), false) AS nulls_not_distinct,\n pg_get_expr(con.conbin, con.conrelid) AS expression, pg_get_constraintdef(con.oid) AS definition\n FROM pg_constraint con JOIN pg_class relation ON relation.oid = con.conrelid\n JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace\n LEFT JOIN pg_class target ON target.oid = con.confrelid\n LEFT JOIN pg_namespace target_namespace ON target_namespace.oid = target.relnamespace\n WHERE ${filter} AND con.contype IN ('p', 'u', 'f', 'c', 'x')\n ORDER BY relation.relname COLLATE \"C\", con.conname COLLATE \"C\"`);\n const indexes = await query<{\n table_name: string;\n name: string;\n valid: boolean;\n ready: boolean;\n definition: string;\n constraint: boolean;\n }>(`\n SELECT relation.relname AS table_name, idx.relname AS name, i.indisvalid AS valid, i.indisready AS ready,\n pg_get_indexdef(i.indexrelid) AS definition,\n EXISTS(SELECT 1 FROM pg_constraint con WHERE con.conindid = i.indexrelid AND con.contype IN ('p', 'u', 'x')) AS constraint\n FROM pg_index i JOIN pg_class relation ON relation.oid = i.indrelid JOIN pg_class idx ON idx.oid = i.indexrelid\n JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace WHERE ${filter}\n ORDER BY relation.relname COLLATE \"C\", idx.relname COLLATE \"C\"`);\n const enumerations = await query<{ name: string; values: string[] }>(`\n SELECT typ.typname AS name, array_agg(enum.enumlabel ORDER BY enum.enumsortorder) AS values\n FROM pg_type typ JOIN pg_namespace namespace ON namespace.oid = typ.typnamespace\n JOIN pg_enum enum ON enum.enumtypid = typ.oid\n WHERE namespace.nspname = COALESCE($1, current_schema()) AND $2::text IS NOT NULL AND $3::text IS NOT NULL\n GROUP BY typ.typname ORDER BY typ.typname COLLATE \"C\"`);\n\n return { tables, columns, constraints, indexes, enumerations };\n};\n","/**\n * Catalog queries that only introspection needs on top of readCatalog: column\n * declaration order, generated columns, partitioning and structured index details.\n */\nimport { normalizeResult } from \"symmetria/internal\";\nimport {\n readCatalog,\n readExtensions,\n type CatalogOptions,\n} from \"../migrations/catalog\";\n\nexport type ColumnLayoutRow = {\n table_name: string;\n column_name: string;\n position: number;\n /** attgenerated: '' for ordinary columns, 's' for stored generated columns. */\n generated: string;\n};\n\nexport type TableDetailRow = {\n name: string;\n /** relkind: 'r' ordinary table, 'p' partitioned parent. */\n kind: string;\n partition: boolean;\n};\n\nexport type IndexDetailRow = {\n table_name: string;\n index_name: string;\n is_unique: boolean;\n nulls_not_distinct: boolean;\n method: string;\n keys: string[];\n /** indoption bits per key: 1 = DESC, 2 = NULLS FIRST. */\n options: number[];\n included: string[];\n /** Non-default operator class per key, null when the default applies. */\n opclasses: (string | null)[];\n /** Storage parameters as `name=value` strings, or null. */\n reloptions: string[] | null;\n predicate: string | null;\n definition: string;\n};\n\nconst query = async <Row>(\n options: CatalogOptions,\n sql: string,\n): Promise<Row[]> =>\n normalizeResult(\n await options.execute({\n sql,\n parameters: [\n options.schemaName ?? null,\n options.metadataSchema ?? \"public\",\n options.metadataTable ?? \"_symmetria_migrations\",\n ],\n }),\n ).rows as Row[];\n\nconst filter =\n \"namespace.nspname = COALESCE($1, current_schema()) AND NOT (namespace.nspname = $2 AND relation.relname = $3)\";\n\n/** Physical column order and generated-column markers; kept apart from readCatalog, whose rows are compared across databases. */\nexport const readColumnLayout = (options: CatalogOptions) =>\n query<ColumnLayoutRow>(\n options,\n `SELECT relation.relname AS table_name, attribute.attname AS column_name,\n attribute.attnum::integer AS position, attribute.attgenerated::text AS generated\n FROM pg_attribute attribute JOIN pg_class relation ON relation.oid = attribute.attrelid\n JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace\n WHERE ${filter} AND relation.relkind IN ('r', 'p') AND attribute.attnum > 0 AND NOT attribute.attisdropped\n ORDER BY relation.relname COLLATE \"C\", attribute.attnum`,\n );\n\nexport const readTableDetails = (options: CatalogOptions) =>\n query<TableDetailRow>(\n options,\n `SELECT relation.relname AS name, relation.relkind::text AS kind, relation.relispartition AS partition\n FROM pg_class relation JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace\n WHERE ${filter} AND relation.relkind IN ('r', 'p')\n ORDER BY relation.relname COLLATE \"C\"`,\n );\n\n/** Every non-primary-key index with its keys, ordering flags, INCLUDE columns and predicate. */\nexport const readIndexDetails = (options: CatalogOptions) =>\n query<IndexDetailRow>(\n options,\n `SELECT relation.relname AS table_name, indexrelation.relname AS index_name,\n index.indisunique AS is_unique, COALESCE((to_jsonb(index)->>'indnullsnotdistinct')::boolean, false) AS nulls_not_distinct, accessmethod.amname AS method,\n ARRAY(SELECT pg_get_indexdef(index.indexrelid, position, true)\n FROM generate_series(1, index.indnkeyatts) position) AS keys,\n ARRAY(SELECT index.indoption[position - 1]::integer\n FROM generate_series(1, index.indnkeyatts) position) AS options,\n ARRAY(SELECT pg_get_indexdef(index.indexrelid, position, true)\n FROM generate_series(index.indnkeyatts + 1, index.indnatts) position) AS included,\n ARRAY(SELECT CASE WHEN opclass.opcdefault THEN NULL ELSE opclass.opcname::text END\n FROM unnest(index.indclass::oid[]) WITH ORDINALITY classes(oid, position)\n JOIN pg_opclass opclass ON opclass.oid = classes.oid ORDER BY position) AS opclasses,\n indexrelation.reloptions::text[] AS reloptions,\n pg_get_expr(index.indpred, index.indrelid, true) AS predicate,\n pg_get_indexdef(index.indexrelid) AS definition\n FROM pg_index index\n JOIN pg_class relation ON relation.oid = index.indrelid\n JOIN pg_class indexrelation ON indexrelation.oid = index.indexrelid\n JOIN pg_am accessmethod ON accessmethod.oid = indexrelation.relam\n JOIN pg_namespace namespace ON namespace.oid = relation.relnamespace\n WHERE ${filter} AND NOT index.indisprimary\n ORDER BY relation.relname COLLATE \"C\", indexrelation.relname COLLATE \"C\"`,\n );\n\nexport type PullCatalog = Awaited<ReturnType<typeof readCatalog>> & {\n schemaName: string;\n layout: ColumnLayoutRow[];\n details: TableDetailRow[];\n indexDetails: IndexDetailRow[];\n extensions: { name: string; schema: string }[];\n};\n\n/** Everything `pull` needs in one round of queries. */\nexport const readPullCatalog = async (\n options: CatalogOptions,\n): Promise<PullCatalog> => {\n const [schemaRow] = await query<{ name: string }>(\n options,\n \"SELECT COALESCE($1, current_schema()) AS name WHERE $2::text IS NOT NULL AND $3::text IS NOT NULL\",\n );\n const catalog = await readCatalog(options);\n const layout = await readColumnLayout(options);\n const details = await readTableDetails(options);\n const indexDetails = await readIndexDetails(options);\n const extensions = await readExtensions(options);\n\n return {\n ...catalog,\n schemaName: schemaRow?.name ?? options.schemaName ?? \"public\",\n layout,\n details,\n indexDetails,\n extensions,\n };\n};\n","import { normalizeResult, quoteIdentifier } from \"symmetria/internal\";\nimport type { QueryExecutor } from \"symmetria\";\n\n/** Let PostgreSQL normalize casts, parentheses and expression rewrites without scanning data. */\nexport const expressionsMatch = async (\n expected: readonly string[],\n actual: readonly string[],\n tableName: string,\n options: { execute: QueryExecutor; schemaName?: string },\n): Promise<boolean> => {\n const table = `${options.schemaName ? `${quoteIdentifier(options.schemaName)}.` : \"\"}${quoteIdentifier(tableName)}`;\n\n try {\n const result = normalizeResult(\n await options.execute({\n sql: `EXPLAIN (VERBOSE, FORMAT JSON, COSTS OFF) SELECT ${[...expected, ...actual].map((expression) => `(${expression})`).join(\", \")} FROM ${table}`,\n parameters: [],\n }),\n );\n const plan = result.rows[0]?.[\"QUERY PLAN\"] as {\n Plan: { Output: string[] };\n }[];\n const output = plan[0]!.Plan.Output;\n\n return (\n output.length === expected.length * 2 &&\n output\n .slice(0, expected.length)\n .every(\n (expression, position) =>\n expression === output[position + expected.length],\n )\n );\n } catch (error) {\n // A changed column/type can make the declared expression unresolvable.\n if (\n error &&\n typeof error === \"object\" &&\n [\"code\", \"errno\"].some((field) =>\n [\n \"42703\",\n \"42704\",\n \"42804\",\n \"42846\",\n \"42883\",\n \"22P02\",\n \"42601\",\n ].includes(String((error as Record<string, unknown>)[field])),\n )\n ) {\n return false;\n }\n\n throw error;\n }\n};\n","/**\n * Constraint-level drift: compares CHECK, UNIQUE, PRIMARY KEY and FOREIGN KEY definitions between the catalog\n * and the expected snapshot.\n */\nimport type { CatalogConstraint } from \"./catalog\";\nimport type { DriftFinding, DriftOptions } from \"./drift\";\nimport { expressionsMatch } from \"./drift-expressions\";\nimport { objectName, type MigrationTable } from \"./snapshot\";\n\nexport const constraintDrift = async (\n table: MigrationTable,\n catalog: CatalogConstraint[],\n options: DriftOptions,\n): Promise<DriftFinding[]> => {\n const findings: DriftFinding[] = [];\n const constraints: {\n name: string;\n kind: string;\n columns?: string[];\n reference?: { table: string; column: string; onDelete: string };\n expression?: string;\n }[] = [\n ...(table.primaryKey.length\n ? [\n {\n name: objectName(table.name, \"pkey\"),\n kind: \"p\",\n columns: table.primaryKey,\n },\n ]\n : []),\n ...table.columns.flatMap((column) => [\n ...(column.unique\n ? [\n {\n name: objectName(table.name, column.name, \"key\"),\n kind: \"u\",\n columns: [column.name],\n },\n ]\n : []),\n ...(column.references\n ? [\n {\n name: objectName(table.name, column.name, \"fkey\"),\n kind: \"f\",\n columns: [column.name],\n reference: column.references,\n },\n ]\n : []),\n ]),\n ...(table.checks ?? []).map((check) => ({\n name: check.sqlName,\n kind: \"c\",\n expression: check.expression,\n })),\n ];\n const liveConstraints = catalog.filter(\n (constraint) => constraint.table_name === table.name,\n );\n const actions: Record<string, string> = {\n \"no action\": \"a\",\n restrict: \"r\",\n cascade: \"c\",\n \"set null\": \"n\",\n \"set default\": \"d\",\n };\n\n for (const constraint of constraints) {\n const live = liveConstraints.find(\n (entry) => entry.name === constraint.name,\n );\n\n if (!live) {\n findings.push({\n kind: \"missing-constraint\",\n table: table.name,\n expected: constraint.name,\n });\n continue;\n }\n\n if (!live.validated) {\n findings.push({\n kind: \"invalid-constraint\",\n table: table.name,\n actual: constraint.name,\n });\n }\n\n if (\n live.kind !== constraint.kind ||\n live.deferrable ||\n live.initially_deferred ||\n (constraint.kind === \"c\" && live.no_inherit) ||\n live.nulls_not_distinct ||\n (constraint.columns &&\n JSON.stringify(constraint.columns) !== JSON.stringify(live.columns)) ||\n (constraint.reference &&\n (live.reference_table !== constraint.reference.table ||\n live.reference_schema !== null ||\n JSON.stringify(live.reference_columns) !==\n JSON.stringify([constraint.reference.column]) ||\n live.on_delete !== actions[constraint.reference.onDelete] ||\n live.on_update !== \"a\" ||\n live.match !== \"s\")) ||\n (constraint.expression &&\n (!live.expression ||\n !(await expressionsMatch(\n [constraint.expression],\n [live.expression],\n table.name,\n options,\n ))))\n ) {\n findings.push({\n kind: \"constraint-mismatch\",\n table: table.name,\n expected: constraint.name,\n actual: live.definition,\n });\n }\n }\n\n for (const constraint of liveConstraints) {\n if (!constraints.some((entry) => entry.name === constraint.name)) {\n findings.push({\n kind: \"extra-constraint\",\n table: table.name,\n actual: constraint.name,\n });\n }\n }\n\n return findings;\n};\n","/**\n * Drift detection: compares the live catalog with the expected snapshot and reports findings by kind.\n */\nimport { quoteIdentifier } from \"symmetria/internal\";\nimport type { QueryExecutor, SchemaSnapshot } from \"symmetria\";\nimport { indexSQL } from \"./ddl\";\nimport { readCatalog, readExtensions } from \"./catalog\";\nimport { readIndexDetails } from \"../introspection/catalog\";\nimport { constraintDrift } from \"./drift-constraints\";\nimport { expressionsMatch } from \"./drift-expressions\";\nimport {\n migrationSnapshot,\n parseMigrationSnapshot,\n type MigrationSnapshot,\n} from \"./snapshot\";\n\nexport type DriftKind =\n | \"missing-table\"\n | \"extra-table\"\n | \"missing-column\"\n | \"extra-column\"\n | \"type-mismatch\"\n | \"nullability-mismatch\"\n | \"default-mismatch\"\n | \"identity-mismatch\"\n | \"missing-constraint\"\n | \"extra-constraint\"\n | \"constraint-mismatch\"\n | \"invalid-constraint\"\n | \"missing-enum\"\n | \"extra-enum\"\n | \"enum-mismatch\"\n | \"invalid-index\"\n | \"missing-index\"\n | \"index-mismatch\"\n | \"extra-index\"\n | \"missing-extension\";\nexport type DriftFinding = {\n readonly kind: DriftKind;\n readonly table: string;\n readonly column?: string;\n readonly expected?: string;\n readonly actual?: string;\n};\nexport type DriftOptions = {\n readonly execute: QueryExecutor;\n readonly snapshot: SchemaSnapshot | MigrationSnapshot;\n /** Schema to inspect; defaults to the connection's current_schema(). */\n readonly schemaName?: string;\n /** Schema containing the migration journal; defaults to public. */\n readonly metadataSchema?: string;\n readonly metadataTable?: string;\n};\n\nconst indexKey = (expression: string) => {\n const ordering = /(?:\\s+(ASC|DESC))?(?:\\s+NULLS\\s+(FIRST|LAST))?$/i.exec(\n expression,\n )!;\n const descending = ordering[1]?.toUpperCase() === \"DESC\";\n\n return {\n expression: expression.slice(0, ordering.index),\n descending,\n nullsFirst: ordering[2]\n ? ordering[2].toUpperCase() === \"FIRST\"\n : descending,\n };\n};\n\nconst typeAliases: Record<string, string> = {\n int: \"integer\",\n int4: \"integer\",\n serial: \"integer\",\n int8: \"bigint\",\n bigserial: \"bigint\",\n int2: \"smallint\",\n bool: \"boolean\",\n timestamptz: \"timestamp with time zone\",\n timestamp: \"timestamp without time zone\",\n varchar: \"character varying\",\n float8: \"double precision\",\n float4: \"real\",\n time: \"time without time zone\",\n timetz: \"time with time zone\",\n};\n\n/** Compare declared and catalog types after resolving aliases such as timestamptz. */\nexport const normalizeSqlType = (sqlType: string): string => {\n const text = sqlType.trim().toLowerCase().replace(/\\s+/g, \" \");\n\n if (text.endsWith(\"[]\")) {\n return `${normalizeSqlType(text.slice(0, -2))}[]`;\n }\n\n // Precision may sit before a time-zone suffix: `time(3) without time zone`.\n const match =\n /^([a-z_][a-z0-9_. ]*?)(\\(.*?\\))?( with(?:out)? time zone)?$/.exec(text);\n\n if (!match) {\n return text;\n }\n\n const base = `${match[1]!.trim()}${match[3] ?? \"\"}`;\n const qualified = base.includes(\".\")\n ? base.slice(base.indexOf(\".\") + 1)\n : base;\n\n // format_type() prints modifiers without spaces: `numeric(12, 2)` is `numeric(12,2)`.\n return `${typeAliases[qualified] ?? qualified}${match[2]?.replace(/\\s+/g, \"\") ?? \"\"}`;\n};\n\n/**\n * Detect manual changes: tables, columns, types, nullability and declared indexes\n * are compared between the live catalog and the expected snapshot.\n */\nexport const detectDrift = async (\n options: DriftOptions,\n): Promise<DriftFinding[]> => {\n const expected =\n \"version\" in options.snapshot\n ? parseMigrationSnapshot(options.snapshot)\n : migrationSnapshot(options.snapshot);\n const catalog = await readCatalog(options);\n const columns = catalog.columns;\n const indexes = await readIndexDetails(options);\n const findings: DriftFinding[] = [];\n const actualTables = new Map<\n string,\n Map<string, { type: string; notNull: boolean }>\n >();\n\n for (const table of catalog.tables) {\n actualTables.set(table.name, new Map());\n }\n\n for (const row of columns) {\n const table = actualTables.get(row.table_name) ?? new Map();\n table.set(row.column_name, { type: row.data_type, notNull: row.not_null });\n actualTables.set(row.table_name, table);\n }\n\n for (const table of expected.tables) {\n const actual = actualTables.get(table.name);\n\n if (!actual) {\n findings.push({ kind: \"missing-table\", table: table.name });\n continue;\n }\n\n for (const column of table.columns) {\n const live = actual.get(column.name);\n\n if (!live) {\n findings.push({\n kind: \"missing-column\",\n table: table.name,\n column: column.name,\n });\n continue;\n }\n\n const details = catalog.columns.find(\n (entry) =>\n entry.table_name === table.name && entry.column_name === column.name,\n )!;\n const expectedType = normalizeSqlType(\n column.enumeration ?? column.sqlType,\n );\n const actualType = normalizeSqlType(live.type);\n\n if (\n column.enumeration\n ? details.enum_name !== column.enumeration ||\n details.enum_schema !== null\n : expectedType !== actualType\n ) {\n findings.push({\n kind: \"type-mismatch\",\n table: table.name,\n column: column.name,\n expected: expectedType,\n actual: actualType,\n });\n }\n\n if (column.notNull !== live.notNull) {\n findings.push({\n kind: \"nullability-mismatch\",\n table: table.name,\n column: column.name,\n expected: column.notNull ? \"NOT NULL\" : \"NULL\",\n actual: live.notNull ? \"NOT NULL\" : \"NULL\",\n });\n }\n\n if (details.identity !== (column.identity ? \"a\" : \"\")) {\n findings.push({\n kind: \"identity-mismatch\",\n table: table.name,\n column: column.name,\n expected: column.identity ? \"GENERATED ALWAYS\" : \"none\",\n actual:\n details.identity === \"a\"\n ? \"GENERATED ALWAYS\"\n : details.identity === \"d\"\n ? \"GENERATED BY DEFAULT\"\n : \"none\",\n });\n }\n\n if (\n (column.default === undefined) !== (details.default === null) ||\n (column.default !== undefined &&\n details.default !== null &&\n !(await expressionsMatch(\n [\n `(${column.default})::${column.enumeration ? quoteIdentifier(column.enumeration) : column.sqlType}`,\n ],\n [\n `(${details.default})::${column.enumeration ? quoteIdentifier(column.enumeration) : column.sqlType}`,\n ],\n table.name,\n options,\n )))\n ) {\n findings.push({\n kind: \"default-mismatch\",\n table: table.name,\n column: column.name,\n ...(column.default === undefined ? {} : { expected: column.default }),\n ...(details.default === null ? {} : { actual: details.default }),\n });\n }\n }\n\n for (const columnName of actual.keys()) {\n if (!table.columns.some((column) => column.name === columnName)) {\n findings.push({\n kind: \"extra-column\",\n table: table.name,\n column: columnName,\n });\n }\n }\n\n const liveIndexes = indexes.filter((row) => row.table_name === table.name);\n\n for (const index of catalog.indexes.filter(\n (index) =>\n index.table_name === table.name && (!index.valid || !index.ready),\n )) {\n findings.push({\n kind: \"invalid-index\",\n table: table.name,\n actual: index.name,\n });\n }\n\n findings.push(\n ...(await constraintDrift(table, catalog.constraints, options)),\n );\n\n for (const definition of table.indexes) {\n const live = liveIndexes.find(\n (row) => row.index_name === definition.sqlName,\n );\n\n if (!live) {\n findings.push({\n kind: \"missing-index\",\n table: table.name,\n expected: definition.sqlName,\n });\n continue;\n }\n\n const declaredKeys = definition.keys.map(indexKey);\n\n if (\n definition.unique !== live.is_unique ||\n live.nulls_not_distinct ||\n definition.method !== live.method ||\n declaredKeys.length !== live.keys.length ||\n definition.include.length !== live.included.length ||\n declaredKeys.some(\n (_key, position) =>\n (definition.opclasses?.[position] ?? null) !==\n (live.opclasses[position] ?? null),\n ) ||\n !sameStorage(definition.with, live.reloptions) ||\n declaredKeys.some(\n (key, position) =>\n key.descending !== !!(live.options[position]! & 1) ||\n key.nullsFirst !== !!(live.options[position]! & 2),\n ) ||\n !(await expressionsMatch(\n [\n ...declaredKeys.map((key) => key.expression),\n ...definition.include,\n definition.where ?? \"TRUE\",\n ],\n [...live.keys, ...live.included, live.predicate ?? \"TRUE\"],\n table.name,\n options,\n ))\n ) {\n findings.push({\n kind: \"index-mismatch\",\n table: table.name,\n expected: indexSQL(table, definition),\n actual: live.definition,\n });\n }\n }\n\n for (const { index_name: name } of liveIndexes) {\n const declared =\n table.indexes.some((definition) => definition.sqlName === name) ||\n catalog.indexes.some(\n (index) =>\n index.table_name === table.name &&\n index.name === name &&\n index.constraint,\n );\n\n if (!declared) {\n findings.push({ kind: \"extra-index\", table: table.name, actual: name });\n }\n }\n }\n\n for (const name of actualTables.keys()) {\n if (!expected.tables.some((table) => table.name === name)) {\n findings.push({ kind: \"extra-table\", table: name });\n }\n }\n\n for (const enumeration of expected.enumerations) {\n const live = catalog.enumerations.find(\n (entry) => entry.name === enumeration.name,\n );\n\n if (!live) {\n findings.push({ kind: \"missing-enum\", table: enumeration.name });\n } else if (\n JSON.stringify(live.values) !== JSON.stringify(enumeration.values)\n ) {\n findings.push({\n kind: \"enum-mismatch\",\n table: enumeration.name,\n expected: JSON.stringify(enumeration.values),\n actual: JSON.stringify(live.values),\n });\n }\n }\n\n for (const enumeration of catalog.enumerations) {\n if (\n !expected.enumerations.some((entry) => entry.name === enumeration.name)\n ) {\n findings.push({ kind: \"extra-enum\", table: enumeration.name });\n }\n }\n\n if (expected.extensions?.length) {\n const installed = new Set(\n (await readExtensions(options)).map((extension) => extension.name),\n );\n\n for (const name of expected.extensions) {\n if (!installed.has(name)) {\n findings.push({ kind: \"missing-extension\", table: name });\n }\n }\n }\n\n return findings;\n};\n\n/** `WITH (m = 16)` versus pg_class.reloptions `[\"m=16\"]`, compared as normalized name=value sets. */\nconst sameStorage = (\n declared: Readonly<Record<string, string | number>> | undefined,\n live: readonly string[] | null,\n): boolean => {\n const normalize = (entries: readonly string[]) =>\n entries\n .map((entry) => {\n const separator = entry.indexOf(\"=\");\n\n return `${entry.slice(0, separator).trim().toLowerCase()}=${entry\n .slice(separator + 1)\n .trim()\n .replace(/^'(.*)'$/, \"$1\")}`;\n })\n .sort();\n const expected = normalize(\n Object.entries(declared ?? {}).map(([name, value]) => `${name}=${value}`),\n );\n const actual = normalize(live ?? []);\n\n return JSON.stringify(expected) === JSON.stringify(actual);\n};\n\nexport const formatDriftFindings = (\n findings: readonly DriftFinding[],\n): string =>\n findings.length\n ? findings\n .map((finding) => {\n const target = `${quoteIdentifier(finding.table)}${finding.column ? `.${quoteIdentifier(finding.column)}` : \"\"}`;\n const details =\n finding.expected !== undefined || finding.actual !== undefined\n ? ` (expected ${finding.expected ?? \"nothing\"}, found ${finding.actual ?? \"nothing\"})`\n : \"\";\n\n return `${finding.kind.padEnd(21)} ${target}${details}`;\n })\n .join(\"\\n\")\n : \"No schema drift detected.\";\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\nexport const executionPlan = (\n migrations: Migration[],\n direction: \"up\" | \"down\",\n): ExecutionStep[] => {\n let group = 0;\n let previous = \"\";\n\n return migrations.map((migration) => {\n const transaction = migration.manifest.transaction ?? \"batch\";\n\n if (transaction !== \"batch\" || previous !== \"batch\") {\n group++;\n }\n\n previous = transaction;\n const statements = splitMigrationSQL(migration[direction]);\n\n if (\n transaction !== \"none\" &&\n parseMigrationSQL(migration[direction]).some(\n ({ words }) => words.includes(\"CONCURRENTLY\") || words[0] === \"VACUUM\",\n )\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\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 constructor(\n migration: string,\n direction: \"up\" | \"down\",\n statement: number,\n sql: string,\n cause: unknown,\n ) {\n const state = sqlState(cause);\n super(\n `symmetria: migration \"${migration}\" failed (${direction}, statement ${statement}${state ? `, SQLSTATE ${state}` : \"\"}): ${cause instanceof Error ? cause.message : String(cause)}\\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 }\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/** Session locks survive commits; transaction-only drivers retain atomic-batch support. */\nexport const withMigrationConnection = async <Result>(\n driver: Driver,\n lock: string,\n options: ExecutionOptions,\n callback: (session: SessionDriver, atomic: boolean) => Promise<Result>,\n): Promise<Result> => {\n const advisory = options.advisoryLockTimeoutMs ?? 10000;\n const ddl = options.lockTimeoutMs ?? 5000;\n const statement = options.statementTimeoutMs ?? 600000;\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 const run = async (session: SessionDriver, atomic: boolean) => {\n options.signal?.throwIfAborted();\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\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 const started = performance.now();\n\n while (true) {\n options.signal?.throwIfAborted();\n lockAttempted = true;\n const acquired = await executeSQL(\n session.execute,\n `SELECT pg_try_advisory_${atomic ? \"xact_\" : \"\"}lock(1937339476, hashtext($1)) AS locked`,\n [lock],\n options.signal,\n );\n\n if (acquired.rows[0]?.locked) {\n break;\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 await delay(\n Math.min(50, advisory),\n undefined,\n options.signal ? { signal: options.signal } : {},\n );\n }\n\n await executeSQL(\n session.execute,\n \"SELECT set_config('lock_timeout', $1, $4), set_config('statement_timeout', $2, $4), set_config('standard_conforming_strings', $3, $4)\",\n [`${ddl}ms`, `${statement}ms`, \"on\", atomic],\n );\n\n return await callback(session, atomic);\n } finally {\n options.signal?.removeEventListener(\"abort\", abort);\n await cancellation?.catch(() => {});\n\n if (!atomic) {\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 executeSQL(\n session.execute,\n \"SELECT pg_advisory_unlock(1937339476, hashtext($1))\",\n [lock],\n );\n }\n }\n }\n }\n };\n\n if (driver.session) {\n return driver.session((session) => run(session, false));\n }\n\n if (!driver.transaction) {\n throw new Error(\n \"symmetria: migrations require a transaction-capable driver\",\n );\n }\n\n return driver.transaction(\n (tx: TransactionDriver) =>\n run(\n { execute: tx.execute, transaction: (callback) => callback(tx) },\n true,\n ),\n { isolationLevel: \"read committed\" },\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 type { QueryExecutor } from \"symmetria\";\nimport type { Driver, SessionDriver } from \"symmetria/driver\";\nimport {\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 executeSQL,\n executionPlan,\n withMigrationConnection,\n type ExecutionOptions,\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};\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\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: (session: SessionDriver, atomic: boolean) => Promise<Result>,\n ) => withMigrationConnection(options.driver, lockName, options, callback);\n\n const readHistory = async (\n execute: QueryExecutor,\n create: boolean,\n ): Promise<HistoryEntry[]> => {\n if (create) {\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())`,\n );\n await executeSQL(\n execute,\n `ALTER TABLE ${qualifiedName} ADD COLUMN IF NOT EXISTS state text NOT NULL DEFAULT 'applied', ADD COLUMN IF NOT EXISTS direction text NOT NULL DEFAULT 'up', ADD COLUMN IF NOT EXISTS statement integer NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS error text`,\n );\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 if (\n migration.checksum !== entry.checksum ||\n migration.manifest.after !== entry.snapshotHash\n ) {\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); 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 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 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\",\n );\n }\n\n const findings = await detectDrift({\n execute,\n snapshot: expected,\n metadataSchema,\n metadataTable,\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: historical verification requires verificationDatabaseUrl or a matching snapshot\",\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 const run = async (\n session: SessionDriver,\n atomic: boolean,\n migrations: Migration[],\n direction: \"up\" | \"down\",\n ) => {\n const plan = executionPlan(migrations, direction);\n\n if (atomic && plan.some((step) => step.transaction !== \"batch\")) {\n throw new Error(\n \"symmetria: each/none migrations require a session-capable driver\",\n );\n }\n\n for (let position = 0; position < migrations.length; ) {\n const step = plan[position]!;\n\n if (step.transaction === \"none\") {\n const migration = migrations[position++]!;\n await session.transaction(async (tx) => {\n await readHistory(tx.execute, true);\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\n try {\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 }\n } else {\n const group: Migration[] = [];\n\n while (position < plan.length && plan[position]!.group === step.group) {\n group.push(migrations[position++]!);\n }\n\n await session.transaction(\n async (tx) => {\n await readHistory(tx.execute, true);\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 { isolationLevel: \"read committed\" },\n );\n }\n }\n\n return migrations.map((migration) => migration.id);\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.\n const history = await inspect(\n options.driver.execute,\n migrations,\n false,\n true,\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(async (session) => {\n const history = await inspect(session.execute, migrations);\n const direction = settings.direction ?? \"up\";\n const steps = settings.steps ?? 1;\n\n if (\n direction === \"down\" &&\n (!Number.isSafeInteger(steps) || steps < 1 || steps > history.length)\n ) {\n throw new Error(\"symmetria: invalid rollback steps\");\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 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(async (session, atomic) => {\n const history = await inspect(session.execute, migrations);\n\n return run(\n session,\n atomic,\n migrations.slice(history.length, target + 1),\n \"up\",\n );\n });\n },\n rollback: async (settings: { steps?: number } = {}): 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\n return connection(async (session, atomic) => {\n const history = await inspect(session.execute, migrations);\n\n if (!history.length) {\n return [];\n }\n\n if (steps > history.length) {\n throw new Error(\n \"symmetria: rollback steps exceed the applied migration count\",\n );\n }\n\n return run(\n session,\n atomic,\n migrations.slice(history.length - steps, history.length).reverse(),\n \"down\",\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((session) =>\n session.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 if (settings.to === undefined && latest) {\n const matching = migrations.flatMap((migration, position) =>\n migration.manifest.after === latest.snapshotHash\n ? [position]\n : [],\n );\n const existing = matching.find(\n (position) =>\n migrations[position]!.id === latest.id &&\n migrations[position]!.checksum === latest.checksum,\n );\n\n if (existing === undefined && matching.length > 1) {\n throw new Error(\n \"symmetria: the database snapshot matches multiple local migrations; pass { to } to choose the baseline explicitly\",\n );\n }\n\n target = existing ?? matching[0] ?? -1;\n }\n\n if (target < 0) {\n throw new Error(\n \"symmetria: the database snapshot matches no local migration; pass { to } to baseline it explicitly\",\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((session) =>\n session.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\",\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 } 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 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 address.searchParams.delete(\"options\");\n driver = postgres({ url: address.toString(), max: 1 });\n\n if (schemaName !== \"public\") {\n await executeSQL(\n driver.execute,\n `CREATE SCHEMA ${quoteIdentifier(schemaName)}`,\n );\n }\n\n await executeSQL(\n driver.execute,\n \"SELECT set_config('search_path', $1, false)\",\n [quoteIdentifier(schemaName)],\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\n/** Reconstruct an older boundary by replaying SQL; no historical snapshots are persisted. */\nexport const verifyBoundary = async (\n options: ExecutionOptions & {\n execute: QueryExecutor;\n state: MigrationState;\n target: number;\n url: string;\n directory: string;\n metadataSchema?: string;\n metadataTable?: string;\n },\n): Promise<void> => {\n const schemaName = String(\n (await executeSQL(options.execute, \"SELECT current_schema() AS name\"))\n .rows[0]!.name,\n );\n const actual = await readCatalog({ ...options, schemaName });\n await disposableDatabase(options.url, schemaName, 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 const expected = await readCatalog({\n ...options,\n execute: driver.execute,\n schemaName,\n });\n catalogMatches(\n expected,\n actual,\n \"schema does not match the adoption/recovery target\",\n );\n });\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\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({ ...options, execute: driver.execute, schemaName });\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 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 } 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 \"inverse\",\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\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) =>\n objectName(table, snakeCase(key), \"check\"),\n index: (table: string, key: string) =>\n objectName(table, snakeCase(key), \"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 * 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 */\nimport { INDEX_METHODS as RUNTIME_INDEX_METHODS } from \"symmetria/internal\";\nimport { normalizeSqlType } from \"../migrations/drift\";\nimport type { CatalogConstraint } from \"../migrations/catalog\";\nimport type { IndexDetailRow, PullCatalog } from \"./catalog\";\nimport {\n camelKey,\n conventionalNames,\n escapeTemplate,\n isReservedColumnKey,\n isReservedTableKey,\n pascal,\n quoteSql,\n} from \"./names\";\n\nexport type PullWarningCode =\n | \"identity-by-default\"\n | \"serial\"\n | \"identity-type\"\n | \"generated-column\"\n | \"custom-type\"\n | \"constraint-name\"\n | \"foreign-key\"\n | \"unique-constraint\"\n | \"index\"\n | \"junction-index\"\n | \"check\"\n | \"enum\"\n | \"primary-key\"\n | \"name\"\n | \"partition\"\n | \"exclusion\"\n | \"extension\";\n\nexport type PullWarning = {\n readonly code: PullWarningCode;\n readonly table?: string;\n readonly column?: string;\n /** The constraint, index or type the warning is about. */\n readonly object?: string;\n readonly message: string;\n /** SQL that makes the database match what the generated schema declares. */\n readonly fix?: string;\n};\n\nexport type ColumnType =\n | {\n kind: \"builder\";\n name:\n | \"int\"\n | \"bigint\"\n | \"smallint\"\n | \"real\"\n | \"doublePrecision\"\n | \"text\"\n | \"bool\"\n | \"uuid\"\n | \"timestamptz\"\n | \"date\"\n | \"time\"\n | \"interval\"\n | \"bytea\"\n | \"inet\"\n | \"jsonb\"\n | \"tsvector\";\n }\n | { kind: \"varchar\"; length?: number }\n | { kind: \"numeric\"; precision?: number; scale?: number }\n | { kind: \"enum\"; values: string[] }\n | { kind: \"vector\"; dimensions?: number }\n | { kind: \"custom\"; sqlType: string; valueType: string };\n\nexport type ColumnDefault =\n | { kind: \"auto\" }\n | { kind: \"now\" }\n | { kind: \"v4\" }\n | { kind: \"v7\" }\n | { kind: \"identity\" }\n | { kind: \"value\"; source: string }\n | { kind: \"sql\"; sql: string };\n\nexport type PulledColumn = {\n kind: \"column\";\n key: string;\n sqlName: string;\n type: ColumnType;\n array: boolean;\n nullable: boolean;\n unique: boolean;\n index: boolean;\n primaryKey: boolean;\n default?: ColumnDefault;\n comments: string[];\n};\n\nexport type PulledReference = {\n kind: \"reference\";\n key: string;\n sqlName: string;\n /** Key of the referenced table. */\n target: string;\n /** Key of the referenced column when it is a unique column rather than the primary key. */\n by?: string;\n /** The SQL column name when it is not `<key>_id`. */\n column?: string;\n nullable: boolean;\n unique: boolean;\n index: boolean;\n onDelete?: \"cascade\" | \"setNull\" | \"noAction\";\n inverse?: string;\n comments: string[];\n};\n\nexport type PulledMember = PulledColumn | PulledReference;\n\nexport type IndexKeySource = {\n /** `column` keys name a scope member; `expression` keys hold template text with `${table.column}` interpolations. */\n kind: \"column\" | \"expression\";\n source: string;\n descending: boolean;\n nulls?: \"first\" | \"last\";\n /** Non-default operator class, rendered through operatorClass(). */\n opclass?: string;\n};\n\nexport type PulledIndex = {\n /** Object key in the indexes callback; the exact SQL name for schema-level indexes. */\n key: string;\n keys: IndexKeySource[];\n unique: boolean;\n method: string;\n /** Scope member keys. */\n include: string[];\n /** Predicate template text, already interpolated and escaped. */\n where?: string;\n /** Storage parameters from pg_class.reloptions. */\n with?: Record<string, string | number>;\n comments: string[];\n};\n\nexport type PulledCheck = {\n key: string;\n /** Predicate template text, already interpolated and escaped. */\n expression: string;\n comments: string[];\n};\n\nexport type PulledTable = {\n key: string;\n sqlName: string;\n junction: boolean;\n members: PulledMember[];\n /** Member keys of an explicit primary key callback (composite keys and keys over relations). */\n primaryKey?: string[];\n indexes: PulledIndex[];\n checks: PulledCheck[];\n comments: string[];\n skipped: { sqlName: string; dataType: string; reason: string }[];\n};\n\nexport type PulledSchema = {\n schemaName: string;\n tables: PulledTable[];\n /** Indexes whose SQL names do not follow `<table>_<key>_idx`, declared with their exact names. */\n schemaIndexes: { table: string; index: PulledIndex }[];\n /** Installed extensions other than plpgsql, declared through the schema options. */\n extensions: string[];\n skippedTables: { sqlName: string; reason: string }[];\n warnings: PullWarning[];\n};\n\ntype CatalogColumn = PullCatalog[\"columns\"][number];\n\ntype TableFacts = {\n key: string;\n sqlName: 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\ntype PendingReference = {\n constraint: CatalogConstraint;\n key: string;\n targetSql: string;\n by?: string | undefined;\n column?: string | undefined;\n};\n\nconst ON_DELETE: Record<string, PulledReference[\"onDelete\"]> = {\n c: \"cascade\",\n n: \"setNull\",\n a: \"noAction\",\n};\n\nconst 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. */\nconst customValueType = (sqlType: string): string => {\n if (/^(oid|money)$/.test(sqlType) || /^float\\d$/.test(sqlType)) {\n return \"number\";\n }\n\n if (sqlType === \"timestamp without time zone\") {\n return \"Date\";\n }\n\n if (sqlType === \"json\") {\n return \"unknown\";\n }\n\n return \"string\";\n};\n\nconst renameFix = (table: string, from: string, to: string) =>\n `ALTER TABLE ${quoteSql(table)} RENAME CONSTRAINT ${quoteSql(from)} TO ${quoteSql(to)};`;\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 // Enum ownership: a column can declare an enum with oneOf() only when it is the\n // enum's only user and the type already carries the derived name.\n const enumUsers = new Map<string, CatalogColumn[]>();\n\n for (const column of catalog.columns) {\n if (column.enum_name) {\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 // -- pass 1: tables that can be declared, with their catalog facts ----------\n const facts = new Map<string, TableFacts>();\n\n for (const table of catalog.tables) {\n const details = catalog.details.find((entry) => entry.name === table.name);\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 const key = camelKey(table.name);\n\n if (!key || isReservedTableKey(key)) {\n skippedTables.push({\n sqlName: table.name,\n reason: \"the name cannot be produced by a schema key\",\n });\n warn({\n code: \"name\",\n table: table.name,\n message: `\"${table.name}\" cannot be declared: table keys are camelCase and map to lowercase snake_case names`,\n });\n continue;\n }\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 facts.set(table.name, {\n key,\n sqlName: table.name,\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 // -- pass 2: foreign keys that can become relations -------------------------\n for (const table of facts.values()) {\n const columnKeys = new Set(\n table.columns.map((column) => camelKey(column.column_name)),\n );\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 (constraint.on_update !== \"a\") {\n return \"ON UPDATE actions 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` columns keep the convention; any other name becomes `.column(\"<name>\")`.\n const conventional =\n columnName!.endsWith(\"_id\") && columnName!.length > 3;\n const key = camelKey(\n conventional ? columnName!.slice(0, -3) : columnName!,\n );\n\n if (!key || isReservedColumnKey(key)) {\n return `\"${columnName}\" does not map to a relation key`;\n }\n\n if (columnKeys.has(key) && key !== camelKey(columnName!)) {\n return `a column already uses the key \"${key}\"`;\n }\n\n if (!conventional && columnKeys.has(`${key}Id`)) {\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 `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: camelKey(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 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 return { unique: false, comments: [] };\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 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 );\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.index(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 const inverse = inverses.get(reference);\n\n if (inverse) {\n member.inverse = inverse;\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 = camelKey(column.column_name);\n\n if (!key) {\n declared.skipped.push({\n sqlName: column.column_name,\n dataType: column.data_type,\n reason: \"the name cannot be produced by a column key\",\n });\n warn({\n code: \"name\",\n table: table.sqlName,\n column: column.column_name,\n message: `\"${table.sqlName}.${column.column_name}\" cannot be declared: column keys are camelCase and map to lowercase snake_case names`,\n });\n continue;\n }\n\n const member = columnMember(column, key, table, {\n ownsEnum,\n enumValues: (name) => enumLabels.get(name),\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.index(table.sqlName, second.sqlName);\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 warn,\n declare: (index) => {\n if (index.exact) {\n schemaIndexes.push({ table: declared.key, index: index.index });\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 for (const constraint of table.constraints.filter(\n (entry) => entry.kind === \"c\",\n )) {\n const check = checkMember(table, constraint, warn);\n check.expression = interpolate(\n check.expression,\n scopeMembers(declared),\n declared.key,\n ).template;\n declared.checks.push(check);\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 for (const enumeration of catalog.enumerations) {\n const users = enumUsers.get(enumeration.name) ?? [];\n\n if (users.length === 1 && ownsEnum(users[0]!)) {\n continue;\n }\n\n const [user] = users;\n const expected =\n users.length === 1\n ? conventionalNames.enumeration(user!.table_name, user!.column_name)\n : undefined;\n\n warn({\n code: \"enum\",\n object: enumeration.name,\n ...(user ? { table: user.table_name, column: user.column_name } : {}),\n message: users.length\n ? users.length === 1\n ? `enum \"${enumeration.name}\" is used through customType(); oneOf() expects it to be named \"${expected}\"`\n : `enum \"${enumeration.name}\" is shared by ${users.length} columns; each is declared through customType()`\n : `enum \"${enumeration.name}\" is unused and not declared`,\n ...(expected\n ? {\n fix: `ALTER TYPE ${quoteSql(enumeration.name)} RENAME TO ${quoteSql(expected)};`,\n }\n : {}),\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 tables,\n schemaIndexes,\n extensions: catalog.extensions.map((extension) => extension.name),\n skippedTables,\n warnings,\n };\n};\n\ntype ColumnTools = {\n ownsEnum: (column: CatalogColumn) => boolean;\n enumValues: (name: string) => string[] | undefined;\n warn: (warning: PullWarning) => void;\n uniqueFor: (columnName: string) => { unique: boolean; comments: string[] };\n indexFor: (columnName: string, unique: boolean) => boolean;\n};\n\nconst 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 (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\nconst 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 && !array) {\n const values = tools.ownsEnum(column)\n ? tools.enumValues(column.enum_name)\n : undefined;\n\n if (values) {\n return { type: { kind: \"enum\", values }, array: false };\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 vectorType = /^vector(?:\\((\\d+)\\))?$/.exec(base);\n\n if (vectorType && !array) {\n return {\n type: {\n kind: \"vector\",\n ...(vectorType[1] ? { dimensions: Number(vectorType[1]) } : {}),\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 const sqlType = column.data_type;\n const enumeration =\n column.enum_name && !array ? tools.enumValues(column.enum_name) : undefined;\n const valueType = enumeration\n ? enumeration.map((value) => JSON.stringify(value)).join(\" | \")\n : customValueType(base) + (normalized.endsWith(\"[]\") ? \"[]\" : \"\");\n\n if (enumeration) {\n comments.push(\n `enum \"${column.enum_name}\" is declared through customType()`,\n );\n } else {\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\n return { type: { kind: \"custom\", sqlType, valueType }, array: false };\n};\n\nconst 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\n if (column.identity !== \"\") {\n if (column.identity === \"d\") {\n comments.push(\"identity BY DEFAULT is declared as GENERATED ALWAYS\");\n tools.warn({\n code: \"identity-by-default\",\n table: table.sqlName,\n column: column.column_name,\n message: `\"${name}\" is GENERATED BY DEFAULT AS IDENTITY; the schema declares GENERATED ALWAYS`,\n fix: `ALTER TABLE ${quoteSql(table.sqlName)} ALTER COLUMN ${quoteSql(column.column_name)} SET GENERATED ALWAYS;`,\n });\n }\n\n if (\n type.kind === \"builder\" &&\n (type.name === \"int\" ||\n type.name === \"bigint\" ||\n type.name === \"smallint\") &&\n !array\n ) {\n return { 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 (type.name === \"timestamptz\" && text === \"now()\") {\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 if (/^nextval\\('[^']*'::regclass\\)$/.test(text)) {\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: `\"${name}\" is a serial column; the schema keeps its nextval() default but migrations from this schema will not create the sequence`,\n fix: `ALTER TABLE ${quoteSql(table.sqlName)} ALTER COLUMN ${quoteSql(column.column_name)} DROP DEFAULT, ALTER COLUMN ${quoteSql(column.column_name)} ADD GENERATED ALWAYS AS IDENTITY;`,\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\nconst unescapeLiteral = (text: string) => text.replaceAll(\"''\", \"'\");\n\n/** JavaScript source for defaults PostgreSQL prints as simple literals. */\nconst literalDefault = (text: string, type: ColumnType): 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\nconst 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 const expected = conventionalNames.primaryKey(table.sqlName);\n\n if (constraint.name !== expected) {\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\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\nconst checkMember = (\n table: TableFacts,\n constraint: CatalogConstraint,\n warn: (warning: PullWarning) => void,\n): PulledCheck => {\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 ? camelKey(constraint.name.slice(prefix.length, -suffix.length))\n : undefined;\n let key = conventional;\n\n if (!key) {\n key =\n camelKey(constraint.name) ??\n camelKey(\n constraint.name\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 const expected = conventionalNames.check(table.sqlName, key);\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 return { key, expression: constraint.expression ?? \"TRUE\", comments };\n};\n\ntype IndexTools = {\n table: TableFacts;\n declared: PulledTable;\n tableNames: Set<string>;\n warn: (warning: PullWarning) => void;\n declare: (index: { exact: boolean; index: PulledIndex }) => void;\n};\n\nconst INDEX_METHODS: ReadonlySet<string> = new Set(RUNTIME_INDEX_METHODS);\nconst 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 */\nconst 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 = /::\\s*$/.test(before) || /\\.\\s*$/.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\nconst 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. */\nconst 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\n if (/\\bcollate\\b/i.test(text)) {\n return skip(\"per-key COLLATE is not supported\");\n }\n\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) {\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 const expression = interpolate(text, members, declared.key);\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: expression.template,\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 ? interpolate(row.predicate, members, declared.key).template\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 ? camelKey(row.index_name.slice(prefix.length, -suffix.length))\n : undefined;\n\n if (\n derivedKey &&\n conventionalNames.index(table.sqlName, derivedKey) === 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 (!/^[a-z_][a-z0-9_]*$/.test(row.index_name)) {\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 * 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 */\nimport { escapeTemplate, quoteString } from \"./names\";\nimport type {\n ColumnType,\n IndexKeySource,\n PulledColumn,\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 \"bigint\",\n \"bool\",\n \"bytea\",\n \"customType\",\n \"date\",\n \"doublePrecision\",\n \"index\",\n \"inet\",\n \"int\",\n \"interval\",\n \"jsonb\",\n \"junction\",\n \"numeric\",\n \"oneOf\",\n \"operatorClass\",\n \"real\",\n \"schema\",\n \"smallint\",\n \"sql\",\n \"table\",\n \"text\",\n \"time\",\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\" ? \"jsonb<unknown>()\" : type.name;\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(\", \")})`;\n case \"vector\":\n imports.add(\"vector\");\n\n return `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 = (column: PulledColumn, imports: Set<string>): string => {\n let source = typeSource(column.type, imports);\n\n if (column.array) {\n source += \".array\";\n }\n\n switch (column.default?.kind) {\n case \"auto\":\n source += \".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\nconst referenceSource = (reference: PulledReference): string => {\n let source = 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) {\n source += `.onDelete.${reference.onDelete}`;\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 = (member: PulledMember, imports: Set<string>): string =>\n `${member.key}: ${member.kind === \"column\" ? columnSource(member, imports) : referenceSource(member)},${comment(member.comments)}`;\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 : `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\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\") || index.where) {\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(sql<boolean>\\`${index.where}\\`.is(true))`;\n }\n\n return source;\n};\n\nconst tableSource = (table: PulledTable, imports: Set<string>): 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 const constructor = table.junction ? \"junction\" : \"table\";\n imports.add(constructor);\n const body = [\n ...table.comments.map((note) => `${indent}// pull: ${note}`),\n ...table.members.map((member) => `${indent}${memberLine(member, imports)}`),\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 (table.primaryKey) {\n chain.push([\n `.primaryKey((${table.key}) => [${table.primaryKey.map((key) => `${table.key}.${key}`).join(\", \")}])`,\n ]);\n }\n\n if (table.indexes.length) {\n chain.push([\n `.indexes((${table.key}) => ({`,\n ...table.indexes.map(\n (index) =>\n ` ${index.key}: ${indexSource(index, table.key, imports)},${comment(index.comments)}`,\n ),\n \"}))\",\n ]);\n }\n\n if (table.checks.length) {\n imports.add(\"sql\");\n chain.push([\n `.checks((${table.key}) => ({`,\n ...table.checks.map(\n (check) =>\n ` ${check.key}: sql<boolean>\\`${check.expression}\\`.is(true),${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}: ({ ${targets.join(\", \")} }) =>`,\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 tables = model.tables.flatMap((table) => tableSource(table, imports));\n // Schema-level indexes contribute imports too, so render them before the import line.\n for (const { table, index } of model.schemaIndexes) {\n indexSource(index, table, 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 ({ table, index }) =>\n ` ${/^[a-z_][a-z0-9_]*$/i.test(index.key) ? index.key : quoteString(index.key)}: ${indexSource(index, table, imports)},${comment(index.comments)}`,\n );\n const optionLines = [\n ...(model.extensions.length\n ? [` extensions: [${model.extensions.map(quoteString).join(\", \")}],`]\n : []),\n ...(schemaIndexLines.length\n ? [\n ` indexes: ({ ${[...new Set(model.schemaIndexes.map((entry) => entry.table))].sort().join(\", \")} }) => ({`,\n ...schemaIndexLines,\n \" }),\",\n ]\n : []),\n ];\n const vectorImport = imports.has(\"vector\")\n ? [\n `import { vector } 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\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(). */\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 const declaredEnums = new Set(\n model.tables.flatMap((table) =>\n table.members.flatMap((member) =>\n member.kind === \"column\" && member.type.kind === \"enum\"\n ? [`${table.sqlName}_${member.sqlName}_enum`]\n : [],\n ),\n ),\n );\n\n return {\n source: renderSchema(model, options),\n schemaName: model.schemaName,\n tables: model.tables.map((table) => table.sqlName),\n enumerations: catalog.enumerations\n .map((entry) => entry.name)\n .filter((name) => declaredEnums.has(name)),\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,MAAa,qBACX,WACuC;CACvC,MAAM,aAAiD,CAAC;CACxD,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,UAAU;CACd,IAAI,QAAkB,CAAC;CAEvB,MAAM,UAAU,QAAsB;EACpC,IAAI,SAAS;GACX,MAAM,QAAQ,MAAM;GAEpB,IACE;IACE;IACA;IACA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