@akal/supaforge 0.0.32 → 0.0.33

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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +28 -10
  3. package/dist/commands/mcp.d.ts +1 -0
  4. package/dist/commands/mcp.js +11 -1
  5. package/package.json +10 -8
  6. package/bin/dev.js +0 -10
  7. package/dist/base-command.js.map +0 -1
  8. package/dist/chunk-2SELREHW.js.map +0 -1
  9. package/dist/chunk-3HGAV5CC.js.map +0 -1
  10. package/dist/chunk-4IVN7QVY.js.map +0 -1
  11. package/dist/chunk-6LJERPUN.js.map +0 -1
  12. package/dist/chunk-6Q7MHFBM.js.map +0 -1
  13. package/dist/chunk-6WAMNZLO.js.map +0 -1
  14. package/dist/chunk-7NAZGZPV.js.map +0 -1
  15. package/dist/chunk-BLKJWDTL.js.map +0 -1
  16. package/dist/chunk-BUOWHE36.js.map +0 -1
  17. package/dist/chunk-DMIWAJRB.js.map +0 -1
  18. package/dist/chunk-DQQ5E563.js.map +0 -1
  19. package/dist/chunk-G2DIPIYU.js.map +0 -1
  20. package/dist/chunk-GEHPTPNZ.js.map +0 -1
  21. package/dist/chunk-GZREXCQZ.js.map +0 -1
  22. package/dist/chunk-MIRLB5JM.js.map +0 -1
  23. package/dist/chunk-NTUASFQ3.js.map +0 -1
  24. package/dist/chunk-ORQJVE57.js.map +0 -1
  25. package/dist/chunk-SC2XHGIS.js.map +0 -1
  26. package/dist/chunk-SQPCWGQO.js.map +0 -1
  27. package/dist/chunk-UWAVXC57.js.map +0 -1
  28. package/dist/commands/clone.js.map +0 -1
  29. package/dist/commands/diff.js.map +0 -1
  30. package/dist/commands/help.js.map +0 -1
  31. package/dist/commands/hukam.js.map +0 -1
  32. package/dist/commands/init.js.map +0 -1
  33. package/dist/commands/mcp.js.map +0 -1
  34. package/dist/commands/migrate/baseline.js.map +0 -1
  35. package/dist/commands/migrate/create.js.map +0 -1
  36. package/dist/commands/migrate/list.js.map +0 -1
  37. package/dist/commands/migrate/run.js.map +0 -1
  38. package/dist/commands/report.js.map +0 -1
  39. package/dist/commands/restore.js.map +0 -1
  40. package/dist/commands/snapshot.js.map +0 -1
  41. package/dist/commands/sync.js.map +0 -1
  42. package/dist/help.js.map +0 -1
  43. package/dist/index.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/dbdiff.ts","../src/sql-ast.ts","../src/sql-deps.ts","../src/dbdiff-units.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport { createRequire } from 'node:module'\nimport { readFile, unlink, access } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { DriftIssue } from './types/drift'\nimport { errMsg, friendlyDbError, DiagnosticError } from './utils/error'\nimport { DBDIFF_EXEC_TIMEOUT_MS, DBDIFF_MAX_BUFFER } from './constants'\nimport { schemaDiffIgnores } from './defaults'\nimport { parseStatements, names, relationName, type Statement } from './sql-ast.js'\nimport { sqlSkeleton, policiesRemoved } from './sql-deps'\nimport { escapeRegex } from './utils/strings'\nimport { pairUnits, parseUnits, REPLACING_KINDS, type DbDiffUnit } from './dbdiff-units'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface DbDiffOptions {\n sourceUrl: string\n targetUrl: string\n type: 'schema' | 'data' | 'all'\n include: 'up' | 'down' | 'both'\n tables?: string[]\n ignoreTables?: string[]\n /** Schemas to exclude — converted to --ignore-tables=schema.* glob patterns. */\n ignoreSchemas?: string[]\n /**\n * Seconds before the diff is abandoned, from the target environment's\n * checks.schema.timeout. SUPAFORGE_DBDIFF_TIMEOUT still wins over this.\n */\n timeoutSeconds?: number\n /**\n * Called as dbdiff reports progress on individual tables, so a long schema\n * diff reads as working rather than hung (issue #29).\n */\n onProgress?: (progress: { table: string; tablesSeen: number }) => void\n /**\n * Ask a schema diff for `--units` (the default). Set false for a dbdiff\n * that predates the flag — runDbDiff does so itself when one refuses it.\n */\n units?: boolean\n}\n\nexport interface DbDiffResult {\n up: string\n down: string\n}\n\n/**\n * Whether a failed run means @dbdiff/cli is missing, rather than that it ran\n * and failed.\n *\n * Read from the spawn's error code and the process's stderr only. The error\n * message starts with the whole command line, connection URLs included, so a\n * bare `404` matched a port like 40425: a real DBDiff failure was reported as\n * \"not installed\" and the schema check skipped.\n */\nexport function dbdiffNotInstalled(code: unknown, stderr: string): boolean {\n if (code === 'ENOENT') return true\n return /ERR_MODULE_NOT_FOUND|could not determine executable|npm (?:ERR!|error) (?:code E404|404)|\\bE404\\b|command not found|: not found\\s*$/m.test(stderr)\n}\n\n/**\n * Resolve the @dbdiff/cli binary path from node_modules.\n *\n * Uses createRequire to locate the installed package, then returns\n * the path to `bin/dbdiff.js`. Falls back to 'npx' if the package\n * is not installed locally (e.g. global install).\n *\n * `SUPAFORGE_DBDIFF_BIN` overrides both with an executable of your own — a\n * DBDiff checkout's `dbdiff` script, say. That is how DBDiff's CI runs\n * SupaForge's scenarios against an unreleased change, and how a fix can be\n * tried through SupaForge before it ships, without touching node_modules.\n */\nexport function resolveDbDiffBin(): { command: string; prefixArgs: string[] } {\n const override = process.env.SUPAFORGE_DBDIFF_BIN?.trim()\n if (override) return { command: override, prefixArgs: [] }\n try {\n const require = createRequire(import.meta.url)\n const binPath = require.resolve('@dbdiff/cli/bin/dbdiff.js')\n return { command: process.execPath, prefixArgs: [binPath] }\n } catch {\n // Fallback: try npx for global installs\n return { command: 'npx', prefixArgs: ['@dbdiff/cli'] }\n }\n}\n\n/**\n * Run @dbdiff/cli and parse UP/DOWN SQL output.\n *\n * Writes to a temp file via --output, reads it back, then parses\n * the `-- ==================== UP ====================` /\n * `-- ==================== DOWN ====================` markers.\n *\n * When @dbdiff/cli is not installed, throws with a clear message.\n */\n/**\n * Resolve the effective dbdiff timeout (ms).\n *\n * Honours the SUPAFORGE_DBDIFF_TIMEOUT environment variable (in seconds) so\n * users with very large schemas can raise the ceiling without a code change.\n * Falls back to DBDIFF_EXEC_TIMEOUT_MS.\n */\nexport function resolveDbDiffTimeoutMs(configuredSeconds?: number): number {\n // Precedence: env var > per-environment config > default. The env var is the\n // runtime escape hatch, so it has to beat a committed config value.\n const raw = process.env.SUPAFORGE_DBDIFF_TIMEOUT\n if (raw) {\n const secs = Number(raw)\n if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1000)\n }\n if (Number.isFinite(configuredSeconds) && (configuredSeconds as number) > 0) {\n return Math.round((configuredSeconds as number) * 1000)\n }\n return DBDIFF_EXEC_TIMEOUT_MS\n}\n\n/**\n * dbdiff logs a line per table as it works. Recognising them turns a silent\n * multi-minute spinner into visible progress.\n *\n * Matches both the per-table diff line and the batch pre-scan summary, and is\n * tolerant of the ANSI colour codes dbdiff emits.\n */\nconst DBDIFF_TABLE_LINE = /calculating schema diff for table [`\"']?([\\w.$]+)/i\n\nexport function parseDbDiffProgress(line: string): string | null {\n return DBDIFF_TABLE_LINE.exec(line)?.[1] ?? null\n}\n\n/**\n * Resolve the PHP memory limit to hand to @dbdiff/cli, if any.\n *\n * @dbdiff/cli caps itself at 1G by default, which is ample for most Supabase\n * projects but can be exceeded by a very large schema or a wide data diff.\n * SUPAFORGE_DBDIFF_MEMORY passes straight through to `--memory-limit`, taking\n * the same values dbdiff accepts: \"512M\", \"2G\", or \"-1\" for unlimited.\n *\n * Returns undefined when unset or malformed, leaving dbdiff on its own default\n * rather than forwarding a value it would reject.\n */\nexport function resolveDbDiffMemoryLimit(): string | undefined {\n const raw = process.env.SUPAFORGE_DBDIFF_MEMORY?.trim()\n if (!raw) return undefined\n return /^-?\\d+[KMG]?$/i.test(raw) ? raw : undefined\n}\n\n/**\n * Strip @dbdiff/cli progress / spinner noise from captured output.\n *\n * dbdiff logs informational lines such as \"ℹ Now generating UP migration\"\n * to stdout while it works. When the process is killed (e.g. on timeout)\n * that last progress line is the only thing in the buffer — surfacing it as\n * the \"error\" is misleading. Drop any line that begins with a known\n * info/spinner glyph and keep only genuine error-looking content.\n */\nconst DBDIFF_NOISE_LINE = /^\\s*[ℹ✔✓⚠⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]/u\n\nexport function stripDbDiffNoise(text: string): string {\n return text\n .split('\\n')\n .filter(line => line.trim() !== '' && !DBDIFF_NOISE_LINE.test(line))\n .join('\\n')\n .trim()\n}\n\n/**\n * Build the full @dbdiff/cli argument list for a diff run.\n *\n * Split out of runDbDiff() so the flag surface is one readable unit and can be\n * asserted directly in tests, rather than only through a spawned process.\n */\nexport function buildDbDiffArgs(options: DbDiffOptions, outputFile: string): string[] {\n const args = [\n 'diff',\n `--server1-url=${options.sourceUrl}`,\n `--server2-url=${options.targetUrl}`,\n `--type=${options.type}`,\n // Was hardcoded to 'both', silently ignoring options.include. Every caller\n // passes 'both' (sqlToIssues pairs each UP statement with its DOWN\n // counterpart, so it needs both directions), but the option was part of the\n // public interface and did nothing.\n `--include=${options.include}`,\n '--nocomments',\n // @dbdiff/cli >= 3.0.0-rc.3 refuses to emit a migration containing\n // DROP TABLE or DROP COLUMN unless this is passed, exiting non-zero and\n // writing no output file. SupaForge is a *detection* tool: an extra table\n // or column on the target is the single most common form of drift, and it\n // has to be reported rather than turned into a hard failure. The safety\n // gate belongs at apply time instead — see isDestructiveSql()/promote(),\n // which skip these statements unless the user opts in explicitly.\n '--allow-destructive',\n `--output=${outputFile}`,\n ]\n\n // Each schema change marked as one unit, so a change of several statements\n // is one finding and its DOWN is found by name — see dbdiff-units.ts. Data\n // diffs stay statement by statement: a unit there is a table's rows, and\n // rows are reviewed and applied one at a time.\n if (options.type === 'schema' && options.units !== false) {\n args.push('--units')\n }\n\n const memoryLimit = resolveDbDiffMemoryLimit()\n if (memoryLimit) {\n args.push(`--memory-limit=${memoryLimit}`)\n }\n\n // A schema diff compares every schema but the ignored ones. dbdiff named\n // tables without their schema, so these were once passed as table globs\n // (auth.*) that matched nothing: dbdiff read `public` alone. Data diffs\n // name their tables in checks.data.tables, which are in `public`.\n if (options.type === 'schema' && options.ignoreSchemas) {\n args.push(`--ignore-schemas=${schemaDiffIgnores(options.ignoreSchemas).join(',')}`)\n }\n const ignore = options.ignoreTables ?? []\n\n if (options.tables?.length) {\n args.push(`--tables=${options.tables.join(',')}`)\n }\n if (ignore.length) {\n args.push(`--ignore-tables=${ignore.join(',')}`)\n }\n\n return args\n}\n\n/**\n * Forward dbdiff's per-table log lines to a progress callback.\n *\n * Entirely best-effort: any failure here must never affect the diff itself,\n * so every step is guarded. A missing stdout (possible if the process dies\n * immediately) simply means no progress is reported.\n */\nfunction attachProgress(\n running: { child?: { stdout?: NodeJS.ReadableStream | null } },\n onProgress?: (progress: { table: string; tablesSeen: number }) => void,\n): void {\n if (!onProgress) return\n try {\n const stdout = running.child?.stdout\n if (!stdout) return\n\n let buffer = ''\n let tablesSeen = 0\n stdout.on('data', (chunk: Buffer | string) => {\n try {\n buffer += String(chunk)\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const table = parseDbDiffProgress(line)\n if (table) {\n tablesSeen++\n onProgress({ table, tablesSeen })\n }\n }\n } catch {\n // Progress reporting is cosmetic — never let it break the run.\n }\n })\n stdout.on('error', () => {})\n } catch {\n // Same: cosmetic only.\n }\n}\n\nexport async function runDbDiff(options: DbDiffOptions): Promise<DbDiffResult> {\n const { command, prefixArgs } = resolveDbDiffBin()\n const outputFile = join(tmpdir(), `supaforge-dbdiff-${Date.now()}-${Math.random().toString(36).slice(2)}.sql`)\n\n const args = [...prefixArgs, ...buildDbDiffArgs(options, outputFile)]\n\n const timeoutMs = resolveDbDiffTimeoutMs(options.timeoutSeconds)\n\n try {\n const running = execFileAsync(command, args, {\n timeout: timeoutMs,\n maxBuffer: DBDIFF_MAX_BUFFER,\n })\n\n // Attach to the child's stdout for progress without changing how it is\n // executed — promisified execFile exposes the ChildProcess as `.child`,\n // so timeout, maxBuffer and every error path stay exactly as they were.\n attachProgress(running, options.onProgress)\n\n await running\n\n // When schemas are identical, dbdiff exits 0 but doesn't write the file\n const fileExists = await access(outputFile).then(() => true, () => false)\n if (!fileExists) {\n return { up: '', down: '' }\n }\n\n const output = await readFile(outputFile, 'utf8')\n return parseDbDiffOutput(output)\n } catch (err: unknown) {\n const errObj = (err ?? {}) as Record<string, unknown>\n const message = errMsg(err)\n const stderr = String(errObj.stderr ?? '').trim()\n const stdout = String(errObj.stdout ?? '').trim()\n const combined = `${message} ${stderr}`\n\n // A dbdiff older than --units (3.0.0-rc.17) refuses the flag; its output\n // is read statement by statement instead.\n if (options.units !== false && /\"--units\" option does not exist/.test(`${combined} ${stdout}`)) {\n return runDbDiff({ ...options, units: false })\n }\n\n if (dbdiffNotInstalled(errObj.code, stderr)) {\n throw new DiagnosticError(\n '@dbdiff/cli is not installed. Install it with: npm install @dbdiff/cli',\n )\n }\n\n // @dbdiff/cli exits 1 when differences are found (standard diff convention).\n // The output file is written before exit — read it if it has real content.\n const fileExists = await access(outputFile).then(() => true, () => false)\n if (fileExists) {\n const output = await readFile(outputFile, 'utf8')\n const parsed = parseDbDiffOutput(output)\n if (parsed.up || parsed.down) return parsed\n }\n\n // Timeout / killed process. execFileAsync sets `killed: true` and a SIGTERM\n // signal when it kills the child on timeout. Previously this fell through and\n // surfaced dbdiff's last progress line (\"ℹ Now generating UP migration\") as\n // the error — hiding the real cause. Report it clearly instead.\n const timedOut =\n errObj.killed === true ||\n errObj.signal === 'SIGTERM' ||\n errObj.code === 'ETIMEDOUT' ||\n /ETIMEDOUT|timed out/i.test(combined)\n if (timedOut) {\n const secs = Math.round(timeoutMs / 1000)\n throw new DiagnosticError(\n `Schema diff timed out after ${secs}s — the schema is very large or the ` +\n `database connection is slow.\\n` +\n ` Remediations:\\n` +\n ` • Raise the limit: set SUPAFORGE_DBDIFF_TIMEOUT=600 (seconds) and re-run.\\n` +\n ` • Narrow the scan: diff one layer at a time with --check=schema.\\n` +\n ` • Exclude large internal schemas via \"ignoreSchemas\" in supaforge.config.json.`,\n )\n }\n\n // No usable output file → genuine error (connection refused, auth, etc.).\n // Prefer stderr; otherwise fall back to stdout with dbdiff's progress/spinner\n // noise stripped so an info line never masquerades as the error. Strip the raw\n // \"Command failed: /path/to/node ...\" prefix which leaks connection URLs.\n const realError = stderr || stripDbDiffNoise(stdout)\n const cleanMessage = realError\n ? realError\n : message.replace(/^Command failed:[^\\n]*/m, '').trim() || 'dbdiff failed with no error output'\n throw new Error(friendlyDbError(cleanMessage, options.sourceUrl))\n } finally {\n await unlink(outputFile).catch(() => {})\n }\n}\n\nconst UP_MARKER = '-- ==================== UP ===================='\nconst DOWN_MARKER = '-- ==================== DOWN ===================='\n\nconst CREATE_FUNCTION = 'create-function'\nconst DROP_FUNCTION = 'drop-function'\n\nconst DROP_TYPES = ['drop', 'drop-view', DROP_FUNCTION, 'drop-trigger', 'drop-type', 'drop-sequence']\n\n/**\n * Does this statement destroy data, or weaken access control, if executed?\n *\n * Still narrower than DROP_TYPES: dropping a view, function, trigger or type\n * loses a definition the migration can recreate. What is gated is losing rows\n * or losing a policy.\n *\n * It used to cover `DROP TABLE` and `ALTER TABLE … DROP COLUMN` only, so two\n * things went through `--apply` that the flag exists to hold back (issue #88):\n *\n * - `DELETE FROM`, which is how the data check removes rows the source does\n * not have. Rows are exactly what `--allow-destructive` is about.\n * - `DROP POLICY`, which is not recoverable from the schema and, for a\n * RESTRICTIVE policy, *grants* access by removing it. The RLS check renders\n * a *modified* policy as a drop and a create of the same name, and that is\n * a replacement rather than a removal — so only a policy left dropped\n * counts.\n *\n * Matching runs over `sqlSkeleton`, so the words appearing inside a string\n * literal or a routine body cannot trigger it — and matching is no longer\n * anchored to the start, since a merged replacement pair puts the second\n * statement mid-string.\n */\nexport function isDestructiveSql(sql: string): boolean {\n return destructiveReason(sql) !== undefined\n}\n\n/**\n * Why this statement is gated, in the words the skip line should use.\n *\n * `recreatedElsewhere` holds the policies (`schema.table.policy`, as createdPolicies\n * keys them) that other fixes applied alongside this one create.\n *\n * \"Destructive (drops data)\" was printed for every case once policies joined\n * the list, which is wrong for a policy — nothing is lost from a table, and\n * saying so obscures the part that matters, that removing a RESTRICTIVE policy\n * opens access up.\n */\nexport function destructiveReason(\n sql: string,\n recreatedElsewhere: ReadonlySet<string> = new Set(),\n): string | undefined {\n const statements = parseStatements(sql)\n return statements\n ? destructiveInTree(statements, recreatedElsewhere)\n : destructiveInText(sql, recreatedElsewhere)\n}\n\n/**\n * destructiveReason() read from PostgreSQL's parse tree — see sql-ast.ts.\n *\n * The tree says what each statement is, so none of the cases the text\n * version guards against can arise: `GRANT TRUNCATE` is a GrantStmt, not a\n * TruncateStmt, and a function body mentioning `DROP TABLE` is a string.\n */\nfunction destructiveInTree(statements: Statement[], recreatedElsewhere: ReadonlySet<string>): string | undefined {\n const dropped = (type: string) => statements.some(s => s.kind === 'DropStmt' && s.node.removeType === type)\n if (dropped('OBJECT_SCHEMA')) return 'drops a schema and everything in it'\n if (dropped('OBJECT_TABLE')) return 'drops a table and its rows'\n if (statements.some(s => s.kind === 'TruncateStmt')) return 'deletes every row in a table'\n if (columnsDroppedForGoodInTree(statements).length > 0) return 'drops a column and its values'\n if (statements.some(s => s.kind === 'DeleteStmt')) return 'deletes rows'\n if (statements.some(s => s.kind === 'DropRoleStmt')) return 'drops a role, and every login and grant it holds'\n\n // A policy the same SQL creates again is being replaced, not removed — as\n // is one another fix in the apply recreates (recreatedElsewhere).\n // Keyed `schema.table.policy`, as createdPolicies keys them: `public` where\n // the table names no schema.\n const key = (schema: string | undefined, table: string, policy: string) =>\n `${(schema || 'public').toLowerCase()}.${table.toLowerCase()}.${policy.toLowerCase()}`\n const created = new Set(statements.filter(s => s.kind === 'CreatePolicyStmt')\n .map(s => key(s.node.table?.schemaname, relationName(s.node.table), s.node.policy_name)))\n const policies = statements\n .filter(s => s.kind === 'DropStmt' && s.node.removeType === 'OBJECT_POLICY')\n .flatMap(s => (s.node.objects as Array<Record<string, any>>).map(o => names(o.List?.items)))\n .map(parts => key(parts.at(-3), parts.at(-2) ?? '', parts.at(-1) ?? ''))\n .filter(k => !created.has(k) && !recreatedElsewhere.has(k))\n if (policies.length > 0) {\n return policies.length === 1\n ? `removes the policy ${policies[0]}, which may widen access`\n : `removes ${policies.length} policies, which may widen access`\n }\n return undefined\n}\n\n/** Columns an ALTER TABLE drops, unless a later command in the same SQL adds them back. */\nfunction columnsDroppedForGoodInTree(statements: Statement[]): string[] {\n const commands = statements\n .filter(s => s.kind === 'AlterTableStmt')\n .flatMap(s => (s.node.cmds as Array<Record<string, any>>).map(c => ({ table: relationName(s.node.relation), cmd: c.AlterTableCmd })))\n return commands.flatMap(({ table, cmd }, i) => {\n if (cmd?.subtype !== 'AT_DropColumn') return []\n const readded = commands.slice(i + 1).some(later =>\n later.table === table && later.cmd?.subtype === 'AT_AddColumn' && later.cmd.def?.ColumnDef?.colname === cmd.name)\n return readded ? [] : [cmd.name as string]\n })\n}\n\n/**\n * destructiveReason() read from the text, for SQL PostgreSQL's parser does not\n * accept — a fragment, or a dialect it does not speak. What it did before the\n * parse tree was used.\n */\nfunction destructiveInText(sql: string, recreatedElsewhere: ReadonlySet<string>): string | undefined {\n const skeleton = sqlSkeleton(sql).toUpperCase()\n\n if (/\\bDROP\\s+SCHEMA\\b/.test(skeleton)) return 'drops a schema and everything in it'\n if (/\\bDROP\\s+TABLE\\b/.test(skeleton)) return 'drops a table and its rows'\n // At the start of a statement only. TRUNCATE is also a privilege and a\n // trigger event, so `GRANT TRUNCATE ON t TO anon` and `BEFORE TRUNCATE ON t`\n // were held back as though they emptied the table — and Supabase's default\n // `GRANT ALL` includes TRUNCATE, so every grant fix for a new table tripped it.\n if (/(?:^|;)\\s*TRUNCATE\\b/.test(skeleton)) return 'deletes every row in a table'\n if (columnsDroppedForGood(skeleton).length > 0) return 'drops a column and its values'\n if (/\\bDELETE\\s+FROM\\b/.test(skeleton)) return 'deletes rows'\n // A role is not schema: it is who can log in. The roles check offered\n // `DROP ROLE` for every role only the target had, including the one the\n // apply was connected as, and nothing held it back.\n if (/(?:^|;)\\s*DROP\\s+(?:ROLE|USER|GROUP)\\b/.test(skeleton)) return 'drops a role, and every login and grant it holds'\n\n // A policy another fix in the same apply creates again is being replaced,\n // not removed: a column type change drops the policies reading the column\n // and the policy's own fix puts the new one back once the type has changed.\n const policies = policiesRemoved(sql).filter(key => !recreatedElsewhere.has(key))\n if (policies.length > 0) {\n return policies.length === 1\n ? `removes the policy ${policies[0]}, which may widen access`\n : `removes ${policies.length} policies, which may widen access`\n }\n\n return undefined\n}\n\n/**\n * Columns a statement drops and does not add back.\n *\n * A stored generated column whose expression changes, or that reads a column\n * being retyped, is dropped and re-added in the same change — recomputed from\n * its expression, so nothing is lost — and was held back as though its values\n * were. Matched on the upper-cased skeleton, so names compare as written.\n */\nfunction columnsDroppedForGood(skeleton: string): string[] {\n const ident = String.raw`(\"(?:[^\"]|\"\")+\"|[\\w$]+)`\n const dropped = [...skeleton.matchAll(new RegExp(String.raw`\\bDROP\\s+COLUMN\\s+(?:IF\\s+EXISTS\\s+)?` + ident, 'g'))]\n return dropped\n .filter(m => !new RegExp(String.raw`\\bADD\\s+COLUMN\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?` + escapeRegex(m[1]) + String.raw`(?![\\w$\"])`)\n .test(skeleton.slice((m.index ?? 0) + m[0].length)))\n .map(m => m[1])\n}\n\nexport function parseDbDiffOutput(output: string): DbDiffResult {\n const upIdx = output.indexOf(UP_MARKER)\n const downIdx = output.indexOf(DOWN_MARKER)\n\n if (upIdx === -1 && downIdx === -1) {\n // Might be UP-only output without markers\n return { up: output.trim(), down: '' }\n }\n\n let up = ''\n let down = ''\n\n if (upIdx !== -1) {\n const upStart = upIdx + UP_MARKER.length\n const upEnd = downIdx !== -1 ? downIdx : output.length\n up = output.slice(upStart, upEnd).trim()\n }\n\n if (downIdx !== -1) {\n const downStart = downIdx + DOWN_MARKER.length\n down = output.slice(downStart).trim()\n }\n\n return { up, down }\n}\n\n/**\n * Convert @dbdiff/cli SQL output into DriftIssues.\n *\n * Each SQL statement (separated by `;`) becomes its own issue\n * with the appropriate severity and layer.\n *\n * When `ignoreSchemas` is provided, FK constraint statements that\n * reference tables in ignored schemas are filtered out — these are\n * false positives caused by dbdiff seeing stub tables.\n *\n * `ignoredSchemaTables` is an optional pre-queried set of table names\n * (lowercase) that exist inside ignored schemas. When provided it lets the\n * filter catch unqualified REFERENCES like `REFERENCES \"users\"` where\n * \"users\" lives in the ignored \"auth\" schema but dbdiff omitted the prefix.\n */\nexport function sqlToIssues(\n result: DbDiffResult,\n check: 'schema' | 'data',\n ignoreSchemas?: string[],\n ignoredSchemaTables?: Set<string>,\n): DriftIssue[] {\n const issues = unfoldedIssues(result, check, ignoreSchemas, ignoredSchemaTables)\n return check === 'schema' ? foldCommentsIntoCreates(issues) : issues\n}\n\n/** What a comment title names: `public.orders.total (column)` → the name and kind. */\nconst COMMENT_TITLE = /^(?:Comment changed|Comment missing): (?:schema (.+)|(.+) \\(([a-z ]+)\\))$/\n/**\n * A finding that creates an object, `Table missing: public.orders`, or\n * recreates one, `View modified: public.v`: dbdiff sets a recreated object's\n * comments again, and apart those read as \"Comment changed\" on a comment that\n * had not.\n */\nconst CREATE_TITLE = /^(Schema|Table|View|Function|Procedure|Type|Domain|Sequence|Index|Policy|Trigger|Extension) (?:missing|modified): (.+)$/\n/** Kinds named after the table (or domain) they belong to. */\nconst ON_A_TABLE = new Set(['column', 'constraint', 'trigger', 'policy', 'rule'])\n\n/**\n * A comment on an object the target does not have yet goes with the finding\n * that creates it.\n *\n * DBDiff emits each comment on its own, so a missing table with three\n * commented columns was four findings, three of them titled \"Comment changed\"\n * on an object that was not there to change. Folded, the comment runs right\n * after its object is made; dropping the object takes the comment with it, so\n * nothing is added to the DOWN.\n */\nexport function foldCommentsIntoCreates(issues: DriftIssue[]): DriftIssue[] {\n const creates = new Map<string, DriftIssue>()\n /** New routines by name alone, for a comment whose signature is spelled differently. */\n const routines = new Map<string, DriftIssue[]>()\n for (const issue of issues) {\n const m = CREATE_TITLE.exec(issue.title)\n if (!m) continue\n creates.set(`${m[1] === 'Schema' ? 'schema' : 'object'}:${m[2]}`, issue)\n if (m[1] === 'Function' || m[1] === 'Procedure') {\n const base = routineBaseName(m[2])\n routines.set(base, [...(routines.get(base) ?? []), issue])\n }\n }\n\n return issues.filter(issue => {\n const up = issue.sql?.up\n if (!up) return true\n const owner = commentOwner(issue, up, creates, routines) ?? rlsFlagsOwner(issue, up, creates)\n if (!owner?.sql) return true\n\n owner.sql = { ...owner.sql, up: `${owner.sql.up.trimEnd()}\\n${up.trim()}` }\n return false\n })\n}\n\n/**\n * The finding creating the object a comment is on. dbdiff names a routine by\n * its argument types in a comment (`f2(integer,pg_catalog.text)`) and by its\n * parameter list in the create (`f2(p_x integer, p_y text DEFAULT 'a')`), so a\n * routine is matched by name when only one new routine has it.\n */\nfunction commentOwner(\n issue: DriftIssue, up: string, creates: Map<string, DriftIssue>, routines: Map<string, DriftIssue[]>,\n): DriftIssue | undefined {\n const m = COMMENT_TITLE.exec(issue.title)\n if (!m || splitStatements(up).length !== 1) return undefined\n const [, schema, name, kind] = m\n const candidates = schema !== undefined\n ? [`schema:${schema}`]\n : [`object:${name}`, ...(ON_A_TABLE.has(kind) ? [`object:${name.slice(0, name.lastIndexOf('.'))}`] : [])]\n const exact = candidates.map(c => creates.get(c)).find(Boolean)\n if (exact || (kind !== 'function' && kind !== 'procedure')) return exact\n const sameName = routines.get(routineBaseName(name)) ?? []\n return sameName.length === 1 ? sameName[0] : undefined\n}\n\n/** A routine's name without its argument list. */\nconst routineBaseName = (name: string) => name.includes('(') ? name.slice(0, name.indexOf('(')) : name\n\n/** `ALTER TABLE t ENABLE ROW LEVEL SECURITY` and the like, the whole of a finding. */\nconst RLS_FLAG = /^\\s*ALTER\\s+TABLE\\s+(?:ONLY\\s+)?\\S+\\s+(?:ENABLE|DISABLE|(?:NO\\s+)?FORCE)\\s+ROW\\s+LEVEL\\s+SECURITY\\s*;?\\s*$/i\n\n/**\n * The finding creating a table whose RLS flags a finding sets: a table that\n * does not exist yet had them as a separate \"Table altered\".\n */\nfunction rlsFlagsOwner(issue: DriftIssue, up: string, creates: Map<string, DriftIssue>): DriftIssue | undefined {\n const m = /^Table altered: (.+)$/.exec(issue.title)\n if (!m || !splitStatements(up).every(sql => RLS_FLAG.test(sql))) return undefined\n return creates.get(`object:${m[1]}`)\n}\n\nfunction unfoldedIssues(\n result: DbDiffResult,\n check: 'schema' | 'data',\n ignoreSchemas?: string[],\n ignoredSchemaTables?: Set<string>,\n): DriftIssue[] {\n if (!result.up && !result.down) return []\n\n const upUnits = parseUnits(result.up)\n if (upUnits) {\n return issuesFromUnits(upUnits, parseUnits(result.down) ?? [], check, ignoreSchemas, ignoredSchemaTables)\n }\n\n let upStatements = splitStatements(result.up)\n let downStatements = splitStatements(result.down)\n\n // Filter out FK constraints that reference tables in ignored schemas.\n // These arise because dbdiff compares stub tables vs real Supabase tables.\n // We check both UP and DOWN statements — dbdiff generates broken REFERENCES \"\" (\"\")\n // in the DOWN when the referenced table is in an ignored schema.\n // `ignoredSchemaTables` additionally catches unqualified refs like\n // REFERENCES \"users\" where \"users\" lives in the ignored \"auth\" schema.\n if (ignoreSchemas?.length && check === 'schema') {\n const keep = filterCrossSchemaFks(upStatements, downStatements, ignoreSchemas, ignoredSchemaTables)\n upStatements = upStatements.filter((_, i) => keep[i])\n downStatements = downStatements.filter((_, i) => keep[i])\n }\n\n if (upStatements.length === 0) return []\n\n upStatements = groupColumnTypeChanges(upStatements)\n downStatements = groupColumnTypeChanges(downStatements)\n\n const merged = mergeReplacements(upStatements, downStatements)\n\n // Generate one issue per UP statement, paired with its DOWN counterpart\n return merged.map(({ up: upSql, down: downSql, modified }, i) => {\n // A grouped column type change is named by its ALTER, not by the DROP\n // that opens the group.\n const lead = columnTypeChangeOf(upSql) ?? upSql\n const type = classifyStatement(lead)\n\n if (modified) {\n const report = REPLACEABLE_REPORT[modified.kind]\n return {\n id: `${check}-alter-${report.idPart}-${i + 1}`,\n check,\n severity: 'warning' as const,\n title: `${report.label}: ${qualifySchemaName(modified.name)}`,\n description: `${report.what} differs between source and target.`,\n sql: { up: upSql, down: downSql },\n }\n }\n\n return {\n id: `${check}-${type}-${i + 1}`,\n check,\n severity: DROP_TYPES.includes(type) ? 'critical' : 'warning',\n // The DOWN counterpart is passed so a title can recover a schema the UP\n // statement does not carry — see routineLabel (issue #47).\n title: summariseStatement(lead, check, downSql),\n description: `${check === 'schema' ? 'Schema' : 'Data'} difference detected by @dbdiff/cli.`,\n sql: { up: upSql, down: downSql },\n }\n })\n}\n\n/**\n * One finding per dbdiff unit (see dbdiff-units.ts), paired with the DOWN\n * unit for the same change.\n *\n * Named as the statement-by-statement path names them: a unit replacing one\n * object — a changed routine, policy, or enum whose labels were removed — is\n * \"<Kind> modified\"; anything else by its leading statement, which for a\n * table change is its first ALTER TABLE rather than a view it stands aside.\n */\nfunction issuesFromUnits(\n upUnits: DbDiffUnit[],\n downUnits: DbDiffUnit[],\n check: 'schema' | 'data',\n ignoreSchemas?: string[],\n ignoredSchemaTables?: Set<string>,\n): DriftIssue[] {\n const pairs = pairUnits(upUnits, downUnits).filter(({ up, down }) =>\n !(ignoreSchemas?.length && isCrossSchemaFkUnit(up, down, ignoreSchemas, ignoredSchemaTables)))\n\n return pairs.map(({ up, down }, i) => {\n const upSql = up.sql\n const downSql = down?.sql ?? ''\n const statements = splitStatements(upSql)\n const replaced = replacedObject(up, statements)\n const manualOnly = manualEnumChange(up)\n const manual = manualOnly ? { manualOnly } : {}\n\n if (replaced) {\n const report = REPLACEABLE_REPORT[replaced.kind]\n return {\n id: `${check}-alter-${report.idPart}-${i + 1}`,\n check,\n severity: 'warning' as const,\n title: `${report.label}: ${qualifySchemaName(replaced.name)}`,\n description: `${report.what} differs between source and target.`,\n sql: { up: upSql, down: downSql },\n ...manual,\n }\n }\n\n const lead = leadStatement(up, statements)\n const type = classifyStatement(lead)\n return {\n id: `${check}-${type}-${i + 1}`,\n check,\n severity: DROP_TYPES.includes(type) ? 'critical' : 'warning',\n title: summariseStatement(lead, check, downSql),\n description: `${check === 'schema' ? 'Schema' : 'Data'} difference detected by @dbdiff/cli.`,\n sql: { up: upSql, down: downSql },\n ...manual,\n }\n })\n}\n\n/**\n * Why an enum change cannot be applied automatically, when dbdiff says so.\n *\n * Removing or reordering labels moves everything using the type to a new one;\n * what a move cannot carry — a routine taking the type, a domain over it — dbdiff\n * names in a comment and falls back to replacing the type, which PostgreSQL\n * refuses. Applied, that one refusal rolled back every other fix with it, so\n * it is reported as a manual step instead, naming what is in the way.\n */\nfunction manualEnumChange(unit: DbDiffUnit): string | undefined {\n if (unit.kind !== 'AlterEnum' || !/^--.*\\benum labels\\b/im.test(unit.sql)) return undefined\n const blockers = [...unit.sql.matchAll(/^--\\s{3}(.+)$/gm)].map(m => m[1].trim())\n return 'removing or reordering these enum labels needs the type replaced'\n + (blockers.length > 0 ? `, and these use it in ways that cannot be moved automatically: ${blockers.join(', ')}` : '')\n + '. Migrate them first, then re-run, or apply the change by hand.'\n}\n\n/**\n * A constraint change about a foreign key into an ignored schema — a false\n * positive from dbdiff seeing that schema's tables as stubs. The reference is\n * in the ADD, which is the UP of an added key and the DOWN of a dropped one.\n */\nfunction isCrossSchemaFkUnit(\n up: DbDiffUnit,\n down: DbDiffUnit | undefined,\n schemas: string[],\n ignoredSchemaTables?: Set<string>,\n): boolean {\n if (!/Constraint$/.test(up.kind)) return false\n return [up.sql, down?.sql ?? ''].some(sql =>\n /\\bFOREIGN\\s+KEY\\b/i.test(sql)\n && (hasCrossSchemaRef(sql, schemas, ignoredSchemaTables) || hasBrokenRef(sql)))\n}\n\n/** The object a unit drops and recreates, when that is what it does. */\nfunction replacedObject(\n unit: DbDiffUnit,\n statements: string[],\n): { kind: ReplaceableKind; name: string } | undefined {\n const kind = REPLACING_KINDS[unit.kind]\n const drop = statements.find(sql => replaceablePart(sql)?.drop)\n if (!kind || !drop) return undefined\n\n if (kind === 'type') return { kind, name: unit.object }\n const create = [...statements].reverse().find(sql => replaceablePart(sql)?.drop === false) ?? drop\n return {\n kind,\n name: kind === 'routine'\n ? extractRoutineName(create) + extractRoutineArgs(drop)\n : REPLACEABLE_NAME[kind](create),\n }\n}\n\n/**\n * The statement a unit is named by: for a table change, its first ALTER\n * TABLE (a column type change opens by standing views aside; a serial column\n * by creating its sequence); otherwise its first statement.\n */\nfunction leadStatement(unit: DbDiffUnit, statements: string[]): string {\n if (unit.kind.startsWith('AlterTable')) {\n const alter = statements.find(sql => /^\\s*ALTER\\s+TABLE\\b/i.test(sql))\n if (alter) return alter\n }\n return statements[0] ?? unit.sql\n}\n\n/** `ALTER TABLE t ALTER COLUMN c TYPE ...`, capturing the table and column. */\nconst ALTER_COLUMN_TYPE = /^\\s*ALTER\\s+TABLE\\s+(?:ONLY\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)\\s+ALTER\\s+COLUMN\\s+(\"[^\"]+\"|[\\w$]+)\\s+(?:SET\\s+DATA\\s+)?TYPE\\b/i\n\n/** The ALTER ... TYPE statement inside a grouped column change, if this is one. */\nfunction columnTypeChangeOf(sql: string): string | undefined {\n if (!/^\\s*DROP\\s+/i.test(sql)) return undefined\n return splitStatements(sql).find(s => ALTER_COLUMN_TYPE.test(s))\n}\n\n/** An identifier without quotes or a `public.` qualifier, for comparing names. */\nfunction plainName(identifier: string): string {\n return identifier.replace(/\"/g, '').replace(/^public\\./i, '').trim()\n}\n\n/**\n * Keep a column type change together with the dependants dbdiff drops and\n * recreates around it.\n *\n * PostgreSQL refuses `ALTER COLUMN ... TYPE` while a view, policy or trigger\n * condition reads the column, so @dbdiff/cli brackets the change: drop them,\n * retype, recreate them with their grants and comments. As separate issues\n * that bracket came apart — the DROP POLICY was held back by the destructive\n * gate as a removal while the ALTER went ahead and failed, and two column\n * changes under one view each became a CREATE VIEW, the second of which\n * failed on the first. One change, one issue.\n *\n * Recognised by shape: the DROP ... IF EXISTS statements immediately before\n * the ALTER, and after it the rest of that column's change and the statements\n * that recreate, grant, comment on or index what was dropped. A plain type\n * change with nothing around it is left exactly as it was.\n */\nexport function groupColumnTypeChanges(statements: string[]): string[] {\n const out: string[] = []\n let i = 0\n\n while (i < statements.length) {\n const alter = ALTER_COLUMN_TYPE.exec(statements[i])\n if (!alter) {\n out.push(statements[i])\n i++\n continue\n }\n\n const [, table, column] = alter\n const views = new Set<string>()\n const attached = new Set<string>() // `name@table` for policies and triggers\n\n // Walk back over the drops dbdiff emitted for this change.\n const drops: Array<{ index: number; view?: string; attached?: string; table?: string }> = []\n let start = out.length\n while (start > 0) {\n const drop = /^\\s*DROP\\s+(?:(MATERIALIZED\\s+VIEW|VIEW)|(POLICY|TRIGGER))\\s+IF\\s+EXISTS\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)(?:\\s+ON\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?))?\\s*;?\\s*$/i\n .exec(out[start - 1])\n if (!drop) break\n if (drop[1]) {\n views.add(plainName(drop[3]))\n drops.unshift({ index: start - 1, view: plainName(drop[3]) })\n } else {\n const key = `${plainName(drop[3])}@${plainName(drop[4] ?? '')}`\n attached.add(key)\n drops.unshift({ index: start - 1, attached: key, table: plainName(drop[4] ?? '') })\n }\n start--\n }\n if (drops.length === 0) {\n out.push(statements[i])\n i++\n continue\n }\n\n const onView = (name: string) => views.has(plainName(name))\n const recreated = new Set<string>()\n const belongs = (sql: string): boolean => {\n const sameColumn = ALTER_COLUMN_TYPE.exec(sql)\n ?? /^\\s*ALTER\\s+TABLE\\s+(?:ONLY\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)\\s+ALTER\\s+COLUMN\\s+(\"[^\"]+\"|[\\w$]+)\\s+(?:SET|DROP)\\b/i.exec(sql)\n if (sameColumn) return plainName(sameColumn[1]) === plainName(table) && plainName(sameColumn[2]) === plainName(column)\n\n let m = /^\\s*CREATE\\s+(?:MATERIALIZED\\s+)?VIEW\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\b[\\s\\S]*?\\bON\\s+(?:ONLY\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*(?:GRANT|REVOKE)\\b[\\s\\S]*?\\bON\\s+(?:TABLE\\s+)?((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)\\s+(?:TO|FROM)\\b/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*COMMENT\\s+ON\\s+(?:MATERIALIZED\\s+VIEW|VIEW)\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*COMMENT\\s+ON\\s+COLUMN\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)\\.(?:\"[^\"]+\"|[\\w$]+)\\s+IS\\b/i.exec(sql)\n if (m) return onView(m[1])\n m = /^\\s*CREATE\\s+(?:POLICY|(?:CONSTRAINT\\s+)?TRIGGER)\\s+(\"[^\"]+\"|[\\w$]+)[\\s\\S]*?\\bON\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (m) {\n const key = `${plainName(m[1])}@${plainName(m[2])}`\n if (attached.has(key)) { recreated.add(key); return true }\n return onView(m[2])\n }\n return false\n }\n\n let end = i + 1\n while (end < statements.length && belongs(statements[end])) end++\n\n // A policy or trigger drop that is neither on the altered table nor put\n // back here belongs to another diff that happened to land next to this\n // one — a policy genuinely being removed. Grouping it would put the whole\n // column change behind the destructive gate with it, so the run is\n // trimmed from its far end until only this change's own drops remain.\n const foreign = (d: typeof drops[number]) =>\n d.attached !== undefined && d.table !== plainName(table) && !recreated.has(d.attached)\n while (drops.length > 0 && foreign(drops[0])) {\n drops.shift()\n start++\n }\n if (drops.length === 0) {\n out.push(statements[i])\n i++\n continue\n }\n\n const group = [...out.splice(start), ...statements.slice(i, end)]\n out.push(group.join('\\n'))\n i = end\n }\n\n return out\n}\n\ninterface MergedStatement {\n up: string\n down: string\n /** Set when this entry is a DROP+CREATE pair replacing one object. */\n modified?: { kind: ReplaceableKind; name: string }\n}\n\n/**\n * The object kinds dbdiff replaces by dropping and recreating.\n *\n * Routines were the first (issue #35). Types, domains and sequences behave the\n * same way — an enum whose values changed arrives as `DROP TYPE` + `CREATE\n * TYPE` — and needed the same treatment for the same two reasons (issue #81).\n */\ntype ReplaceableKind = 'routine' | 'type' | 'sequence' | 'policy' | 'trigger' | 'view'\n\n/** How each kind's identifier is read out of a statement. */\nconst REPLACEABLE_NAME: Record<ReplaceableKind, (sql: string) => string> = {\n routine: extractRoutineName,\n type: (sql) => extractQualifiedName(sql, /\\b(?:TYPE|DOMAIN)\\s+(?:IF\\s+EXISTS\\s+)?/i),\n sequence: (sql) => extractQualifiedName(sql, /\\bSEQUENCE\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?/i),\n // `table.policy`: a policy name is unique only per table.\n policy: (sql) => policyLabel(sql),\n // `schema.table.trigger`, for the same reason.\n trigger: (sql) => triggerLabel(sql),\n view: (sql) => extractQualifiedName(sql, AFTER.view),\n}\n\n/** How a merged pair of each kind is reported. */\nconst REPLACEABLE_REPORT: Record<ReplaceableKind, { idPart: string; label: string; what: string }> = {\n routine: { idPart: 'function', label: 'Function modified', what: 'Function body' },\n type: { idPart: 'type', label: 'Type modified', what: 'Type definition' },\n sequence: { idPart: 'sequence', label: 'Sequence modified', what: 'Sequence definition' },\n policy: { idPart: 'policy', label: 'Policy modified', what: 'Policy definition' },\n trigger: { idPart: 'trigger', label: 'Trigger modified', what: 'Trigger definition' },\n view: { idPart: 'view', label: 'View modified', what: 'View definition' },\n}\n\n/** Whether a statement drops or creates a replaceable object, and of which kind. */\nfunction replaceablePart(sql: string): { kind: ReplaceableKind; drop: boolean } | undefined {\n // dbdiff renders a changed policy as DROP POLICY + CREATE POLICY, adjacent.\n // Apart, the DROP read as a policy *removed* and was held back by the\n // destructive gate (issue #88), leaving the CREATE to fail on the policy\n // still there. Together they are a replacement, which the gate allows.\n if (/^\\s*DROP\\s+POLICY\\b/i.test(sql)) return { kind: 'policy', drop: true }\n if (/^\\s*CREATE\\s+POLICY\\b/i.test(sql)) return { kind: 'policy', drop: false }\n // A changed trigger is dropped and recreated the same way, and read apart\n // was a critical \"Extra trigger\" for a trigger that is still wanted.\n if (/^\\s*DROP\\s+TRIGGER\\b/i.test(sql)) return { kind: 'trigger', drop: true }\n // A changed view too: dbdiff can only replace one, and a PostgreSQL 15\n // and 16+ pair printed every view differently.\n if (/^\\s*DROP\\s+(?:MATERIALIZED\\s+)?VIEW\\b/i.test(sql)) return { kind: 'view', drop: true }\n if (/^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:MATERIALIZED\\s+)?VIEW\\b/i.test(sql)) return { kind: 'view', drop: false }\n if (/^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER\\b/i.test(sql)) return { kind: 'trigger', drop: false }\n switch (classifyStatement(sql)) {\n case CREATE_FUNCTION: return { kind: 'routine', drop: false }\n case DROP_FUNCTION: return { kind: 'routine', drop: true }\n case 'create-type': return { kind: 'type', drop: false }\n case 'drop-type': return { kind: 'type', drop: true }\n case 'create-sequence': return { kind: 'sequence', drop: false }\n case 'drop-sequence': return { kind: 'sequence', drop: true }\n default: return undefined\n }\n}\n\n/** Kind and bare name together, so a function and a type of one name cannot pair. */\nfunction replacementKey(kind: ReplaceableKind, sql: string): string {\n const name = REPLACEABLE_NAME[kind](sql)\n if (kind === 'policy') return `policy:${name.replace(/\"/g, '').toLowerCase()}`\n // Table and trigger, without the schema a DROP may leave out.\n if (kind === 'trigger') return `trigger:${name.split('.').slice(-2).join('.').toLowerCase()}`\n return `${kind}:${name.slice(name.lastIndexOf('.') + 1).toLowerCase()}`\n}\n\n/**\n * Collapse `DROP FUNCTION` + `CREATE [OR REPLACE] FUNCTION` pairs for the same\n * routine into a single entry.\n *\n * dbdiff replaces a changed function by emitting both statements. Treating them\n * as independent issues reported one modified function twice — once as a\n * CRITICAL \"Extra function\" and once as a WARNING \"Function missing\" — when it\n * is neither extra nor missing (issue #35). On a real diff that inflated 105\n * genuine differences into 149 reported issues, and dragged the drift score\n * down via the bogus criticals.\n *\n * Only a DROP followed by a CREATE for the same routine is merged; an\n * unpaired DROP is still a genuine \"Extra function\".\n *\n * Postgres allows overloading, so one name can own several DROP+CREATE pairs\n * whose argument types differ. They cannot be told apart by name, and the\n * statements do not agree on a signature to match them by (see `replacementKey`),\n * so pairing goes by position:\n *\n * - Adjacent DROP+CREATE always merge. dbdiff renders a changed routine from a\n * single diff object, so the two statements come out together — adjacency is\n * what a replacement actually looks like.\n * - A non-adjacent pair merges only when that name has exactly one DROP and one\n * CREATE in the batch, where there is nothing to confuse it with. This is\n * the case issue #35 was about.\n *\n * Anything else stays unmerged and is reported as a genuine extra or missing\n * routine, which is the safe direction: over-reporting is noise, whereas a\n * wrong pairing writes a migration that drops an overload and recreates a\n * different one in its place.\n */\nexport function mergeReplacements(\n upStatements: string[],\n downStatements: string[],\n): MergedStatement[] {\n // Per key, the indices of the CREATEs still up for grabs, in source order.\n const unclaimedCreates = new Map<string, number[]>()\n const dropCounts = new Map<string, number>()\n upStatements.forEach((sql, i) => {\n const part = replaceablePart(sql)\n if (!part) return\n\n const key = replacementKey(part.kind, sql)\n if (part.drop) {\n dropCounts.set(key, (dropCounts.get(key) ?? 0) + 1)\n } else {\n unclaimedCreates.set(key, [...(unclaimedCreates.get(key) ?? []), i])\n }\n })\n\n const absorbed = new Set<number>()\n const out: MergedStatement[] = []\n\n upStatements.forEach((upSql, i) => {\n if (absorbed.has(i)) return\n\n const down = downStatements[i] ?? ''\n const part = replaceablePart(upSql)\n if (!part?.drop) {\n out.push({ up: upSql, down })\n return\n }\n\n const key = replacementKey(part.kind, upSql)\n const unambiguous = dropCounts.get(key) === 1 && unclaimedCreates.get(key)?.length === 1\n const createIdx = claimCreateFor(unclaimedCreates, key, i, unambiguous)\n if (createIdx === undefined) {\n out.push({ up: upSql, down })\n return\n }\n\n const createSql = upStatements[createIdx]\n absorbed.add(createIdx)\n out.push({\n // Drop first, create second, in one statement. Kept together rather than\n // ordered apart because `orderStatements` sends drops to the last phase\n // and creates to an early one, which put the CREATE before the DROP it\n // was replacing — `type \"order_state\" already exists`, and the whole\n // apply rolled back (issue #81). Phasing reads the CREATE in a merged\n // pair, so the pair runs where the object it leaves behind belongs.\n up: `${upSql}\\n${createSql}`,\n down: [down, downStatements[createIdx] ?? ''].filter(Boolean).join('\\n'),\n modified: {\n kind: part.kind,\n // A routine's name is qualified by its argument types, since overloads\n // share a name; nothing else can be overloaded.\n name: part.kind === 'routine'\n ? extractRoutineName(createSql) + extractRoutineArgs(upSql)\n : REPLACEABLE_NAME[part.kind](createSql),\n },\n })\n })\n\n return out\n}\n\n/**\n * Claim the CREATE that replaces the DROP at `dropIdx`, removing it so a later\n * DROP of the same name cannot claim it too.\n *\n * Normally that is the immediately following statement. When `unambiguous` —\n * one DROP and one CREATE for this name in the whole batch — any later CREATE\n * will do, since there is no second candidate to get it wrong.\n */\nfunction claimCreateFor(\n unclaimed: Map<string, number[]>,\n key: string,\n dropIdx: number,\n unambiguous: boolean,\n): number | undefined {\n const queue = unclaimed.get(key)\n if (!queue) return undefined\n\n const at = queue.findIndex((idx) => (unambiguous ? idx > dropIdx : idx === dropIdx + 1))\n if (at === -1) return undefined\n\n return queue.splice(at, 1)[0]\n}\n\n/**\n * Identify which UP statements to keep after filtering cross-schema FK false positives.\n *\n * Two-pass approach:\n * 1. Mark ADD CONSTRAINT ... FOREIGN KEY statements where the UP references an\n * ignored schema or the DOWN counterpart has broken `REFERENCES \"\" (\"\")`,\n * or the referenced table (even unqualified) is in `ignoredSchemaTables`.\n * 2. Mark paired DROP CONSTRAINT statements that share the same constraint name.\n */\nfunction filterCrossSchemaFks(\n upStmts: string[],\n downStmts: string[],\n schemas: string[],\n ignoredSchemaTables?: Set<string>,\n): boolean[] {\n const keep = new Array<boolean>(upStmts.length).fill(true)\n\n // Collect constraint names that are cross-schema FKs\n const crossSchemaConstraints = new Set<string>()\n\n // Pass 1: detect ADD CONSTRAINT ... FOREIGN KEY with cross-schema refs\n for (let i = 0; i < upStmts.length; i++) {\n const upper = upStmts[i].toUpperCase()\n if (!upper.includes('ADD CONSTRAINT') || !upper.includes('FOREIGN KEY')) continue\n\n const isCrossSchema =\n hasCrossSchemaRef(upStmts[i], schemas, ignoredSchemaTables) ||\n (downStmts[i] != null && hasBrokenRef(downStmts[i]))\n\n if (isCrossSchema) {\n keep[i] = false\n const name = upStmts[i].match(/CONSTRAINT\\s+\"([^\"]+)\"/i)?.[1]\n if (name) crossSchemaConstraints.add(name)\n }\n }\n\n // Pass 2: filter paired DROP CONSTRAINT for the same FK names\n for (let i = 0; i < upStmts.length; i++) {\n if (!keep[i]) continue\n const upper = upStmts[i].toUpperCase()\n if (!upper.includes('DROP CONSTRAINT')) continue\n const name = upStmts[i].match(/DROP\\s+CONSTRAINT\\s+\"([^\"]+)\"/i)?.[1]\n if (name && crossSchemaConstraints.has(name)) {\n keep[i] = false\n }\n }\n\n return keep\n}\n\n/**\n * Check if a REFERENCES clause points to an ignored schema, is empty/broken,\n * or is unqualified but the referenced table exists in an ignored schema.\n *\n * Handles three forms:\n * REFERENCES \"\" (\"\") — broken ref from dbdiff, always filtered\n * REFERENCES \"auth\".\"users\" (\"id\") — schema-qualified into an ignored schema: kept\n * when the target has that table, else filtered\n * REFERENCES \"users\" (\"id\") — unqualified, filtered if \"users\" is in\n * ignoredSchemaTables (queried from target DB)\n */\nfunction hasCrossSchemaRef(sql: string, schemas: string[], ignoredSchemaTables?: Set<string>): boolean {\n const refsMatch = sql.match(/REFERENCES\\s+\"([^\"]*)\"(?:\\s*\\.\\s*\"([^\"]*)\")?\\s*\\(\\s*\"([^\"]*)\"\\s*\\)/i)\n if (!refsMatch) return false\n const [, first, second] = refsMatch\n // Broken: REFERENCES \"\" (\"\")\n if (first === '') return true\n // Schema-qualified: REFERENCES \"auth\".\"users\" (\"id\"). A key from the user's\n // own schema onto an ignored one — every Supabase table referencing\n // auth.users — is real drift, kept when the target has the table it\n // references. Filtered only when that is not known, as before: dbdiff\n // before 3.0.0-rc.18 rendered these without the schema, which is why they\n // were all dropped, and so they were never synced.\n if (second !== undefined) {\n if (!schemas.some(s => s.toLowerCase() === first.toLowerCase())) return false\n return !ignoredSchemaTables?.has(`${first}.${second}`.toLowerCase())\n }\n // Unqualified: REFERENCES \"users\" (\"id\") — filter if the table lives in an ignored schema.\n // This catches the case where pg_dump or dbdiff drops the schema prefix due to\n // search_path, so the reference appears unqualified even though it targets e.g. auth.users.\n return ignoredSchemaTables ? ignoredSchemaTables.has(first.toLowerCase()) : false\n}\n\n/** Check if SQL contains a broken REFERENCES \"\" (\"\") from dbdiff. */\nfunction hasBrokenRef(sql: string): boolean {\n return /REFERENCES\\s+\"\"\\s*\\(\\s*\"\"\\s*\\)/i.test(sql)\n}\n\nfunction splitStatements(sql: string): string[] {\n if (!sql) return []\n\n const statements: string[] = []\n let buf = ''\n let i = 0\n\n while (i < sql.length) {\n // Dollar-quoted string: $tag$...$tag$ consumed as a single token so that\n // semicolons inside function/trigger/procedure bodies are not treated as\n // statement boundaries. The tag is /\\$([A-Za-z0-9_]*)\\$/ e.g. $$ or $body$.\n if (sql[i] === '$') {\n const tagMatch = sql.slice(i + 1).match(/^([A-Za-z0-9_]*)\\$/)\n if (tagMatch) {\n const tag = `$${tagMatch[1]}$`\n const closeIdx = sql.indexOf(tag, i + tag.length)\n if (closeIdx !== -1) {\n buf += sql.slice(i, closeIdx + tag.length)\n i = closeIdx + tag.length\n continue\n }\n }\n }\n\n // Statement boundary: ';' optionally followed by spaces/tabs/CR then '\\n'\n if (sql[i] === ';') {\n buf += ';'\n i++\n let j = i\n while (j < sql.length && (sql[j] === ' ' || sql[j] === '\\t' || sql[j] === '\\r')) j++\n if (j >= sql.length || sql[j] === '\\n') {\n const stmt = withoutLeadingComments(buf)\n if (stmt.length > 0) {\n statements.push(stmt)\n }\n buf = ''\n i = j < sql.length ? j + 1 : j\n }\n continue\n }\n\n buf += sql[i]\n i++\n }\n\n // Flush any trailing content without a statement-ending newline\n const last = withoutLeadingComments(buf)\n if (last.length > 0) {\n statements.push(last.endsWith(';') ? last : `${last};`)\n }\n\n return statements\n}\n\n/**\n * A statement without the `--` lines in front of it.\n *\n * A statement opening with a comment used to be dropped whole — and dbdiff\n * puts notes in front of statements: the DROP TYPE replacing an enum whose\n * labels it could not move came after three lines saying why, so it never\n * reached a finding.\n */\nfunction withoutLeadingComments(chunk: string): string {\n return chunk.trim().replace(/^(?:--[^\\n]*(?:\\n|$)\\s*)+/, '').trim()\n}\n\nexport function classifyStatement(sql: string): string {\n const upper = sql.toUpperCase().trimStart()\n // Views\n if (upper.startsWith('CREATE VIEW') || upper.startsWith('CREATE OR REPLACE VIEW')) return 'create-view'\n if (upper.startsWith('ALTER VIEW')) return 'alter-view'\n if (upper.startsWith('DROP VIEW')) return 'drop-view'\n // Functions / procedures\n if (upper.startsWith('CREATE FUNCTION') || upper.startsWith('CREATE OR REPLACE FUNCTION')) return CREATE_FUNCTION\n if (upper.startsWith('ALTER FUNCTION')) return 'alter-function'\n if (upper.startsWith('DROP FUNCTION')) return DROP_FUNCTION\n if (upper.startsWith('CREATE PROCEDURE') || upper.startsWith('CREATE OR REPLACE PROCEDURE')) return CREATE_FUNCTION\n if (upper.startsWith('DROP PROCEDURE')) return DROP_FUNCTION\n // Triggers\n if (upper.startsWith('CREATE TRIGGER') || upper.startsWith('CREATE OR REPLACE TRIGGER')) return 'create-trigger'\n if (upper.startsWith('ALTER TRIGGER')) return 'alter-trigger'\n if (upper.startsWith('DROP TRIGGER')) return 'drop-trigger'\n // Types / enums / domains\n if (upper.startsWith('CREATE TYPE')) return 'create-type'\n if (upper.startsWith('ALTER TYPE')) return 'alter-type'\n if (upper.startsWith('DROP TYPE')) return 'drop-type'\n if (upper.startsWith('CREATE DOMAIN')) return 'create-type'\n if (upper.startsWith('ALTER DOMAIN')) return 'alter-type'\n if (upper.startsWith('DROP DOMAIN')) return 'drop-type'\n // Tables\n if (upper.startsWith('ALTER TABLE')) return 'alter'\n if (upper.startsWith('CREATE TABLE')) return 'create-table'\n if (upper.startsWith('DROP TABLE')) return 'drop'\n // Indexes\n if (upper.startsWith('CREATE INDEX') || upper.startsWith('CREATE UNIQUE INDEX')) return 'create-index'\n if (upper.startsWith('DROP INDEX')) return 'drop'\n // Sequences\n if (upper.startsWith('CREATE SEQUENCE')) return 'create-sequence'\n if (upper.startsWith('ALTER SEQUENCE')) return 'alter-sequence'\n if (upper.startsWith('DROP SEQUENCE')) return 'drop-sequence'\n // Data\n if (upper.startsWith('INSERT')) return 'insert'\n if (upper.startsWith('UPDATE')) return 'update'\n if (upper.startsWith('DELETE')) return 'delete'\n return 'change'\n}\n\n/**\n * One title format for every schema finding: `<Finding>: <schema>.<name>`.\n *\n * Each kind used to carry its own ad-hoc regex, and two of them read the wrong\n * capture group: `/INDEX\\s+.../` never reached the index name at all, so\n * `CREATE INDEX idx_orders_status ON public.orders` was titled \"Index missing on\n * public\" — the schema, in the name's place (issue #47). The rules below all\n * go through one schema-aware identifier parser instead.\n *\n * Matched in order and anchored at the start of the statement, so a trigger\n * that executes a function is a trigger, not a function.\n */\ninterface SummaryRule {\n match: RegExp\n label: string\n name: (sql: string, downSql?: string) => string\n}\n\n/** Head patterns for the identifier that follows each keyword. */\nconst AFTER = {\n view: /\\bVIEW\\s+(?:IF\\s+EXISTS\\s+)?/i,\n trigger: /\\bTRIGGER\\s+(?:IF\\s+EXISTS\\s+)?/i,\n type: /\\bTYPE\\s+(?:IF\\s+EXISTS\\s+)?/i,\n domain: /\\bDOMAIN\\s+(?:IF\\s+EXISTS\\s+)?/i,\n sequence: /\\bSEQUENCE\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?/i,\n table: /\\bTABLE\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(?:ONLY\\s+)?/i,\n index: /\\bINDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?/i,\n policy: /\\bPOLICY\\s+(?:IF\\s+EXISTS\\s+)?/i,\n on: /\\bON\\s+(?:ONLY\\s+)?/i,\n}\n\n/** Name an object by the identifier following `head`. */\nconst named = (head: RegExp) => (sql: string) => extractQualifiedName(sql, head)\n\n/**\n * `table.policy` for a policy statement.\n *\n * A policy name is unique only per table, so the table is part of its\n * identity — the same keying the RLS check uses, which means the two checks\n * now name the same policy the same way.\n */\nfunction policyLabel(sql: string): string {\n const policy = extractQualifiedName(sql, AFTER.policy)\n const table = extractQualifiedName(sql, AFTER.on)\n\n if (policy === UNKNOWN_NAME) return UNKNOWN_NAME\n if (table === UNKNOWN_NAME) return policy\n\n // The table is qualified here rather than by the caller: the caller only\n // qualifies a name with no dot in it, and `orders.p` already has one.\n return `${qualifySchemaName(table)}.${policy}`\n}\n\n/**\n * `schema.table.trigger` for a trigger statement.\n *\n * A trigger name is unique only per table, like a policy's, and one name is\n * commonly reused on every table (`set_updated_at`): titled by the name alone,\n * three findings about three tables read as the same one three times. dbdiff\n * leaves the table of a DROP unqualified, so its schema is read off the\n * counterpart CREATE when that is on the same table.\n */\nfunction triggerLabel(sql: string, downSql?: string): string {\n const trigger = extractQualifiedName(sql, AFTER.trigger)\n let table = extractQualifiedName(sql, AFTER.on)\n if (trigger === UNKNOWN_NAME) return UNKNOWN_NAME\n if (table === UNKNOWN_NAME) return trigger\n\n if (!table.includes('.') && downSql) {\n const counterpart = extractQualifiedName(downSql, AFTER.on)\n if (counterpart.includes('.') && unqualify(counterpart) === table.toLowerCase()) table = counterpart\n }\n return `${qualifySchemaName(table)}.${trigger}`\n}\n\n/**\n * The schema @dbdiff/cli compares.\n *\n * Its Postgres adapter is scoped to `public` throughout — every catalogue query\n * filters on `schemaname = 'public'` — so a name it emits without a qualifier is\n * a `public` object, not an object of unknown schema. Restoring the qualifier is\n * recovering information the SQL dropped, not guessing at it.\n */\nconst DBDIFF_SCHEMA = 'public'\n\n/**\n * Put every schema finding's name in the same form: `schema.name`.\n *\n * Whether a name arrived qualified depended on which statement dbdiff happened\n * to emit — `CREATE INDEX ... ON public.orders` carries a schema, `DROP TABLE\n * \"legacy_notes\"` does not — so titles for one run were a mix of both, split by\n * object type rather than by anything a reader could predict, and the mix did\n * not even hold within a type (issue #70). A long list then neither sorted nor\n * aligned.\n *\n * Splits at the first `(` so a routine's argument list cannot be mistaken for a\n * qualifier: `dist(numeric(10,2))` contains dots that are not schema separators.\n */\nfunction qualifySchemaName(name: string): string {\n if (name === UNKNOWN_NAME) return name\n const paren = name.indexOf('(')\n const head = paren === -1 ? name : name.slice(0, paren)\n if (head.includes('.')) return name\n return `${DBDIFF_SCHEMA}.${name}`\n}\n\n/**\n * Qualify an index with the schema of the table it is on.\n *\n * Postgres puts an index in its table's schema and its grammar does not let\n * the CREATE qualify the index name, so the `ON` clause is where the schema\n * actually is. Left bare when the table is unqualified too — the schema is\n * then genuinely unknown, and inventing `public` would be a guess.\n */\nfunction indexLabel(sql: string): string {\n const name = extractQualifiedName(sql, AFTER.index)\n if (name === UNKNOWN_NAME || name.includes('.')) return name\n\n const table = extractQualifiedName(sql, AFTER.on)\n const dot = table.lastIndexOf('.')\n return dot === -1 ? name : `${table.slice(0, dot)}.${name}`\n}\n\nconst SCHEMA_RULES: SummaryRule[] = [\n { match: /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:MATERIALIZED\\s+)?VIEW\\b/i, label: 'View missing', name: named(AFTER.view) },\n { match: /^\\s*ALTER\\s+(?:MATERIALIZED\\s+)?VIEW\\b/i, label: 'View altered', name: named(AFTER.view) },\n { match: /^\\s*DROP\\s+(?:MATERIALIZED\\s+)?VIEW\\b/i, label: 'Extra view', name: named(AFTER.view) },\n\n { match: /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?FUNCTION\\b/i, label: 'Function missing', name: routineLabel },\n { match: /^\\s*ALTER\\s+FUNCTION\\b/i, label: 'Function altered', name: routineLabel },\n { match: /^\\s*DROP\\s+FUNCTION\\b/i, label: 'Extra function', name: routineLabel },\n { match: /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?PROCEDURE\\b/i, label: 'Procedure missing', name: routineLabel },\n { match: /^\\s*DROP\\s+PROCEDURE\\b/i, label: 'Extra procedure', name: routineLabel },\n\n { match: /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER\\b/i, label: 'Trigger missing', name: triggerLabel },\n { match: /^\\s*ALTER\\s+TRIGGER\\b/i, label: 'Trigger altered', name: triggerLabel },\n { match: /^\\s*DROP\\s+TRIGGER\\b/i, label: 'Extra trigger', name: triggerLabel },\n\n { match: /^\\s*CREATE\\s+TYPE\\b/i, label: 'Type missing', name: named(AFTER.type) },\n { match: /^\\s*ALTER\\s+TYPE\\b/i, label: 'Type altered', name: named(AFTER.type) },\n { match: /^\\s*DROP\\s+TYPE\\b/i, label: 'Extra type', name: named(AFTER.type) },\n { match: /^\\s*CREATE\\s+DOMAIN\\b/i, label: 'Domain missing', name: named(AFTER.domain) },\n { match: /^\\s*ALTER\\s+DOMAIN\\b/i, label: 'Domain altered', name: named(AFTER.domain) },\n { match: /^\\s*DROP\\s+DOMAIN\\b/i, label: 'Extra domain', name: named(AFTER.domain) },\n\n { match: /^\\s*ALTER\\s+TABLE\\b/i, label: 'Table altered', name: named(AFTER.table) },\n { match: /^\\s*CREATE\\s+TABLE\\b/i, label: 'Table missing', name: named(AFTER.table) },\n { match: /^\\s*DROP\\s+TABLE\\b/i, label: 'Extra table', name: named(AFTER.table) },\n\n { match: /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\b/i, label: 'Index missing', name: indexLabel },\n { match: /^\\s*DROP\\s+INDEX\\b/i, label: 'Extra index', name: named(AFTER.index) },\n\n // Policies. Without these, dbdiff's own CREATE/DROP POLICY statements fell\n // through to the catch-all and were titled \"Schema change: unknown\" — the\n // one finding in a report that named no object at all (issue #97). Keyed\n // `table.policy`, which is how a policy is identified and how the RLS check\n // names the same one.\n { match: /^\\s*CREATE\\s+POLICY\\b/i, label: 'Policy missing', name: policyLabel },\n { match: /^\\s*ALTER\\s+POLICY\\b/i, label: 'Policy altered', name: policyLabel },\n { match: /^\\s*DROP\\s+POLICY\\b/i, label: 'Extra policy', name: policyLabel },\n\n // Comments (rc.21) and extensions (rc.22), named like everything else, and\n // a comment by the object it is on and that object's kind.\n { match: /^\\s*COMMENT\\s+ON\\b/i, label: 'Comment changed', name: commentLabel },\n { match: /^\\s*CREATE\\s+EXTENSION\\b/i, label: 'Extension missing', name: extensionLabel },\n { match: /^\\s*DROP\\s+EXTENSION\\b/i, label: 'Extra extension', name: extensionLabel },\n\n { match: /^\\s*CREATE\\s+SEQUENCE\\b/i, label: 'Sequence missing', name: named(AFTER.sequence) },\n { match: /^\\s*ALTER\\s+SEQUENCE\\b/i, label: 'Sequence altered', name: named(AFTER.sequence) },\n { match: /^\\s*DROP\\s+SEQUENCE\\b/i, label: 'Extra sequence', name: named(AFTER.sequence) },\n]\n\n/** An identifier as written, unquoted: `\"App Data\"` → `App Data`. */\nconst unquoted = (part: string) => part.replace(/^\"|\"$/g, '').replace(/\"\"/g, '\"')\n\n/**\n * `public.orders.own (policy)` for `COMMENT ON POLICY \"own\" ON \"public\".\"orders\"`:\n * the object, qualified as written, and its kind. A constraint, trigger or\n * policy is named after the table (or domain) it is on.\n */\nfunction commentLabel(sql: string): string {\n const m = /^\\s*COMMENT\\s+ON\\s+(MATERIALIZED\\s+VIEW|FOREIGN\\s+TABLE|[A-Z]+)\\s+([\\s\\S]*?)\\s+IS\\s/i.exec(sql)\n if (!m) return UNKNOWN_NAME\n const kind = m[1].toLowerCase().replace(/\\s+/g, ' ')\n const on = /^(\"(?:[^\"]|\"\")+\"|\\S+)\\s+ON\\s+(?:DOMAIN\\s+)?([\\s\\S]+)$/i.exec(m[2].trim())\n const object = on ? `${on[2].trim()}.${on[1]}` : m[2].trim()\n const name = object.split(/\\.(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/).map(unquoted).join('.')\n return `${name} (${kind})`\n}\n\n/** `schema.extension` for CREATE EXTENSION ... WITH SCHEMA, or the bare name. */\nfunction extensionLabel(sql: string): string {\n const name = /\\bEXTENSION\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(\"[^\"]+\"|[\\w$-]+)/i.exec(sql)?.[1]\n const schema = /\\bSCHEMA\\s+(\"[^\"]+\"|[\\w$]+)/i.exec(sql)?.[1]\n if (!name) return UNKNOWN_NAME\n return schema ? `${unquoted(schema)}.${unquoted(name)}` : unquoted(name)\n}\n\n/** Titles for a schema made, dropped or commented on, which have no schema of their own. */\nfunction schemaTitle(sql: string, downSql?: string): string | undefined {\n const m = /^\\s*(CREATE|DROP|COMMENT\\s+ON)\\s+SCHEMA\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?(\"[^\"]+\"|[\\w$]+)/i.exec(sql)\n if (!m) return undefined\n const label = { CREATE: 'Schema missing', DROP: 'Extra schema' }[m[1].toUpperCase() as 'CREATE' | 'DROP']\n return label ? `${label}: ${unquoted(m[2])}` : `${commentChange(sql, downSql)}: schema ${unquoted(m[2])}`\n}\n\nconst CLEARS_COMMENT = /\\bIS\\s+NULL\\s*;?\\s*$/i\n\n/**\n * What a comment finding does. \"Comment changed\" was the title for all three,\n * including a comment on an object the target does not have yet, where there\n * is nothing to change: the DOWN of a comment only the source has clears it,\n * and the UP of one only the target has does.\n */\nfunction commentChange(sql: string, downSql?: string): string {\n if (CLEARS_COMMENT.test(sql)) return 'Extra comment'\n if (downSql && CLEARS_COMMENT.test(downSql)) return 'Comment missing'\n return 'Comment changed'\n}\n\n/** Titles for the row-level findings of the data check. */\nfunction summariseDataStatement(sql: string): string {\n const table = extractQualifiedName(sql, /\\b(?:INTO|FROM|UPDATE)\\s+(?:ONLY\\s+)?/i)\n const upper = sql.toUpperCase().trimStart()\n if (upper.startsWith('INSERT')) return `Missing row in ${table}`\n if (upper.startsWith('DELETE')) return `Extra row in ${table}`\n if (upper.startsWith('UPDATE')) return `Modified row in ${table}`\n return `Data change in ${table}`\n}\n\n/**\n * Title one finding.\n *\n * `downSql` is the paired counterpart statement, used only to recover a schema\n * the UP statement does not carry — see `routineLabel`.\n */\nexport function summariseStatement(sql: string, check: 'schema' | 'data', downSql?: string): string {\n if (check === 'data') return summariseDataStatement(sql)\n\n const schema = schemaTitle(sql, downSql)\n if (schema) return schema\n\n for (const rule of SCHEMA_RULES) {\n if (rule.match.test(sql)) {\n const label = rule.name === commentLabel ? commentChange(sql, downSql) : rule.label\n return `${label}: ${qualifySchemaName(rule.name(sql, downSql))}`\n }\n }\n\n // Same `<finding>: <schema>.<name>` shape as every rule above, so an\n // unclassified change lines up with the rest of the list too.\n return `Schema change: ${qualifySchemaName(\n extractQualifiedName(sql, /\\b(?:TABLE|INTO|FROM|UPDATE)\\s+(?:ONLY\\s+)?/i),\n )}`\n}\n\n/**\n * Name a routine in an issue title, schema-qualified, with its argument\n * signature.\n *\n * The detection has been signature-aware since overloads were fixed, but only\n * the \"Function modified\" title carried the signature through — \"Extra\n * function\" printed the bare name (issue #40). For an overloaded routine that\n * left the title unable to say which overload was being dropped, and two\n * target-only overloads of one name produced two identical titles.\n *\n * The schema is still never invented, but it no longer has to be missing.\n * dbdiff emits a DROP unqualified (`DROP FUNCTION IF EXISTS \"example_fn\"(uuid)`)\n * while the DOWN statement that restores the same routine comes from\n * `pg_get_functiondef` and *is* qualified. So when the UP has no schema, it is\n * read off that counterpart — a schema dbdiff itself reported, not a guess —\n * which is what left \"Extra function\" the one unqualified schema title\n * (issue #47).\n *\n * The counterpart is only trusted when it names the same routine; a mismatched\n * pair would otherwise attach one routine's schema to another's name.\n */\nexport function routineLabel(sql: string, downSql?: string): string {\n const name = extractRoutineName(sql)\n const args = extractRoutineArgs(sql)\n if (!downSql || name === UNKNOWN_NAME || name.includes('.')) return name + args\n\n const counterpart = extractRoutineName(downSql)\n const sameRoutine = unqualify(counterpart) === unqualify(name)\n return (counterpart.includes('.') && sameRoutine ? counterpart : name) + args\n}\n\n/** The last segment of a possibly schema-qualified name, lowercased. */\nfunction unqualify(name: string): string {\n return name.slice(name.lastIndexOf('.') + 1).toLowerCase()\n}\n\n/**\n * Extract a routine name from a FUNCTION or PROCEDURE statement.\n *\n * A bare `/FUNCTION\\s+\"?(\\w+)\"?/` gets this wrong in both directions\n * (issue #35): it returns \"IF\" for `DROP FUNCTION IF EXISTS \"f\"`, and the\n * schema qualifier \"public\" for `CREATE OR REPLACE FUNCTION public.f(...)`.\n * Neither title named the routine at all.\n *\n * Skips an optional IF EXISTS, then takes the optionally schema-qualified,\n * optionally quoted identifier, normalising `\"public\" . \"f\"` to `public.f`.\n */\nexport function extractRoutineName(sql: string): string {\n return extractQualifiedName(sql, /\\b(?:FUNCTION|PROCEDURE)\\s+(?:IF\\s+EXISTS\\s+)?/i)\n}\n\n/** What a title shows when the identifier cannot be read out of the SQL. */\nexport const UNKNOWN_NAME = 'unknown'\n\n/**\n * Read the optionally schema-qualified, optionally quoted identifier that\n * follows `head`, normalising `\"public\" . \"f\"` to `public.f`.\n *\n * The one identifier parser behind every schema title. Before it, each kind\n * carried its own `/KEYWORD\\s+[\"'`]?(\\w+)/`, and those got it wrong in both\n * directions (issues #35, #47): \"IF\" for `DROP FUNCTION IF EXISTS \"f\"`, and the\n * schema qualifier \"public\" for anything written `public.name` — which is how\n * an index came to be titled by its schema instead of its name.\n *\n * Matched piecewise rather than as one expression. A combined pattern needs an\n * optional quote on both sides of each identifier (\"?[\\w$]+\"?), and that\n * ambiguity backtracks super-linearly on adversarial input — a real concern for\n * SQL arriving from an external process.\n */\nexport function extractQualifiedName(sql: string, head: RegExp): string {\n const found = head.exec(sql)\n if (!found) return UNKNOWN_NAME\n\n let rest = sql.slice(found.index + found[0].length)\n const parts: string[] = []\n\n for (let depth = 0; depth < 2; depth++) {\n // A quoted name doubles any quote inside it: \"say \"\"hi\"\" there\".\n const ident = /^(?:\"((?:[^\"]|\"\")*)\"|([\\w$]+))/.exec(rest)\n if (!ident) break\n parts.push(ident[1] !== undefined ? ident[1].replace(/\"\"/g, '\"') : ident[2])\n rest = rest.slice(ident[0].length)\n\n const dot = /^\\s*\\.\\s*/.exec(rest)\n if (!dot) break\n rest = rest.slice(dot[0].length)\n }\n\n return parts.length > 0 ? parts.join('.') : UNKNOWN_NAME\n}\n\n/**\n * Extract the argument list of a `DROP FUNCTION`, parens included.\n *\n * @dbdiff/cli >= 3.0.0-rc.7 qualifies the DROP with the argument types so an\n * overloaded routine can be dropped unambiguously — `DROP FUNCTION IF EXISTS\n * \"dist\"(bigint,bigint)`. Earlier versions emitted a bare name, and MySQL has\n * no overloading, so both return ''.\n *\n * Scanned rather than matched. The types can themselves contain parens\n * (`numeric(10,2)`), so this counts depth instead of taking the first `)`.\n */\nexport function extractRoutineArgs(sql: string): string {\n const open = sql.indexOf('(')\n if (open === -1) return ''\n\n let depth = 0\n for (let i = open; i < sql.length; i++) {\n if (sql[i] === '(') depth++\n else if (sql[i] === ')' && --depth === 0) return sql.slice(open, i + 1)\n }\n return ''\n}\n","/**\n * SQL read by PostgreSQL's own parser, rather than by regular expressions.\n *\n * SupaForge has to understand statements it did not write — DBDiff's fixes, a\n * snapshot's files, migrations — to order them, hold back the destructive\n * ones, and find what they name. Reading that from the text with patterns\n * meant guessing: a role named inside a function body, `TRUNCATE` as a\n * privilege rather than a statement, a quoted name with a dot in it. Each\n * guess that went wrong was a bug, fixed by blanking out more of the text\n * first (sqlSkeleton) and adding another pattern.\n *\n * libpg_query is the parser PostgreSQL itself uses, compiled to WebAssembly.\n * It returns each statement as a tree, so a function body is a string in a\n * field rather than text that might look like DDL, and a name is a list of\n * identifiers rather than something to split on dots.\n *\n * The module is loaded once, when this file is first imported, so every\n * function here is synchronous.\n */\nimport { loadModule, parseSync } from 'libpg-query'\n\nawait loadModule()\n\n/** One parsed statement: its node type, and the node itself. */\nexport interface Statement {\n /** `DropStmt`, `AlterTableStmt`, `CreatePolicyStmt`… */\n kind: string\n // The parser's tree is untyped JSON; accessors below give it shape.\n node: Record<string, any>\n}\n\n/**\n * The statements in `sql`, or undefined when PostgreSQL would not accept it.\n *\n * Undefined rather than an exception: a caller can then fall back to what it\n * did before, which matters while SupaForge is moved over piece by piece.\n */\nexport function parseStatements(sql: string): Statement[] | undefined {\n try {\n const tree = parseSync(sql) as { stmts?: Array<{ stmt: Record<string, any> }> }\n return (tree.stmts ?? []).map(({ stmt }) => {\n const kind = Object.keys(stmt)[0]\n return { kind, node: stmt[kind] }\n })\n } catch {\n return undefined\n }\n}\n\n/** The plain name list of a `List` of `String` nodes, as the parser gives one. */\nexport function names(list: Array<Record<string, any>> | undefined): string[] {\n return (list ?? []).map(item => item.String?.sval ?? '').filter(Boolean)\n}\n\n/** The bare name of a `RangeVar` (a table reference), without its schema. */\nexport function relationName(rangeVar: Record<string, any> | undefined): string {\n return rangeVar?.relname ?? ''\n}\n","import { splitSqlStatements } from './utils/sql-split.js'\nimport { parseStatements, type Statement } from './sql-ast.js'\nimport { escapeRegex } from './utils/strings.js'\n\n/**\n * Dependency analysis for the SQL statements a diff produces.\n *\n * `@dbdiff/cli` emits one statement per difference, in the order it walked the\n * catalogue. That order carries no meaning for execution: a trigger can sort\n * ahead of the function it calls, and applying the set top-to-bottom then fails\n * on a sync that was perfectly valid (issue #48).\n *\n * Everything here works on the SQL text alone, because that is all a fix set\n * is. Two views of a statement are used, and the distinction matters:\n *\n * - the **skeleton** (`sqlSkeleton`), with string and dollar-quoted bodies\n * removed, for deciding *what a statement is*. A function body containing\n * the words `CREATE TABLE` must not make its statement look like a table.\n * - the **full text**, for deciding *what a statement mentions*. A view or\n * function body is exactly where the references to other objects live.\n */\n\n// ─── Execution phases ────────────────────────────────────────────────────────\n\n/**\n * Coarse ordering by object kind, ascending.\n *\n * Postgres requires an object to exist before anything referencing it is\n * created, and requires dependants to be gone before their base object is\n * dropped. Both directions are captured here: dependants are dropped first,\n * base objects are created first, and the destructive drops land at the end.\n *\n * Gaps between the values leave room to slot a kind in later without\n * renumbering the rest.\n */\nexport const PHASE = {\n /** Triggers, policies, views, indexes — dropped before what they depend on. */\n DROP_DEPENDANT: 10,\n /** A schema, before anything is made in it. */\n CREATE_SCHEMA: 15,\n /**\n * An extension, before the types and tables that may use it — an exclusion\n * constraint's btree_gist operator class. Read as OTHER it came after the\n * table, which failed (`no default operator class for access method gist`).\n */\n CREATE_EXTENSION: 20,\n /** Types, domains, sequences: no dependencies of their own. */\n CREATE_BASE: 30,\n CREATE_TABLE: 40,\n /** Columns and constraints, needing every table to exist first. */\n ALTER_TABLE: 50,\n /** Before the triggers that execute them and the views that call them. */\n CREATE_ROUTINE: 60,\n CREATE_INDEX: 70,\n CREATE_VIEW: 80,\n /** Anything unrecognised — grants, comments, ownership. */\n OTHER: 85,\n /** Triggers and policies: the last things to be created. */\n CREATE_DEPENDANT: 90,\n /**\n * Comments, once what they name exists: a policy or trigger is created at\n * CREATE_DEPENDANT, and a COMMENT ON it read as OTHER ran before it.\n */\n COMMENT: 95,\n /** Row changes, once the structure holding them is in place. */\n DATA: 100,\n DROP_TABLE: 110,\n /**\n * Routines, dropped once nothing calls them: the triggers, views and\n * policies come off first, and so do the column defaults, CHECK constraints,\n * expression indexes and tables — all of which can call one, and were still\n * in place when routines were dropped at the start (`cannot drop function\n * ... because other objects depend on it`). Before the types a routine's\n * signature can use.\n */\n DROP_ROUTINE: 115,\n DROP_BASE: 120,\n /** Once nothing that used it is left. */\n DROP_EXTENSION: 125,\n} as const\n\n/** The phases that take something away rather than make it. */\nconst DROP_PHASES: ReadonlySet<number> = new Set([\n PHASE.DROP_DEPENDANT, PHASE.DROP_TABLE, PHASE.DROP_ROUTINE, PHASE.DROP_BASE, PHASE.DROP_EXTENSION,\n])\n\n/**\n * Phase rules, first match wins.\n *\n * Order is deliberate in two places. The `CREATE` rules precede the `DROP`\n * ones so a merged `DROP FUNCTION` + `CREATE OR REPLACE FUNCTION` pair — how\n * `mergeRoutineReplacements` represents a modified routine — is phased by the\n * object it leaves behind rather than by the drop that opens it. And the\n * dependant kinds precede `FUNCTION` and `TABLE` so `CREATE TRIGGER ... EXECUTE\n * FUNCTION f()` is read as a trigger.\n */\nconst PHASE_RULES: Array<[RegExp, number]> = [\n // A column type change grouped with the dependants dbdiff drops and\n // recreates around it (see groupColumnTypeChanges) runs as the column change\n // it is — before a foreign key that needs the new type, for one — not as the\n // view or policy it happens to recreate.\n [/^\\s*DROP\\s+(?:POLICY|TRIGGER|(?:MATERIALIZED\\s+)?VIEW)\\b[\\s\\S]*\\bALTER\\s+TABLE\\s+\\S+\\s+ALTER\\s+COLUMN\\s+\\S+\\s+(?:SET\\s+DATA\\s+)?TYPE\\b/i, PHASE.ALTER_TABLE],\n [/\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER\\b/i, PHASE.CREATE_DEPENDANT],\n [/\\bCREATE\\s+POLICY\\b/i, PHASE.CREATE_DEPENDANT],\n [/\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:MATERIALIZED\\s+)?VIEW\\b/i, PHASE.CREATE_VIEW],\n [/\\bCREATE\\s+(?:UNIQUE\\s+)?INDEX\\b/i, PHASE.CREATE_INDEX],\n [/\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:FUNCTION|PROCEDURE)\\b/i, PHASE.CREATE_ROUTINE],\n [/^\\s*COMMENT\\s+ON\\b/i, PHASE.COMMENT],\n [/^\\s*CREATE\\s+SCHEMA\\b/i, PHASE.CREATE_SCHEMA],\n [/^\\s*CREATE\\s+EXTENSION\\b/i, PHASE.CREATE_EXTENSION],\n [/^\\s*DROP\\s+EXTENSION\\b/i, PHASE.DROP_EXTENSION],\n [/\\bCREATE\\s+(?:TYPE|DOMAIN|SEQUENCE)\\b/i, PHASE.CREATE_BASE],\n [/\\bCREATE\\s+TABLE\\b/i, PHASE.CREATE_TABLE],\n [/^\\s*ALTER\\s+TABLE\\b/i, PHASE.ALTER_TABLE],\n [/^\\s*DROP\\s+(?:TRIGGER|POLICY|INDEX)\\b/i, PHASE.DROP_DEPENDANT],\n [/^\\s*DROP\\s+(?:MATERIALIZED\\s+)?VIEW\\b/i, PHASE.DROP_DEPENDANT],\n [/^\\s*DROP\\s+(?:FUNCTION|PROCEDURE)\\b/i, PHASE.DROP_ROUTINE],\n [/^\\s*DROP\\s+TABLE\\b/i, PHASE.DROP_TABLE],\n [/^\\s*DROP\\s+(?:TYPE|DOMAIN|SEQUENCE)\\b/i, PHASE.DROP_BASE],\n [/^\\s*(?:INSERT|UPDATE|DELETE)\\b/i, PHASE.DATA],\n]\n\n/** Which execution phase a statement belongs to. */\nexport function statementPhase(sql: string): number {\n const skeleton = sqlSkeleton(sql)\n for (const [pattern, phase] of PHASE_RULES) {\n if (pattern.test(skeleton)) return phase\n }\n return PHASE.OTHER\n}\n\n// ─── Text views ──────────────────────────────────────────────────────────────\n\n/** Dollar-quoted routine bodies: `$$ ... $$`, `$fn$ ... $fn$`. */\nconst DOLLAR_BODY = /\\$([A-Za-z0-9_]*)\\$[\\s\\S]*?\\$\\1\\$/g\n\n/**\n * Single-quoted literals, doubled quotes included.\n *\n * Written as the unrolled `'[^']*(?:''[^']*)*'` rather than the equivalent\n * `'(?:[^']|'')*'`: only one alternative can match at any position either way,\n * but the unrolled form has no alternation to backtrack through at all, which\n * matters for a pattern run over SQL from an external process.\n */\nconst STRING_LITERAL = /'[^']*(?:''[^']*)*'/g\n\n/** `-- to end of line`, and `/* ... *\\/` across lines. */\nconst LINE_COMMENT = /--[^\\n]*/g\nconst BLOCK_COMMENT = /\\/\\*[\\s\\S]*?\\*\\//g\n\n/**\n * A statement with its literals and routine bodies blanked out.\n *\n * Used wherever the *shape* of a statement is being read rather than its\n * contents, so a body that happens to contain DDL keywords cannot be mistaken\n * for the statement's own kind.\n */\nexport function sqlSkeleton(sql: string): string {\n return sql\n .replace(DOLLAR_BODY, ' ')\n .replace(STRING_LITERAL, \" '' \")\n // Comments last, so a `--` inside a literal has already been blanked and\n // cannot swallow the rest of the line. dbdiff's own migrations are full of\n // `-- Recreate trigger` lines, and a commented-out CREATE would otherwise\n // read as a real one: enough to make the duplicate-fix check believe an\n // object exists and drop the statement that genuinely creates it.\n .replace(LINE_COMMENT, ' ')\n .replace(BLOCK_COMMENT, ' ')\n}\n\n// ─── Identifiers ─────────────────────────────────────────────────────────────\n\n/** One name, quoted (its own quotes doubled) or not. */\nconst NAME_PART = String.raw`\"(?:[^\"]|\"\")+\"|[\\w$]+`\n\n/** An optionally schema-qualified, optionally quoted identifier. */\nconst IDENT = String.raw`(?:${NAME_PART})(?:\\s*\\.\\s*(?:${NAME_PART}))?`\n\n/** Strip quoting and any schema qualifier, leaving a comparable bare name. */\nexport function bareName(identifier: string): string {\n const parts = identifier.match(new RegExp(NAME_PART, 'g')) ?? [identifier]\n return unquote(parts[parts.length - 1]).toLowerCase()\n}\n/** A quoted identifier as the name it is, its doubled quotes made single. */\nconst unquote = (part: string) => {\n const p = part.trim()\n return p.startsWith('\"') ? p.slice(1, -1).replace(/\"\"/g, '\"') : p\n}\n\n/** `schema.table.object`, lowercased, `public` where no schema is named: how policies are keyed. */\nconst objectKey = (schema: string | undefined, table: string | undefined, name: string | undefined) =>\n `${(schema || 'public').toLowerCase()}.${(table ?? '').toLowerCase()}.${(name ?? '').toLowerCase()}`\n\n/**\n * A relation's name with its schema, `public` where it names none:\n * `\"app\".\"accounts\"` → `app.accounts`, `users` → `public.users`. Folded the\n * way bareName folds, so the same relation written either way agrees.\n */\nexport function schemaQualified(identifier: string): string {\n const parts = identifier.match(new RegExp(NAME_PART, 'g')) ?? [identifier]\n const fold = (part: string) => unquote(part).toLowerCase()\n return `${parts.length > 1 ? fold(parts[0]) : 'public'}.${fold(parts[parts.length - 1])}`\n}\n\n/** `CREATE [OR REPLACE] [UNIQUE|MATERIALIZED|TEMP] <kind> [IF NOT EXISTS] <name>` */\nconst CREATES = new RegExp(\n String.raw`\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:UNIQUE\\s+|MATERIALIZED\\s+|TEMP(?:ORARY)?\\s+|CONSTRAINT\\s+){0,2}` +\n String.raw`(?:TABLE|VIEW|FUNCTION|PROCEDURE|TYPE|DOMAIN|SEQUENCE|INDEX|TRIGGER|POLICY)\\s+` +\n String.raw`(?:IF\\s+NOT\\s+EXISTS\\s+)?(${IDENT})`,\n 'gi',\n)\n\n/**\n * The bare names of every object a statement creates.\n *\n * Read off the skeleton so a routine body that creates something locally does\n * not advertise it to the rest of the batch. A merged DROP + CREATE pair\n * reports the name it recreates, which is what other statements need.\n */\nexport function providedNames(sql: string): string[] {\n const names = new Set<string>()\n for (const match of sqlSkeleton(sql).matchAll(CREATES)) {\n names.add(bareName(match[1]))\n }\n return [...names]\n}\n\n/**\n * A statement that only removes things.\n *\n * These take no \"must run after a CREATE\" edges: `DROP TABLE orders` mentions\n * `orders` but has to run *after* everything using it, not after its creation —\n * an ordering the phases already express. Recognised by creating nothing rather\n * than by the leading keyword alone, so a merged DROP + CREATE pair is\n * correctly excluded.\n */\nfunction isDropOnly(sql: string, provides: string[]): boolean {\n return provides.length === 0 && /^\\s*DROP\\b/i.test(sql)\n}\n\n// ─── Table references ────────────────────────────────────────────────────────\n\n/** `FROM`/`JOIN`/`INTO`/`UPDATE`/`REFERENCES` each introduce a table name. */\nconst BODY_TABLE_REF = new RegExp(String.raw`\\b(?:FROM|JOIN|INTO|UPDATE|REFERENCES)\\s+(?:ONLY\\s+)?(${IDENT})`, 'gi')\n\n/**\n * The `ON <table>` of an index, trigger or policy.\n *\n * Anchored on what follows the name so a join condition (`ON a.id = b.id`) is\n * not read as a table reference — the trailing keyword or punctuation is what\n * separates the two forms.\n */\nconst ON_TABLE_REF = new RegExp(String.raw`\\bON\\s+(?:ONLY\\s+)?(${IDENT})\\s*(?:USING\\b|FOR\\b|AS\\b|TO\\b|\\(|;|$)`, 'gi')\n\n/** The table an `ALTER`/`DROP TABLE` acts on. */\nconst TARGET_TABLE_REF = new RegExp(\n String.raw`^\\s*(?:ALTER|DROP)\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${IDENT})`,\n 'gi',\n)\n\n/**\n * Keywords that can follow a reference keyword without naming a table.\n *\n * `UPDATE ON public.orders` in a trigger definition is the one that matters:\n * without this, the word `ON` would be collected as a table called \"on\".\n */\nconst NOT_A_TABLE = new Set([\n 'on', 'of', 'from', 'join', 'into', 'select', 'lateral', 'only', 'conflict',\n 'delete', 'update', 'insert', 'constraint', 'each', 'row', 'statement', 'values',\n])\n\n/**\n * The tables a statement reads, writes or hangs off, as bare lowercase names.\n *\n * Deliberately over-inclusive: it reads the full text, bodies included, so a\n * view or function that touches an out-of-scope table is caught. A false\n * positive costs a fix that is skipped with a reason the user can read, which\n * is the safer direction — a false negative is a statement that runs and fails\n * (issue #48).\n */\n/**\n * The policies a statement creates, as `table.policy` in lower case.\n *\n * Two layers can now legitimately produce the same `CREATE POLICY`. The schema\n * check gets its SQL from `@dbdiff/cli`, which models RLS policies as of\n * 3.0.0-rc.10, and the rls check has always written its own. Applied together\n * the second fails with \"policy ... already exists\" and takes the whole\n * transaction with it, so the duplicate has to be recognised before it runs.\n *\n * Matched on the pair that identifies a policy in Postgres — its name and its\n * table — because the two layers spell the same policy differently: one emits\n * `ON \"t\"`, the other `ON \"public\".\"t\"` across several lines. The schema\n * qualifier is dropped for the same reason `referencedTables` drops it.\n */\nexport function createdPolicies(sql: string): string[] {\n const tree = parseStatements(sql)\n if (tree) {\n return tree.filter(s => s.kind === 'CreatePolicyStmt')\n .map(({ node }) => objectKey(node.table?.schemaname, node.table?.relname, node.policy_name))\n }\n const out: string[] = []\n const re = new RegExp(String.raw`CREATE\\s+POLICY\\s+(${NAME_PART})\\s+ON\\s+(${IDENT})`, 'gi')\n for (const m of sqlSkeleton(sql).matchAll(re)) {\n out.push(`${schemaQualified(m[2])}.${bareName(m[1])}`)\n }\n return out\n}\n\n/**\n * True when creating policies is all this statement does.\n *\n * The schema check bundles its policy alongside the table and the ENABLE ROW\n * LEVEL SECURITY that makes it mean anything, so that statement must never be\n * dropped as a duplicate — only a statement whose sole purpose is the policy can\n * be. Anything left once the CREATE POLICY statements are removed counts, which\n * errs towards keeping a statement rather than losing DDL.\n */\n/**\n * The policies a statement drops, keyed as `createdPolicies` keys them.\n *\n * Needed to tell a policy being *removed* from one being *replaced*: the RLS\n * check renders a modified policy as `DROP POLICY` + `CREATE POLICY` for the\n * same name, and that is not a loss of access control (issue #88).\n */\nexport function droppedPolicies(sql: string): string[] {\n const tree = parseStatements(sql)\n if (tree) {\n return tree.filter(s => s.kind === 'DropStmt' && s.node.removeType === 'OBJECT_POLICY')\n .flatMap(({ node }) => (node.objects as Array<Record<string, any>>)\n .map(o => (o.List?.items ?? []).map((i: Record<string, any>) => i.String?.sval as string))\n .map((parts: string[]) => objectKey(parts.at(-3), parts.at(-2), parts.at(-1))))\n }\n const out: string[] = []\n const re = new RegExp(String.raw`DROP\\s+POLICY\\s+(?:IF\\s+EXISTS\\s+)?(${NAME_PART})\\s+ON\\s+(${IDENT})`, 'gi')\n for (const m of sqlSkeleton(sql).matchAll(re)) {\n out.push(`${schemaQualified(m[2])}.${bareName(m[1])}`)\n }\n return out\n}\n\n/**\n * Policies this statement drops without putting back.\n *\n * Dropping a policy is not recoverable from the schema the way dropping a view\n * or a function is, and a dropped RESTRICTIVE policy *grants* access rather\n * than removing it — so it belongs behind the same gate as losing rows.\n */\nexport function policiesRemoved(sql: string): string[] {\n const recreated = new Set(createdPolicies(sql))\n return droppedPolicies(sql).filter(key => !recreated.has(key))\n}\n\nexport function createsOnlyPolicies(sql: string): boolean {\n if (createdPolicies(sql).length === 0) return false\n const withoutPolicies = sqlSkeleton(sql)\n .replace(/CREATE\\s+POLICY[\\s\\S]*?(?=;|$)/gi, '')\n .replace(/DROP\\s+POLICY[\\s\\S]*?(?=;|$)/gi, '')\n return !/[A-Za-z]/.test(withoutPolicies)\n}\n\n/**\n * The triggers a statement creates, keyed the way Postgres identifies one.\n *\n * Same collision as policies, one layer along. The schema check's SQL creates\n * webhook triggers — they are ordinary triggers as far as dbdiff is concerned —\n * and since issue #77 the webhooks check emits the server's own\n * `pg_get_triggerdef()` for the same trigger. Applied together the second fails\n * with `trigger \"x\" for relation \"y\" already exists`, and the transactional\n * apply discards every other fix with it: the reported symptom was a full\n * `diff --apply` rolling back six correct schema fixes.\n *\n * A trigger name is unique per table, not per schema, so the table belongs in\n * the key — which is also why the webhooks check now keys its own entries that\n * way. The schema qualifier is dropped for the same reason `referencedTables`\n * drops it: the two layers spell the same table differently.\n */\nexport function createdTriggers(sql: string): string[] {\n const tree = parseStatements(sql)\n if (tree) {\n return tree.filter(s => s.kind === 'CreateTrigStmt')\n .map(({ node }) => `${(node.relation?.relname ?? '').toLowerCase()}.${String(node.trigname).toLowerCase()}`)\n }\n const out: string[] = []\n const re = new RegExp(String.raw`CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER\\s+(${NAME_PART})[\\s\\S]*?\\sON\\s+(${IDENT})`, 'gi')\n for (const m of sqlSkeleton(sql).matchAll(re)) {\n out.push(`${bareName(m[2])}.${bareName(m[1])}`)\n }\n return out\n}\n\n/**\n * True when creating triggers is all this statement does.\n *\n * The same guard as `createsOnlyPolicies`: the schema check bundles a trigger\n * with the table and function it needs, and dropping that as a duplicate would\n * lose the DDL around it. A leading DROP TRIGGER is expected — the webhooks\n * check emits one before recreating a modified webhook — so it does not count\n * as doing something else.\n */\nexport function createsOnlyTriggers(sql: string): boolean {\n if (createdTriggers(sql).length === 0) return false\n const withoutTriggers = sqlSkeleton(sql)\n .replace(/CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER[\\s\\S]*?(?=;|$)/gi, '')\n .replace(/DROP\\s+TRIGGER[\\s\\S]*?(?=;|$)/gi, '')\n return !/[A-Za-z]/.test(withoutTriggers)\n}\n\nexport function referencedTables(sql: string): string[] {\n const names = new Set<string>()\n for (const pattern of [BODY_TABLE_REF, ON_TABLE_REF, TARGET_TABLE_REF]) {\n for (const match of sql.matchAll(pattern)) {\n const name = bareName(match[1])\n if (!NOT_A_TABLE.has(name)) names.add(name)\n }\n }\n return [...names]\n}\n\n// ─── Ordering ────────────────────────────────────────────────────────────────\n\n/** One statement, with everything the sort needs precomputed. */\ninterface Node {\n /** The fix's position in the order its producer wrote it, when that order is to be kept. */\n rank?: number\n phase: number\n /** Indices that must execute before this one. */\n after: Set<number>\n}\n\n/**\n * Match `name` used as a whole identifier, quoted or not, schema-qualified or\n * not. Built once per name rather than per comparison — a large fix set is\n * thousands of pairings.\n */\n/** Matches `name` as a whole identifier, quoted or not. */\nexport function identifierMatcher(name: string): RegExp {\n return new RegExp(String.raw`(?<![\\w$])\"?${escapeRegex(name)}\"?(?![\\w$])`, 'i')\n}\n\n/**\n * Build the \"must run after\" edges between statements.\n *\n * One rule covers every object kind: if a statement creates something named\n * `n`, any other statement mentioning `n` is assumed to need it. That catches\n * the reported trigger-before-function case, and equally a view over a new\n * table, an index on one, or a column default that calls a new function.\n */\nfunction linkDependencies(nodes: Node[], texts: string[], provides: string[][]): void {\n const droppers = texts.map((sql, i) => isDropOnly(sql, provides[i]))\n // What a statement *uses* is what it mentions outside its DROPs. A column\n // type change grouped with the dependants it drops and recreates mentions\n // the policy it drops, and was made to wait for the fix that creates that\n // policy — which then ran first, against the column's old type.\n const uses = texts.map(withoutDropStatements)\n\n for (let provider = 0; provider < nodes.length; provider++) {\n for (const name of provides[provider]) {\n const matcher = identifierMatcher(name)\n for (let consumer = 0; consumer < nodes.length; consumer++) {\n if (consumer === provider || droppers[consumer]) continue\n // A statement that creates `name` itself does not need another's:\n // two column changes under one view each recreate it, and linking\n // them both ways made a cycle, which the fallback resolves by\n // report order rather than by phase.\n if (provides[consumer].includes(name)) continue\n if (matcher.test(uses[consumer])) nodes[consumer].after.add(provider)\n }\n }\n }\n}\n\n/** A statement batch with its DROP statements taken out. */\nfunction withoutDropStatements(sql: string): string {\n if (!/\\bDROP\\b/i.test(sql)) return sql\n return splitSqlStatements(sql).filter(s => !/^\\s*DROP\\b/i.test(sqlSkeleton(s))).join('\\n')\n}\n\n/**\n * Pick the next statement to run: the one whose dependencies are all satisfied,\n * earliest by phase, then by the order the diff reported it.\n *\n * Falls back to the lowest remaining index when nothing is ready, which happens\n * only if the edges form a cycle — mutually referencing tables, or a name that\n * reads like two different objects. Emitting those in their original order is\n * no worse than the behaviour this replaces.\n */\nfunction nextReady(remaining: number[], nodes: Node[], done: Set<number>): number {\n const ready = remaining.filter(i => isSatisfied(nodes[i].after, done))\n const first = (from: number[], key: (n: Node) => number) =>\n from.reduce<number | undefined>((best, i) => best === undefined || key(nodes[i]) < key(nodes[best]) ? i : best, undefined)\n\n const head = first(ready.filter(i => nodes[i].rank !== undefined), n => n.rank as number)\n const free = first(ready.filter(i => nodes[i].rank === undefined), n => n.phase)\n if (head === undefined || free === undefined) return head ?? free ?? remaining[0]\n\n // DBDiff's fixes are one sequence, in DBDiff's order. Another check's fix\n // goes ahead of it only when it belongs before everything the sequence\n // still has to do — the earliest phase left in it, not the phase of the\n // fix at its head. Compared with the head alone, an RLS policy jumped ahead\n // of a column change it needed whenever a late-phase fix happened to come\n // first: \"operator does not exist: text = uuid\".\n //\n // What it has left to make, that is: a drop provides nothing another fix\n // could need. Counted, a DROP INDEX DBDiff sequences after its tables held\n // CREATE EXTENSION back until after the table whose exclusion constraint\n // needs it.\n const sequence = Math.min(...remaining\n .filter(i => nodes[i].rank !== undefined && !DROP_PHASES.has(nodes[i].phase))\n .map(i => nodes[i].phase))\n return nodes[free].phase < sequence ? free : head\n}\n/** Have all of `after` already run? Iterated rather than spread — this is the\n * inner loop of the sort, and a large fix set runs it thousands of times. */\nfunction isSatisfied(after: Set<number>, done: Set<number>): boolean {\n for (const dep of after) {\n if (!done.has(dep)) return false\n }\n return true\n}\n\n/**\n * Sort a fix set into an order Postgres can execute in a single pass.\n *\n * Stable within a phase: statements that neither depend on one another nor\n * differ in kind come out in the order the diff reported them, so the plan\n * stays recognisable against `--detail`.\n */\nexport function orderStatements<T>(\n items: T[],\n sqlOf: (item: T) => string,\n rankOf: (item: T) => number | undefined = () => undefined,\n): T[] {\n if (items.length < 2) return [...items]\n\n const texts = items.map(sqlOf)\n const provides = texts.map(providedNames)\n const nodes: Node[] = texts.map((sql, i) => ({ phase: statementPhase(sql), rank: rankOf(items[i]), after: new Set<number>() }))\n\n linkDependencies(nodes, texts, provides)\n\n const done = new Set<number>()\n let remaining = texts.map((_, i) => i)\n const ordered: T[] = []\n\n while (remaining.length > 0) {\n const next = nextReady(remaining, nodes, done)\n ordered.push(items[next])\n done.add(next)\n remaining = remaining.filter(i => i !== next)\n }\n\n return ordered\n}\n\n// ─── Statement subject ───────────────────────────────────────────────────────\n\n/** A schema-qualified object name, unquoted. `schema` is null when unqualified. */\nexport interface QualifiedName {\n schema: string | null\n name: string\n}\n\nfunction splitQualified(identifier: string): QualifiedName {\n const parts = identifier.match(/\"[^\"]+\"|[\\w$]+/g) ?? []\n const clean = parts.map(p => p.replace(/^\"|\"$/g, ''))\n if (clean.length >= 2) return { schema: clean[clean.length - 2], name: clean[clean.length - 1] }\n return { schema: null, name: clean[0] ?? '' }\n}\n\n/** A possibly three-part name (`schema.table.column`), as COMMENT ON COLUMN takes. */\nconst IDENT3 = String.raw`(?:\"[^\"]+\"|[\\w$]+)(?:\\s*\\.\\s*(?:\"[^\"]+\"|[\\w$]+)){0,2}`\n\nconst OBJECT_KIND = String.raw`(?:TABLE|VIEW|MATERIALIZED\\s+VIEW|FOREIGN\\s+TABLE|FUNCTION|PROCEDURE|ROUTINE|AGGREGATE|SEQUENCE|TYPE|DOMAIN|INDEX|SCHEMA)`\n\n/**\n * Subject patterns, most specific first, each with what its capture names:\n * an object, a schema, or a `schema.table.column`. For a trigger, policy,\n * rule or index the object is the table it belongs to rather than its own\n * name, since that is what owns it.\n */\nconst SUBJECT_RULES: Array<[RegExp, 'object' | 'schema' | 'column']> = [\n // CREATE/DROP/ALTER TRIGGER|POLICY name ... ON <table>\n [new RegExp(String.raw`^\\s*(?:CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?|DROP\\s+|ALTER\\s+)(?:TRIGGER|POLICY)\\s+(?:IF\\s+EXISTS\\s+)?(?:\"[^\"]+\"|[\\w$]+)[\\s\\S]*?\\bON\\s+(?:ONLY\\s+)?(${IDENT})`, 'i'), 'object'],\n // CREATE RULE name AS ON <event> TO <table>\n [new RegExp(String.raw`^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?RULE\\s+(?:\"[^\"]+\"|[\\w$]+)\\s+AS\\s+ON\\s+\\w+\\s+TO\\s+(${IDENT})`, 'i'), 'object'],\n // CREATE [UNIQUE] INDEX [CONCURRENTLY] [IF NOT EXISTS] [name] ON [ONLY] <table>\n [new RegExp(String.raw`^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\b[\\s\\S]*?\\bON\\s+(?:ONLY\\s+)?(${IDENT})`, 'i'), 'object'],\n // COMMENT ON TRIGGER|POLICY|RULE|CONSTRAINT name ON <table>\n [new RegExp(String.raw`^\\s*COMMENT\\s+ON\\s+(?:TRIGGER|POLICY|RULE|CONSTRAINT)\\s+(?:\"[^\"]+\"|[\\w$]+)\\s+ON\\s+(?:DOMAIN\\s+)?(${IDENT})`, 'i'), 'object'],\n [new RegExp(String.raw`^\\s*COMMENT\\s+ON\\s+COLUMN\\s+(${IDENT3})`, 'i'), 'column'],\n [new RegExp(String.raw`^\\s*COMMENT\\s+ON\\s+SCHEMA\\s+((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n [new RegExp(String.raw`^\\s*COMMENT\\s+ON\\s+${OBJECT_KIND}\\s+(${IDENT})`, 'i'), 'object'],\n // GRANT/REVOKE ... ON SCHEMA <schema> | ON ALL <kind> IN SCHEMA <schema> | ON [kind] <name>\n [new RegExp(String.raw`^\\s*(?:GRANT|REVOKE)\\b[\\s\\S]*?\\bON\\s+SCHEMA\\s+((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n [new RegExp(String.raw`^\\s*(?:GRANT|REVOKE)\\b[\\s\\S]*?\\bON\\s+ALL\\s+\\w+\\s+IN\\s+SCHEMA\\s+((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n [new RegExp(String.raw`^\\s*(?:GRANT|REVOKE)\\b[\\s\\S]*?\\bON\\s+(?:${OBJECT_KIND}\\s+)?(${IDENT})`, 'i'), 'object'],\n // ALTER DEFAULT PRIVILEGES ... IN SCHEMA <schema>\n [new RegExp(String.raw`^\\s*ALTER\\s+DEFAULT\\s+PRIVILEGES\\b[\\s\\S]*?\\bIN\\s+SCHEMA\\s+((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n // CREATE|ALTER|DROP SCHEMA <schema>\n [new RegExp(String.raw`^\\s*(?:CREATE|ALTER|DROP)\\s+SCHEMA\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n // CREATE [OR REPLACE] [modifiers] <kind> [IF NOT EXISTS] <name>\n [new RegExp(String.raw`^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:(?:TEMP|TEMPORARY|UNLOGGED|RECURSIVE)\\s+)*${OBJECT_KIND}\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(${IDENT})`, 'i'), 'object'],\n // ALTER|DROP <kind> [IF EXISTS] [ONLY] <name>\n [new RegExp(String.raw`^\\s*(?:ALTER|DROP)\\s+${OBJECT_KIND}\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${IDENT})`, 'i'), 'object'],\n]\n\n/**\n * The object a statement acts on — its *subject*, not every name it mentions.\n *\n * `CREATE TRIGGER t ... ON public.orders EXECUTE FUNCTION\n * supabase_functions.http_request(...)` acts on `public.orders`: it mentions a\n * platform schema, but what it creates belongs to the project. Deciding\n * ownership by mention skipped every Database Webhook on restore, and every\n * view reading `cron` or `vault`. The subject is what decides who owns a\n * statement's result.\n *\n * For `COMMENT ON COLUMN s.t.c` the subject is the table `s.t`; for a\n * schema-level statement (`CREATE SCHEMA x`, `GRANT ... ON SCHEMA x`,\n * `... IN SCHEMA x`) it is `{ schema: x, name: x }`. Undefined when the\n * statement's shape is not one of these.\n */\nexport function statementSubject(sql: string): QualifiedName | undefined {\n const skeleton = sqlSkeleton(sql)\n\n for (const [rule, captures] of SUBJECT_RULES) {\n const match = rule.exec(skeleton)\n if (!match) continue\n\n const parts = (match[1].match(/\"[^\"]+\"|[\\w$]+/g) ?? []).map(p => p.replace(/^\"|\"$/g, ''))\n if (captures === 'schema') return { schema: parts[0], name: parts[0] }\n if (captures === 'column') {\n return parts.length >= 3\n ? { schema: parts[parts.length - 3], name: parts[parts.length - 2] }\n : { schema: null, name: parts[0] ?? '' }\n }\n return splitQualified(match[1])\n }\n\n return undefined\n}\n\n/**\n * The policies (`schema.table.policy`) a fix consists of, when it is nothing but\n * CREATE and DROP POLICY statements; otherwise null.\n */\nexport function policyOnlyKeys(sql: string | undefined): string[] | null {\n if (!sql) return null\n const statements = splitSqlStatements(sql).filter(s => sqlSkeleton(s).trim() !== '')\n if (statements.length === 0) return null\n if (!statements.every(s => /^\\s*(?:CREATE|DROP)\\s+POLICY\\b/i.test(sqlSkeleton(s)))) return null\n return [...new Set([...createdPolicies(sql), ...droppedPolicies(sql)])]\n}\n\n/** The roles one parsed statement grants to or scopes a policy to. */\nfunction rolesOf({ kind, node }: Statement): string[] {\n const specs: Array<Record<string, any>> =\n (kind === 'GrantStmt' && node.is_grant) ? node.grantees ?? []\n : (kind === 'GrantRoleStmt' && node.is_grant) ? node.grantee_roles ?? []\n : (kind === 'CreatePolicyStmt' || kind === 'AlterPolicyStmt') ? node.roles ?? []\n : []\n return specs\n .map(spec => spec.RoleSpec)\n // PUBLIC, CURRENT_USER and the like are not role names.\n .filter(role => role?.roletype === 'ROLESPEC_CSTRING' && typeof role.rolename === 'string')\n .map(role => role.rolename as string)\n .filter(name => !name.startsWith('pg_'))\n}\n\n/** Role specifications that are keywords rather than roles, so never created. */\nconst ROLE_KEYWORDS = new Set(['public', 'current_user', 'current_role', 'session_user'])\n\n/**\n * Every role a statement grants to or scopes a policy to.\n *\n * A restore creates them first where the target lacks them, and `--prove`\n * declines to run when the server lacks them, since creating a role is never\n * confined to a throwaway database.\n *\n * A snapshot's `roles.sql` grants to Supabase's Data API roles — `anon`,\n * `authenticated`, `service_role` — and the usual restore target is plain\n * PostgreSQL, where none of them exist. A policy names roles too, and the\n * schema dump and the RLS layer both replay policies long before the roles\n * layer's grants: `CREATE POLICY … TO service_role` into plain PostgreSQL\n * failed with `role \"service_role\" does not exist` and, in one transaction,\n * rolled the whole restore back. Every role in the list is returned, not just\n * the first, since a policy for `authenticated, service_role` needs both.\n *\n * Read off the skeleton, so a role named inside a function body or a string\n * literal is not mistaken for one. `PUBLIC` and `CURRENT_USER` are keywords,\n * not roles, and a `pg_` role is built in: none of them can be created.\n * `ALTER POLICY … RENAME TO` names a policy, not a role.\n */\nexport function rolesNamedBy(sql: string): string[] {\n // Read from the parse tree: the regex below took TO inside a quoted policy\n // name for the role list — \"Allow users to read items\" named the roles\n // read, items, on and for, and a restore went looking for them — and read\n // only the first statement of a fix.\n const statements = parseStatements(sql)\n if (statements) return [...new Set(statements.flatMap(rolesOf))]\n\n const skeleton = sqlSkeleton(sql)\n const list =\n /^\\s*GRANT\\b[\\s\\S]*?\\bTO\\s+([\\s\\S]*?)(?=\\s+WITH\\b|\\s+GRANTED\\s+BY\\b|\\s*;|\\s*$)/i.exec(skeleton)\n ?? /^\\s*(?:CREATE|ALTER)\\s+POLICY\\b(?![\\s\\S]*\\bRENAME\\s+TO\\b)[\\s\\S]*?\\bTO\\s+([\\s\\S]*?)(?=\\s+USING\\b|\\s+WITH\\s+CHECK\\b|\\s*;|\\s*$)/i.exec(skeleton)\n if (!list) return []\n\n const roles = (list[1].match(/\"(?:[^\"]|\"\")+\"|[\\w$]+/g) ?? [])\n // Unquoted, PostgreSQL folds the name to lower case.\n .map(r => r.startsWith('\"') ? r.slice(1, -1).replace(/\"\"/g, '\"') : r.toLowerCase())\n .filter(r => !ROLE_KEYWORDS.has(r.toLowerCase()) && !r.startsWith('pg_'))\n return [...new Set(roles)]\n}\n","/**\n * dbdiff's `--units` output: each change's statements between\n *\n * -- dbdiff:unit <Kind> <object>\n * ...\n * -- dbdiff:end\n *\n * Some changes are several statements that only work together and in order —\n * an enum label swap, a column type change with the views reading it stood\n * aside, a generated column re-added, a serial column turned into an identity.\n * Split into separate findings they were reordered, half-applied, or held back\n * as destructive for a DROP the same change undoes a statement later. The\n * markers say where each change starts and ends, and which object it is, so\n * nothing here has to guess that from the SQL:\n *\n * - a unit is one finding, whatever it holds;\n * - its DOWN is the unit of the same kind and object in the DOWN section,\n * not whatever happens to sit at the same position there.\n */\n\n/** One change, as dbdiff marked it. */\nexport interface DbDiffUnit {\n /** dbdiff's diff class: `AlterTableChangeColumn`, `AlterEnum`, `CreateView`, … */\n kind: string\n /** `table`, `table.column`, `table.name` or `name` — empty when dbdiff gave none. */\n object: string\n /** The unit's SQL, statements in order, without the marker lines. */\n sql: string\n}\n\nconst BEGIN = /^-- dbdiff:unit (\\S+)(?: (.*))?$/\nconst END = '-- dbdiff:end'\n\n/**\n * The units of one section (UP or DOWN), or undefined when it carries no\n * markers — output from a dbdiff without `--units`.\n *\n * Text outside any unit is ignored: dbdiff writes nothing there but blank\n * lines and, without `--nocomments`, its own header.\n */\nexport function parseUnits(section: string): DbDiffUnit[] | undefined {\n if (!section.includes('-- dbdiff:unit ')) return undefined\n\n const units: DbDiffUnit[] = []\n let open: { kind: string; object: string; lines: string[] } | undefined\n\n for (const line of section.split('\\n')) {\n const begin = BEGIN.exec(line.trimEnd())\n if (begin) {\n open = { kind: begin[1], object: (begin[2] ?? '').trim(), lines: [] }\n } else if (line.trimEnd() === END && open) {\n units.push({ kind: open.kind, object: open.object, sql: open.lines.join('\\n').trim() })\n open = undefined\n } else if (open) {\n open.lines.push(line)\n }\n }\n\n return units.filter(u => u.sql !== '')\n}\n\n/** What identifies a change across the two sections. */\nexport function unitKey(unit: DbDiffUnit): string {\n return `${unit.kind} ${unit.object}`\n}\n\n/**\n * Each UP unit with the DOWN unit for the same change, if there is one.\n *\n * By kind and object, in order: two units with the same key (two overloads of\n * one routine, say) pair first with first. A change can have nothing to do in\n * one direction — a column's storage on a column the DOWN drops anyway — so\n * an UP unit may have no DOWN.\n */\nexport function pairUnits(\n up: DbDiffUnit[],\n down: DbDiffUnit[],\n): Array<{ up: DbDiffUnit; down: DbDiffUnit | undefined }> {\n const unclaimed = new Map<string, DbDiffUnit[]>()\n for (const unit of down) {\n const key = unitKey(unit)\n unclaimed.set(key, [...(unclaimed.get(key) ?? []), unit])\n }\n return up.map(unit => ({ up: unit, down: unclaimed.get(unitKey(unit))?.shift() }))\n}\n\n/** The kinds dbdiff renders as dropping and recreating one object. */\nexport const REPLACING_KINDS: Record<string, 'routine' | 'type' | 'sequence' | 'policy' | 'trigger' | 'view' | undefined> = {\n AlterRoutine: 'routine',\n AlterEnum: 'type',\n AlterCompositeType: 'type',\n AlterDomain: 'type',\n AlterPolicy: 'policy',\n AlterTrigger: 'trigger',\n AlterView: 'view',\n AlterMatView: 'view',\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAC9B,SAAS,UAAU,QAAQ,c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rB,SAAS,qBAAqB,KAAa,MAAsB;AACtE,QAAM,QAAQ,KAAK,KAAK,GAAG;AAC3B,MAAI,CAAC,MAAO,QAAO;AAEnB,MAAI,OAAO,IAAI,MAAM,MAAM,QAAQ,MAAM,CAAC,EAAE,MAAM;AAClD,QAAM,QAAkB,CAAC;AAEzB,WAAS,QAAQ,GAAG,QAAQ,GAAG,SAAS;AAEtC,UAAM,QAAQ,iCAAiC,KAAK,IAAI;AACxD,QAAI,CAAC,MAAO;AACZ,UAAM,KAAK,MAAM,CAAC,MAAM,SAAY,MAAM,CAAC,EAAE,QAAQ,OAAO,GAAG,IAAI,MAAM,CAAC,CAAC;AAC3E,WAAO,KAAK,MAAM,MAAM,CAAC,EAAE,MAAM;AAEjC,UAAM,MAAM,YAAY,KAAK,IAAI;AACjC,QAAI,CAAC,IAAK;AACV,WAAO,KAAK,MAAM,IAAI,CAAC,EAAE,MAAM;AAAA,EACjC;AAEA,SAAO,MAAM,SAAS,IAAI,MAAM,KAAK,GAAG,IAAI;AAC9C;AAaO,SAAS,mBAAmB,KAAqB;AACtD,QAAM,OAAO,IAAI,QAAQ,GAAG;AAC5B,MAAI,SAAS,GAAI,QAAO;AAExB,MAAI,QAAQ;AACZ,WAAS,IAAI,MAAM,IAAI,IAAI,QAAQ,KAAK;AACtC,QAAI,IAAI,CAAC,MAAM,IAAK;AAAA,aACX,IAAI,CAAC,MAAM,OAAO,EAAE,UAAU,EAAG,QAAO,IAAI,MAAM,MAAM,IAAI,CAAC;AAAA,EACxE;AACA,SAAO;AACT;","names":["names","require"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/prove.ts","../src/state-diff.ts"],"sourcesContent":["/**\n * Convergence proof.\n *\n * A migration is only trustworthy if applying it actually produces the target\n * schema. Every silent-wrong-answer bug found so far shared one shape: the\n * generated SQL executed without error and left the database in a state that\n * was *not* the source — a duplicate primary key aborted loudly, but a\n * flattened partition, a dropped enum type name and an unpropagated index all\n * ran cleanly and lied.\n *\n * A text comparison cannot catch that class, and neither can a test suite that\n * only exercises the patterns its authors thought of. The only check that\n * generalises is to run the migration and look at what came out.\n *\n * So: copy the target's schema into a throwaway database, apply the migration\n * there, and diff the result against the source. Zero drift means the migration\n * does what it claims. Anything else is reported as residual drift, naming the\n * objects the migration failed to reproduce.\n *\n * The real target is never touched. The clone lives on the target's own server\n * (so no cross-host credentials are needed) and is dropped in a finally block\n * even when the proof throws.\n */\nimport { randomBytes } from 'node:crypto'\nimport { execFile, spawn } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { fingerprintSql, stateSql, type SchemaState } from '@akal/pg-conformance'\nimport { pgQuery, type QueryFn } from './db'\nimport { runLikeApply, type PlannedSql } from './promote'\nimport { diffState } from './state-diff'\nimport { resolvePgDumpPath, getServerMajorVersion, describeMissingPgDump } from './pg-tools'\nimport { rolesNamedBy, sqlSkeleton } from './sql-deps'\nimport { splitSqlStatements, isCommentOnly } from './utils/sql-split.js'\nimport { quoteName } from './utils/sql.js'\nimport { globToRegExp } from './utils/strings.js'\nimport { join, dirname } from 'node:path'\n\nconst exec = promisify(execFile)\n\n/**\n * Extensions on the target, and the schema each is installed into.\n *\n * The clone holds only the schemas being proved, so anything those schemas\n * reference from outside has to be put there first — and in practice that means\n * extensions: a Supabase column default calling `extensions.uuid_generate_v4()`\n * cannot be created without the extension that owns the function.\n *\n * Extensions living in a system schema are excluded, by *schema* rather than\n * by name. Filtering `plpgsql` by name left `pg_cron` — which Supabase installs\n * into `pg_catalog` — and the clone preparation then ran\n * `CREATE SCHEMA IF NOT EXISTS \"pg_catalog\"`. PostgreSQL rejects a name\n * beginning with `pg_` before it evaluates `IF NOT EXISTS`:\n *\n * error: unacceptable schema name \"pg_catalog\" (42939)\n *\n * so `--prove` aborted on every project with Cron enabled (issue #94). There is\n * nothing to create for these schemas in any case: they exist in every\n * database, and so do the extensions in them.\n */\nconst TARGET_EXTENSIONS_SQL = `\n SELECT e.extname AS name, n.nspname AS schema\n FROM pg_extension e\n JOIN pg_namespace n ON n.oid = e.extnamespace\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_%'\n ORDER BY e.extname\n`\n\nexport interface ProofResult {\n /** True when the clone matched the source after applying. */\n converged: boolean\n /** Objects still differing after the migration — the migration's blind spots. */\n residual: string[]\n /** Name of the throwaway database, for error messages. */\n cloneName: string\n /** Set when the proof could not run at all (missing pg_dump, no CREATEDB). */\n skipped?: string\n /**\n * Fixes the replay left out because the server can't hold them — an\n * extension it does not ship, and what needs it — as the apply will. Their\n * absence is expected, not a failure to converge.\n */\n notApplied?: Array<{ issueId: string; sql: string; reason: string }>\n /**\n * For a run limited to some checks: differences the target already had,\n * still there, and of a kind none of those checks compares — see\n * outsideTheRun(). They do not count against convergence.\n */\n outOfScope?: string[]\n}\n\n/** Replace the database name in a libpq URL, keeping everything else. */\nfunction withDatabase(dbUrl: string, database: string): string {\n const url = new URL(dbUrl)\n url.pathname = `/${database}`\n return url.toString()\n}\n\n\n/**\n * The structural fingerprint comes from @akal/pg-conformance.\n *\n * It used to be defined here, and separately in the e2e harness, and again in\n * dbdiff's conformance runner. They drifted, and this copy was the one that\n * compared views, functions and triggers by name alone — so it called two\n * schemas converged when a view's predicate had been inverted, a function's\n * body replaced, or a trigger moved from AFTER INSERT to BEFORE UPDATE.\n *\n * A shared definition of \"same schema\" is the whole point of the proof, so it\n * lives in one place that both projects depend on.\n */\n\nasync function fingerprint(dbUrl: string, schemas: string[]): Promise<string> {\n const rows = await pgQuery(dbUrl, fingerprintSql(schemas)) as unknown as\n Array<{ fingerprint: string | null }>\n\n // An empty fingerprint would make every comparison succeed, so a schema that\n // produced nothing is treated as a fault rather than as \"no differences\".\n // Reading the wrong column name would fail exactly this way, silently.\n const value = rows[0]?.fingerprint\n if (value === undefined) {\n throw new Error('fingerprint query returned no \"fingerprint\" column')\n }\n return value ?? ''\n}\n\n/**\n * Say what differs, in terms a reader can act on.\n *\n * The fingerprint has already decided that something does. This turns the two\n * schema-state documents into named findings — \"column public.orders.total:\n * storage extended → plain\" — rather than two near-identical lines of catalog\n * shorthand with one field moved somewhere in the middle.\n *\n * Falls back to the raw fingerprint lines if the structured diff comes back\n * empty. That should not happen, but \"the schemas differ and I cannot tell you\n * how\" is a far worse answer than an ugly one.\n */\nasync function describeDifference(\n sourceUrl: string, cloneUrl: string, schemas: string[], want: string, got: string,\n): Promise<string[]> {\n try {\n const [before, after] = await Promise.all([\n schemaState(sourceUrl, schemas),\n schemaState(cloneUrl, schemas),\n ])\n const findings = diffState(before, after)\n if (findings.length > 0) return findings\n } catch {\n // fall through to the fingerprint lines\n }\n\n const wanted = new Set(want.split('\\n').filter(Boolean))\n const actual = new Set(got.split('\\n').filter(Boolean))\n return [\n ...[...wanted].filter(l => !actual.has(l)).map(l => `missing: ${l}`),\n ...[...actual].filter(l => !wanted.has(l)).map(l => `unexpected: ${l}`),\n ]\n}\n\n/** The schema-state document for one database. */\nasync function schemaState(dbUrl: string, schemas: string[]): Promise<SchemaState> {\n const rows = await pgQuery(dbUrl, stateSql(schemas)) as unknown as Array<{ state: string | null }>\n const value = rows[0]?.state\n if (!value) throw new Error('state query returned no \"state\" column')\n return JSON.parse(value) as SchemaState\n}\n\n/**\n * The schemas a schema diff compares between two databases: every schema\n * either has, but the system's own, an extension's own, and `ignore`\n * (globs: `*`, `?`), as `dbdiff --ignore-schemas` chooses them. What a\n * proof must cover, and nothing more.\n */\nexport async function comparedSchemas(\n sourceUrl: string, targetUrl: string, ignore: readonly string[], query: QueryFn = pgQuery,\n): Promise<string[]> {\n const sql = `SELECT n.nspname AS name FROM pg_namespace n\n WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_toast%' AND n.nspname NOT LIKE 'pg\\\\_temp\\\\_%'\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_namespace'::regclass\n AND d.objid = n.oid AND d.deptype = 'e')`\n const ignored = ignore.map(globToRegExp)\n const names = (await Promise.all([sourceUrl, targetUrl].map(url => query(url, sql))))\n .flat().map(r => String((r as { name: unknown }).name))\n return [...new Set(names)].filter(n => !ignored.some(g => g.test(n))).sort()\n}\n\n/**\n * Prove that `migrationSql` turns the target into the source.\n *\n * Returns `converged: false` with the differing objects rather than throwing,\n * so the caller can decide whether that blocks an apply or merely warns.\n */\nexport async function proveConvergence(opts: {\n sourceUrl: string\n targetUrl: string\n migrationSql: string\n /**\n * The fixes behind migrationSql. Given, they are replayed exactly as the\n * apply will run them (see runLikeApply), so a fix the server can't hold is\n * left out rather than stopping the proof. Without them the SQL runs as one\n * script and any error ends the proof.\n */\n fixes?: PlannedSql[]\n schemas?: string[]\n /**\n * The checks the run compares. Without the schema check the migration only\n * sets out to fix part of the difference, and must not be refused for the\n * rest — see outsideTheRun(). Omitted, the whole schema must converge.\n */\n checks?: readonly string[]\n}): Promise<ProofResult> {\n const schemas = opts.schemas ?? ['public']\n const suffix = randomBytes(4).toString('hex')\n const cloneName = `supaforge_prove_${suffix}`\n const adminUrl = withDatabase(opts.targetUrl, 'postgres')\n const cloneUrl = withDatabase(opts.targetUrl, cloneName)\n\n let pgDump: string\n let psql: string\n let serverMajor: number\n let clientMajor: number\n let sourceMajor: number\n try {\n serverMajor = await getServerMajorVersion(opts.targetUrl)\n sourceMajor = await getServerMajorVersion(opts.sourceUrl).catch(() => serverMajor)\n // The proof dumps both servers: the target into the clone, and the source\n // into a copy compared like with like. A pg_dump new enough for the target\n // alone failed on a newer source, and the proof fell back to comparing a\n // 17 source's rendering with a 15 clone's, refusing correct migrations.\n const resolved = await resolvePgDumpPath(Math.max(serverMajor, sourceMajor))\n ?? await resolvePgDumpPath(serverMajor)\n if (!resolved) {\n return { converged: false, residual: [], cloneName, skipped: await describeMissingPgDump(serverMajor) }\n }\n pgDump = resolved.path\n clientMajor = resolved.major\n psql = psqlBeside(pgDump)\n } catch (err) {\n return {\n converged: false, residual: [], cloneName,\n skipped: `could not resolve pg_dump: ${(err as Error).message}`,\n }\n }\n\n // A role is the server's, not the database's: creating one for the proof\n // would create it for real, and the apply's own CREATE ROLE then failed\n // with \"already exists\". So a migration that needs a role the server does\n // not have yet cannot be proved here — say so rather than create it.\n const absent = await absentRoles(opts.targetUrl, opts.migrationSql)\n if (absent.length > 0) {\n return {\n converged: false, residual: [], cloneName,\n skipped: `the migration needs role(s) this server does not have yet (${absent.join(', ')}), `\n + 'and creating a role is server-wide, so it cannot be done in a throwaway database',\n }\n }\n\n let created = false\n let sourceCopyCreated = false\n let roundTripName: string | undefined\n try {\n try {\n await pgQuery(adminUrl, `CREATE DATABASE ${quoteName(cloneName)}`)\n created = true\n } catch (err) {\n // Typically insufficient privilege. Not being able to prove is not the\n // same as failing to converge, so say which it is.\n return {\n converged: false, residual: [], cloneName,\n skipped: `could not create a throwaway database: ${(err as Error).message}`,\n }\n }\n\n const tools = { pgDump, psql, clientMajor, serverMajor }\n await copyStructure(opts.targetUrl, cloneUrl, schemas, tools, opts.sourceUrl)\n const scoped = opts.checks !== undefined && !opts.checks.includes('schema')\n const before = scoped ? await schemaState(cloneUrl, schemas) : undefined\n\n // The migration under test.\n let notApplied: ProofResult['notApplied']\n if (opts.fixes) {\n const replayed = await runLikeApply(cloneUrl, opts.fixes)\n const unmet = replayed.errors.filter(e => / — not applied: /.test(e.error))\n const failed = replayed.errors.filter(e => !unmet.includes(e))\n if (failed.length > 0) {\n // A fix the apply itself would fail on: the migration can't reproduce\n // the source, and saying which fix and why is the useful answer.\n return {\n converged: false, cloneName,\n residual: failed.map(e => `fix ${e.issueId} failed: ${e.error}`),\n }\n }\n const byId = new Map(opts.fixes.map(f => [f.issueId, f.sql]))\n notApplied = unmet.map(e => ({ issueId: e.issueId, sql: byId.get(e.issueId) ?? '', reason: e.error }))\n } else {\n await runSql(psql, cloneUrl, opts.migrationSql)\n }\n const reported = (r: ProofResult): ProofResult => (notApplied?.length ? { ...r, notApplied } : r)\n\n const [want, got] = await Promise.all([\n fingerprint(opts.sourceUrl, schemas),\n fingerprint(cloneUrl, schemas),\n ])\n\n // The verdict stays with the fingerprint. It is the comparison already\n // trusted, and keeping it means the structured diff below can only change\n // how a difference is *described*, never whether one is detected.\n if (want === got) return reported({ converged: true, residual: [], cloneName })\n\n // The clone's objects have been through a dump and restore, or were\n // recreated from the SQL a rendering produced; the source's have not, and\n // PostgreSQL does not render every expression the same way twice —\n // `status IN ('draft', 'active')` on a varchar column comes back as a\n // different but equivalent ARRAY expression. So a correct migration\n // creating such a CHECK, index or policy was refused. Compared with the\n // source copied the same way, like is compared with like.\n roundTripName = `${cloneName}_src`\n const roundTripUrl = withDatabase(opts.targetUrl, roundTripName)\n const roundTrip = await copyOfSource(adminUrl, opts.sourceUrl, roundTripUrl, roundTripName, schemas, tools)\n if (roundTrip !== null) {\n sourceCopyCreated = true\n if (roundTrip.ok) {\n const wantRoundTripped = await fingerprint(roundTripUrl, schemas)\n if (wantRoundTripped === got) return reported({ converged: true, residual: [], cloneName })\n const residual = await describeDifference(roundTripUrl, cloneUrl, schemas, wantRoundTripped, got)\n return reported(withinScope(residual, before && diffState(await schemaState(roundTripUrl, schemas), before), opts.checks, cloneName))\n }\n }\n\n // Without a copy of the source on the target's server, two major versions\n // cannot be compared: each prints the same objects its own way. That is\n // not proven rather than not converged.\n if (sourceMajor !== serverMajor) {\n return {\n converged: false, residual: [], cloneName,\n skipped: `no pg_dump ${sourceMajor} or later to copy the PostgreSQL ${sourceMajor} source onto the `\n + `PostgreSQL ${serverMajor} target's server, which comparing across the two versions needs`,\n }\n }\n const residual = await describeDifference(opts.sourceUrl, cloneUrl, schemas, want, got)\n return reported(withinScope(residual, before && diffState(await schemaState(opts.sourceUrl, schemas), before), opts.checks, cloneName))\n } finally {\n if (sourceCopyCreated && roundTripName) {\n await dropDatabase(adminUrl, roundTripName)\n }\n if (created) {\n // Never leave a clone behind, even on failure. Terminating first because\n // a failed apply can leave a session attached.\n await dropDatabase(adminUrl, cloneName)\n }\n }\n}\n\ninterface PgTools { pgDump: string; psql: string; clientMajor: number; serverMajor: number }\n\n/**\n * Copy `fromUrl`'s structure in the given schemas into the empty database at\n * `intoUrl` — data is irrelevant to a schema proof and copying it would make\n * this unusable on anything but a toy database.\n *\n * Only the schemas being proved. Listing Supabase's schemas as exclusions\n * instead left the dump carrying everything that *references* them — a\n * `CREATE EXTENSION ... WITH SCHEMA extensions`, an event trigger calling\n * `extensions.set_graphql_placeholder()` — none of which could be replayed\n * into a clone that deliberately has no such schema. `--prove` therefore\n * failed on every real Supabase project, whatever the client version.\n */\nasync function copyStructure(\n fromUrl: string, intoUrl: string, schemas: string[], tools: PgTools, migratingFrom?: string,\n): Promise<void> {\n // Prepare the copy to receive the proved schemas, and nothing else.\n await prepareClone(intoUrl, fromUrl, schemas)\n\n // And the schemas they lean on. A Supabase table referencing auth.users, or\n // a policy calling auth.uid(), cannot be created without them — every real\n // project failed here with `schema \"auth\" does not exist`. Copied, not\n // compared: the fingerprint covers only the proved schemas.\n //\n // The schemas the source's objects lean on as well, when it is a migration\n // from that source being proved: a foreign key the migration adds onto\n // another schema's table needs that schema in the clone, though nothing in\n // the target uses it yet — the proof failed with `schema \"app\" does not\n // exist` where the apply itself would have worked. Only those the target\n // has: one it lacks would fail the real apply as well.\n const supporting = await supportingSchemas(fromUrl, schemas)\n const present = new Set((await pgQuery(fromUrl, 'SELECT nspname FROM pg_namespace') as Array<{ nspname: string }>).map(r => r.nspname))\n if (migratingFrom) {\n for (const name of await supportingSchemas(migratingFrom, schemas)) {\n if (present.has(name) && !supporting.includes(name)) supporting.push(name)\n }\n }\n\n // A proved schema only the source has is the migration's to create. Each\n // name quoted: pg_dump reads --schema as a pattern, folding `App Data` to\n // lower case, which matched nothing.\n const dumpArgs = [\n fromUrl, '--schema-only', '--no-owner', '--no-privileges',\n ...[...schemas.filter(s => present.has(s)), ...supporting].map(s => `--schema=${quoteName(s)}`),\n ]\n const { stdout: structure } = await exec(tools.pgDump, dumpArgs, {\n maxBuffer: 256 * 1024 * 1024, timeout: 300_000,\n })\n\n // pg_dump writes its preamble for its own version, so a newer client can\n // hand an older server a parameter that does not exist there (issue #72).\n // A supporting schema may already exist, created for an extension living in\n // it, so its CREATE SCHEMA has to tolerate that.\n const { sql: replayable } = dropUnsupportedSetStatements(\n tolerateExistingSchemas(structure), await knownParameters(intoUrl),\n )\n\n try {\n await runSql(tools.psql, intoUrl, replayable)\n } catch (err) {\n // Rethrown, not returned as `skipped`: a caller treats `skipped` as\n // \"could not check, carry on and apply\", and this is a case where we do\n // not know what the migration would do. Blocking the apply is the\n // behaviour that was already right (issue #72 confirmed nothing was\n // written and no clone was left behind) — only the message needed to say\n // what the cause actually is.\n throw new Error(explainStructureFailure((err as Error).message, tools.clientMajor, tools.serverMajor))\n }\n}\n\n/**\n * Schemas outside `schemas` holding something an object in them depends on —\n * a referenced table, a called function, a column's type — followed\n * transitively. Extension members are left out: prepareClone installs the\n * extensions themselves.\n */\nexport async function supportingSchemas(\n dbUrl: string, schemas: string[], queryFn: QueryFn = pgQuery,\n): Promise<string[]> {\n const known = new Set(schemas)\n const found: string[] = []\n for (let from = [...schemas]; from.length > 0;) {\n const rows = await queryFn(dbUrl, SUPPORTING_SCHEMAS_SQL(from)) as unknown as Array<{ schema: string }>\n from = rows.map(r => r.schema).filter(s => !known.has(s))\n for (const schema of from) {\n known.add(schema)\n found.push(schema)\n }\n }\n return found\n}\n\n/** The namespace of any object pg_depend can name, by catalog. */\nconst NAMESPACE_OF = (cls: string, oid: string) => `CASE ${cls}\n WHEN 'pg_class'::regclass THEN (SELECT relnamespace FROM pg_class WHERE oid = ${oid})\n WHEN 'pg_proc'::regclass THEN (SELECT pronamespace FROM pg_proc WHERE oid = ${oid})\n WHEN 'pg_type'::regclass THEN (SELECT typnamespace FROM pg_type WHERE oid = ${oid})\n WHEN 'pg_constraint'::regclass THEN (SELECT connamespace FROM pg_constraint WHERE oid = ${oid})\n WHEN 'pg_attrdef'::regclass THEN (SELECT x_c.relnamespace FROM pg_attrdef x_d JOIN pg_class x_c ON x_c.oid = x_d.adrelid WHERE x_d.oid = ${oid})\n WHEN 'pg_policy'::regclass THEN (SELECT x_c.relnamespace FROM pg_policy x_p JOIN pg_class x_c ON x_c.oid = x_p.polrelid WHERE x_p.oid = ${oid})\n WHEN 'pg_trigger'::regclass THEN (SELECT x_c.relnamespace FROM pg_trigger x_t JOIN pg_class x_c ON x_c.oid = x_t.tgrelid WHERE x_t.oid = ${oid})\n WHEN 'pg_rewrite'::regclass THEN (SELECT x_c.relnamespace FROM pg_rewrite x_r JOIN pg_class x_c ON x_c.oid = x_r.ev_class WHERE x_r.oid = ${oid})\n END`\n\nconst SUPPORTING_SCHEMAS_SQL = (from: string[]) => `\n SELECT DISTINCT rn.nspname AS schema\n FROM pg_depend d\n JOIN pg_namespace n ON n.oid = ${NAMESPACE_OF('d.classid', 'd.objid')}\n JOIN pg_namespace rn ON rn.oid = ${NAMESPACE_OF('d.refclassid', 'd.refobjid')}\n WHERE n.nspname IN (${from.map(quoteLiteral).join(', ')})\n AND rn.nspname <> n.nspname\n AND rn.nspname NOT IN ('pg_catalog', 'information_schema')\n AND rn.nspname NOT LIKE 'pg\\\\_%'\n AND d.deptype IN ('n', 'a')\n AND NOT EXISTS (SELECT 1 FROM pg_depend e\n WHERE e.classid = d.refclassid AND e.objid = d.refobjid AND e.deptype = 'e')\n ORDER BY 1`\n\nfunction quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`\n}\n\n/** `CREATE SCHEMA x;` lines made `IF NOT EXISTS`. */\nexport function tolerateExistingSchemas(sql: string): string {\n return sql.replace(/^CREATE SCHEMA (?!IF NOT EXISTS )/gm, 'CREATE SCHEMA IF NOT EXISTS ')\n}\n\n/**\n * The source's structure copied onto the target's server the way the clone\n * was, for comparing like with like. `null` when the database could not be\n * created, `{ ok: false }` when the copy failed — the proof then falls back to\n * comparing against the source itself, as it did before.\n */\nasync function copyOfSource(\n adminUrl: string, sourceUrl: string, intoUrl: string, name: string, schemas: string[], tools: PgTools,\n): Promise<{ ok: boolean } | null> {\n try {\n await pgQuery(adminUrl, `CREATE DATABASE ${quoteName(name)}`)\n } catch {\n return null\n }\n try {\n await copyStructure(sourceUrl, intoUrl, schemas, tools)\n return { ok: true }\n } catch {\n return { ok: false }\n }\n}\n\n/** Drop a throwaway database, ending any session still attached first. */\nasync function dropDatabase(adminUrl: string, name: string): Promise<void> {\n await pgQuery(adminUrl,\n `SELECT pg_terminate_backend(pid) FROM pg_stat_activity\n WHERE datname = '${name}' AND pid <> pg_backend_pid()`).catch(() => undefined)\n await pgQuery(adminUrl, `DROP DATABASE IF EXISTS ${quoteName(name)}`).catch(() => undefined)\n}\n\n/**\n * Execute a multi-statement script through psql rather than a plain connection.\n *\n * pg_dump output is not pure SQL: recent versions emit psql meta-commands such\n * as `\\restrict`, which a normal client rejects with a scanner error. psql also\n * gives us ON_ERROR_STOP, so a migration that half-applies fails the proof\n * loudly instead of producing a partially-migrated clone that then reports\n * confusing residual drift.\n */\nfunction runSql(psqlPath: string, dbUrl: string, sql: string): Promise<void> {\n const trimmed = sql.trim()\n if (!trimmed) return Promise.resolve()\n\n return new Promise((resolve, reject) => {\n // Fed over stdin: promisified execFile has no `input` option, so passing\n // one silently leaves psql waiting on a stdin that never closes until the\n // timeout kills it.\n const child = spawn(psqlPath, [dbUrl, '-v', 'ON_ERROR_STOP=1', '-q', '-f', '-'], {\n stdio: ['pipe', 'pipe', 'pipe'],\n })\n let stderr = ''\n child.stderr.on('data', (d: Buffer) => { stderr += d.toString() })\n child.on('error', reject)\n child.on('close', (code) => {\n if (code === 0) resolve()\n else reject(new Error(stderr.trim() || `psql exited ${code}`))\n })\n child.stdin.write(trimmed)\n child.stdin.end()\n })\n}\n\n/** psql ships alongside pg_dump; reuse the version-matched directory. */\nfunction psqlBeside(pgDumpPath: string): string {\n return pgDumpPath === 'pg_dump' ? 'psql' : join(dirname(pgDumpPath), 'psql')\n}\n\n/**\n * Lines pg_dump emits before the first real object, in the order it emits them.\n *\n * `\\restrict` is a psql meta-command recent versions wrap the script in;\n * `SET` and `SELECT pg_catalog.set_config(...)` configure the session. Nothing\n * here creates anything, which is what makes the preamble safe to rewrite.\n */\nconst PREAMBLE_LINE =\n /^\\s*(?:--|$|\\\\(?:un)?restrict\\b|SET\\s+[\\w.]+\\s*=|SELECT\\s+pg_catalog\\.set_config\\s*\\()/i\n\n/** A top-level `SET some.guc = value;`, capturing the parameter name. */\nconst SET_STATEMENT = /^\\s*SET\\s+([\\w.]+)\\s*=/i\n\n/**\n * Drop `SET` statements from a dump's preamble that the destination server\n * would reject.\n *\n * pg_dump writes its preamble for the version of pg_dump, not the version of\n * the server the SQL will be replayed into: pg_dump 17 added an unconditional\n * `SET transaction_timeout = 0;`, and a PostgreSQL 15 or 16 server answers that\n * with `unrecognized configuration parameter`. A PostgreSQL 18 client against a\n * Supabase still on 15 is the common case rather than an exotic one, and it made\n * `--prove` unusable there — it aborted before replaying anything (issue #72).\n *\n * The filter asks the destination which parameters it actually has rather than\n * carrying a list of version-specific names, so the next parameter a future\n * pg_dump adds to the preamble needs no change here.\n *\n * Deliberately narrow in two ways. It only rewrites the leading run of\n * preamble lines, so a `SET` inside a function body — which lives after the\n * first `CREATE` — is never touched. And it only removes statements naming a\n * parameter the destination does not have, so a `SET` that fails for any other\n * reason still fails the proof loudly: `ON_ERROR_STOP` stays on, and no error\n * from the replay is ignored. Tolerating errors instead (as `pg_restore` does,\n * which is why `clone` never noticed this) would let an incomplete clone be\n * reported as converged.\n */\nexport function dropUnsupportedSetStatements(\n sql: string, knownParameters: ReadonlySet<string>,\n): { sql: string; dropped: string[] } {\n const lines = sql.split('\\n')\n const dropped: string[] = []\n const kept: string[] = []\n\n let inPreamble = true\n for (const line of lines) {\n if (inPreamble && !PREAMBLE_LINE.test(line)) inPreamble = false\n\n if (inPreamble) {\n const name = SET_STATEMENT.exec(line)?.[1]\n if (name && !knownParameters.has(name.toLowerCase())) {\n dropped.push(name.toLowerCase())\n continue\n }\n }\n kept.push(line)\n }\n\n return { sql: kept.join('\\n'), dropped }\n}\n\n/**\n * Make a fresh clone ready to receive a dump of just the proved schemas.\n *\n * Two steps, in this order.\n *\n * The proved schemas are dropped, because the dump recreates them itself —\n * pg_dump emits `CREATE SCHEMA public` for an explicitly selected schema, which\n * a database that already has one rejects.\n *\n * Then the target's extensions are installed, those living in a proved schema\n * too: `pg_dump --schema` does not carry an extension, even one in the schema\n * it dumps, so a table whose exclusion constraint needs btree_gist in `public`\n * could not be replayed. Without this, a table whose column default calls an\n * extension function — the `extensions.uuid_generate_v4()` pattern all over\n * Supabase — cannot be created either, because a default is resolved when the\n * table is created, not when it is used. The dump's own CREATE SCHEMA then\n * finds the schema there, which tolerateExistingSchemas() allows.\n */\nexport async function prepareClone(\n cloneUrl: string, targetUrl: string, schemas: string[], queryFn: QueryFn = pgQuery,\n): Promise<void> {\n for (const schema of schemas) {\n await queryFn(cloneUrl, `DROP SCHEMA IF EXISTS ${quoteName(schema)} CASCADE`)\n }\n\n const extensions = await queryFn(targetUrl, TARGET_EXTENSIONS_SQL) as unknown as\n Array<{ name: string; schema: string }>\n\n for (const ext of extensions) {\n // Tolerated for the same reason the CREATE EXTENSION below it is: a schema\n // this clone will not accept is not a reason to abandon the proof. If the\n // structure genuinely needed it, the replay fails next and says so — which\n // is a better error than this one (issue #94).\n await queryFn(cloneUrl, `CREATE SCHEMA IF NOT EXISTS ${quoteName(ext.schema)}`)\n .catch(() => undefined)\n // Best-effort: an extension the server cannot offer this database is not a\n // reason to abandon the proof. If the schema genuinely needed it, the replay\n // fails next and says so.\n await queryFn(cloneUrl,\n `CREATE EXTENSION IF NOT EXISTS ${quoteName(ext.name)} WITH SCHEMA ${quoteName(ext.schema)}`,\n ).catch(() => undefined)\n }\n}\n\n/** Configuration parameter names this server recognises. */\nexport async function knownParameters(dbUrl: string): Promise<Set<string>> {\n const rows = await pgQuery(dbUrl, 'SELECT name FROM pg_settings') as unknown as\n Array<{ name: string }>\n return new Set(rows.map(r => r.name.toLowerCase()))\n}\n\n/**\n * Explain a failure to replay the target's own structure.\n *\n * The raw psql error names a parameter or a syntax element, with nothing to\n * connect it to the real cause — a client newer than the server. Someone\n * reading `unrecognized configuration parameter` goes looking at their schema,\n * which is the one place the problem is not (issue #72).\n */\nexport function explainStructureFailure(\n message: string, clientMajor: number, serverMajor: number,\n): string {\n // Only when the error actually looks like one — a newer client emitting SQL\n // the server has no concept of. Appending it to every failure would send\n // someone chasing a version gap that has nothing to do with, say, a missing\n // schema, which is the same species of misdirection this message exists to\n // undo.\n const looksLikeVersionGap = /unrecognized configuration parameter|syntax error/i.test(message)\n const versionGap = clientMajor > serverMajor && looksLikeVersionGap\n ? ` The local client is PostgreSQL ${clientMajor} and the target server is `\n + `${serverMajor}; pg_dump ${clientMajor} can emit SQL that a ${serverMajor} `\n + `server rejects. Installing postgresql-client-${serverMajor} removes the gap.`\n : ''\n return `could not replay the target's structure onto the clone: ${message}${versionGap}`\n}\n\n/** `DROP <kind> [IF EXISTS] <name>` and `DROP COLUMN [IF EXISTS] <name>`, capturing the bare name. */\nconst DROPPED_NAME = /\\bDROP\\s+(?:TABLE|VIEW|MATERIALIZED\\s+VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE|INDEX|COLUMN|CONSTRAINT|POLICY|TRIGGER)\\s+(?:IF\\s+EXISTS\\s+)?(?:(?:\"[^\"]+\"|[\\w$]+)\\s*\\.\\s*)?(\"[^\"]+\"|[\\w$]+)/gi\n\n/** `CREATE [OR REPLACE] <kind> [IF NOT EXISTS] <name>`, capturing the bare name. */\nconst CREATED_NAME = /\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:UNIQUE\\s+)?(?:TABLE|VIEW|MATERIALIZED\\s+VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE|INDEX|POLICY|TRIGGER|EXTENSION)\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(?:(?:\"[^\"]+\"|[\\w$]+)\\s*\\.\\s*)?(\"[^\"]+\"|[\\w$]+)/gi\n\n/**\n * Split a proof's residual into what the held-back fixes account for and\n * what they do not.\n *\n * A fix held back — a destructive drop without --allow-destructive, one left\n * out by --only — leaves its object on the target on purpose, and the proof\n * then reported that object as `unexpected`, refusing the whole apply. A line\n * is only accounted for when it is that shape — an object present that the\n * source lacks — and a held-back fix drops an object of that name; anything\n * else about the same table still blocks.\n */\nexport function residualHeldBack(\n residual: string[],\n heldBackSql: string[],\n): { heldBack: string[]; unexplained: string[] } {\n const dropped = new Set<string>()\n for (const sql of heldBackSql) {\n for (const m of sql.matchAll(DROPPED_NAME)) dropped.add(m[1].replace(/^\"|\"$/g, '').toLowerCase())\n }\n // And the creations a fix left out would have made: on a target that can't\n // hold them (no supabase_functions for a webhook, no auth schema for a\n // policy calling auth.uid()) the apply leaves them out, so the clone lacks\n // them by design and the line reads `…: missing`.\n const created: string[] = []\n for (const sql of heldBackSql) {\n for (const m of sql.matchAll(CREATED_NAME)) created.push(m[1].replace(/^\"|\"$/g, '').toLowerCase())\n }\n const heldBack: string[] = []\n const unexplained: string[] = []\n for (const line of residual) {\n const subject = /^[a-z ]+?\\s([^\\s:]+(?:\\s[^\\s:]+)?):\\s*unexpected$/i.exec(line)?.[1]\n const name = subject?.split(/[.\\s]/).pop()?.replace(/^\"|\"$/g, '').toLowerCase()\n const missing = /^(.*):\\s*missing$/i.exec(line)?.[1].toLowerCase()\n if (name && dropped.has(name)) heldBack.push(line)\n else if (missing && created.some(n => missing.endsWith(` ${n}`) || missing.endsWith(`.${n}`))) heldBack.push(line)\n else unexplained.push(line)\n }\n return { heldBack, unexplained }\n}\n\n/**\n * The checks whose fixes the proof replays: the ones that act on the proved\n * schemas, which is all the fingerprint compares.\n *\n * The others act on something the throwaway database does not have, or that\n * is not its own. pg_cron lives in one database per server, so\n * `cron.schedule()` failed in the clone with `schema \"cron\" does not exist`\n * and aborted the proof, blocking an apply that would have worked. A role\n * belongs to the whole server, so `CREATE ROLE` in the clone created it for\n * real. A publication, a reference-data row, a storage policy: none of them\n * is in the fingerprint, so replaying them could only fail, never prove.\n */\nconst PROVED_CHECKS: ReadonlySet<string> = new Set(['schema', 'rls', 'rls-coverage', 'extensions', 'webhooks'])\n\n/** A statement that acts on the server rather than the database it runs in. */\nconst SERVER_WIDE = [\n /^\\s*(?:CREATE|ALTER|DROP)\\s+(?:ROLE|USER|GROUP|DATABASE|TABLESPACE)\\b/i,\n /^\\s*ALTER\\s+SYSTEM\\b/i,\n // Role membership: a GRANT or REVOKE with no ON names roles, not objects.\n /^\\s*(?:GRANT|REVOKE)\\b(?![\\s\\S]*\\bON\\b)/i,\n]\n\n/**\n * Split the planned fixes into those the proof replays and those it cannot.\n *\n * A fix holding a server-wide statement is never replayed, whichever check it\n * came from: the proof must not change anything outside the database it made.\n */\nexport function proofScope<T extends { check: string; sql: string }>(\n statements: readonly T[],\n): { replay: T[]; unproved: T[] } {\n const replay: T[] = []\n const unproved: T[] = []\n for (const stmt of statements) {\n const serverWide = splitSqlStatements(stmt.sql)\n .filter(s => !isCommentOnly(s))\n .some(s => SERVER_WIDE.some(re => re.test(sqlSkeleton(s))))\n if (PROVED_CHECKS.has(stmt.check) && !serverWide) replay.push(stmt)\n else unproved.push(stmt)\n }\n return { replay, unproved }\n}\n\n/** Roles the migration grants to or scopes a policy to that the server lacks. */\nasync function absentRoles(dbUrl: string, sql: string): Promise<string[]> {\n const named = [...new Set(splitSqlStatements(sql).flatMap(s => rolesNamedBy(s)))]\n if (named.length === 0) return []\n const rows = await pgQuery(dbUrl, 'SELECT rolname FROM pg_roles WHERE rolname = ANY($1::text[])', [named]) as unknown as\n Array<{ rolname: string }>\n const present = new Set(rows.map(r => r.rolname))\n return named.filter(r => !present.has(r))\n}\n\n/**\n * The verdict for what remains after the migration.\n *\n * Unscoped — `baseline` undefined — everything remaining is a failure to\n * converge. Scoped, a remaining difference is set aside when the target\n * already had it and none of the run's checks compares that kind of object:\n * `diff --check=rls --prove` was refused for every unrelated table the target\n * lacked, which the run never set out to create.\n */\nfunction withinScope(\n residual: string[], baseline: string[] | undefined, checks: readonly string[] | undefined, cloneName: string,\n): ProofResult {\n if (!baseline || !checks) return { converged: residual.length === 0, residual, cloneName }\n const had = new Set(baseline)\n const outOfScope = residual.filter(l => had.has(l) && outsideTheRun(l, checks))\n const remaining = residual.filter(l => !outOfScope.includes(l))\n return { converged: remaining.length === 0, residual: remaining, outOfScope, cloneName }\n}\n\n/** Which state-diff lines each check compares, beyond the schema check's all. */\nconst GOVERNED: Record<string, RegExp> = {\n 'rls': /^policy on |: RLS (?:enabled|forced) /,\n 'rls-coverage': /: RLS enabled /,\n 'extensions': /^extension /,\n 'webhooks': /^trigger on /,\n}\n\n/** A difference none of the run's checks compares. */\nexport function outsideTheRun(line: string, checks: readonly string[]): boolean {\n if (checks.includes('schema')) return false\n return !checks.some(c => GOVERNED[c]?.test(line))\n}\n","/**\n * Structural diff between two schema-state documents.\n *\n * The convergence proof used to compare fingerprints — one sorted string per\n * database — and report the lines that differed. That is correct but close to\n * unreadable: a changed column arrives as two near-identical lines of catalog\n * shorthand and leaves the reader to spot the one field that moved.\n *\n * missing: col public.orders.total numeric NO - ident= gen= store=x compress=- coll=-\n * unexpected: col public.orders.total numeric NO - ident= gen= store=p compress=- coll=-\n *\n * The state document has the same information as data, so the same difference\n * can be named:\n *\n * column public.orders.total: storage extended → plain\n *\n * Detection is unchanged. The state document is verified to distinguish every\n * pair of schemas the fingerprint distinguishes, so this reports the same\n * differences — it does not find more of them, and it must not find fewer.\n */\nimport type { SchemaState, StateTable, StateColumn } from '@akal/pg-conformance'\n\n/** How a value reads when absent, so `null` never reaches the output raw. */\nconst show = (v: unknown): string => {\n if (v === null || v === undefined) return 'none'\n if (typeof v === 'boolean') return v ? 'yes' : 'no'\n if (Array.isArray(v)) return v.length ? v.join(', ') : 'none'\n if (typeof v === 'object') return JSON.stringify(v)\n return String(v)\n}\n\n/** `schema.name`, or just the name when the schema adds nothing. */\nconst qualify = (schema: string, name: string): string => `${schema}.${name}`\n\n/**\n * Compare one field of two objects, appending a finding when it moved.\n *\n * Values are compared by their rendered form rather than by identity, so an\n * array whose contents match reads as unchanged even when the two documents\n * hold different array instances.\n */\nfunction compareField(\n out: string[], subject: string, label: string, before: unknown, after: unknown,\n): void {\n const a = show(before), b = show(after)\n if (a !== b) out.push(`${subject}: ${label} ${a} → ${b}`)\n}\n\n/** Diff two collections keyed by a stable identity. */\nfunction compareKeyed<T>(\n out: string[],\n kind: string,\n before: T[] | null | undefined,\n after: T[] | null | undefined,\n keyOf: (item: T) => string,\n compare: (out: string[], subject: string, a: T, b: T) => void,\n): void {\n const a = new Map((before ?? []).map(x => [keyOf(x), x]))\n const b = new Map((after ?? []).map(x => [keyOf(x), x]))\n\n for (const [key, item] of a) {\n if (!b.has(key)) out.push(`${kind} ${key}: missing`)\n else compare(out, `${kind} ${key}`, item, b.get(key) as T)\n }\n for (const key of b.keys()) {\n if (!a.has(key)) out.push(`${kind} ${key}: unexpected`)\n }\n}\n\nfunction compareColumn(out: string[], subject: string, a: StateColumn, b: StateColumn): void {\n compareField(out, subject, 'type', a.type, b.type)\n compareField(out, subject, 'not null', a.not_null, b.not_null)\n compareField(out, subject, 'default', a.default, b.default)\n compareField(out, subject, 'identity', a.identity, b.identity)\n compareField(out, subject, 'identity options', a.identity_options, b.identity_options)\n compareField(out, subject, 'generated', a.generated, b.generated)\n compareField(out, subject, 'storage', a.storage, b.storage)\n compareField(out, subject, 'compression', a.compression, b.compression)\n compareField(out, subject, 'collation', a.collation, b.collation)\n compareField(out, subject, 'comment', a.comment, b.comment)\n}\n\nfunction compareTable(out: string[], subject: string, a: StateTable, b: StateTable): void {\n compareField(out, subject, 'kind', a.kind, b.kind)\n compareField(out, subject, 'unlogged', a.unlogged, b.unlogged)\n compareField(out, subject, 'partition of', a.partition_of, b.partition_of)\n compareField(out, subject, 'partition bound', a.partition_bound, b.partition_bound)\n compareField(out, subject, 'partition by', a.partition_by, b.partition_by)\n compareField(out, subject, 'inherits', a.inherits, b.inherits)\n compareField(out, subject, 'options', a.options, b.options)\n compareField(out, subject, 'RLS enabled', a.rls_enabled, b.rls_enabled)\n compareField(out, subject, 'RLS forced', a.rls_forced, b.rls_forced)\n compareField(out, subject, 'comment', a.comment, b.comment)\n\n // Findings name the object in full — \"column public.orders.total\" — so a\n // reader never has to hold the enclosing table in their head.\n const prefix = subject.replace(/^table /, '')\n compareKeyed(out, 'column', a.columns, b.columns,\n c => `${prefix}.${c.name}`,\n (o, s, x, y) => compareColumn(o, s, x, y))\n compareKeyed(out, `constraint on ${prefix}`, a.constraints, b.constraints,\n c => c.name,\n (o, s, x, y) => {\n compareField(o, s, 'definition', x.definition, y.definition)\n compareField(o, s, 'validated', x.validated, y.validated)\n compareField(o, s, 'deferrable', x.deferrable, y.deferrable)\n compareField(o, s, 'deferred', x.deferred, y.deferred)\n })\n compareKeyed(out, `index on ${prefix}`, a.indexes, b.indexes,\n i => i.name,\n (o, s, x, y) => compareField(o, s, 'definition', x.definition, y.definition))\n compareKeyed(out, `policy on ${prefix}`, a.policies, b.policies,\n p => p.name,\n (o, s, x, y) => {\n compareField(o, s, 'command', x.command, y.command)\n compareField(o, s, 'permissive', x.permissive, y.permissive)\n compareField(o, s, 'roles', x.roles, y.roles)\n compareField(o, s, 'using', x.using, y.using)\n compareField(o, s, 'with check', x.with_check, y.with_check)\n })\n compareKeyed(out, `trigger on ${prefix}`, a.triggers, b.triggers,\n t => t.name,\n (o, s, x, y) => compareField(o, s, 'definition', x.definition, y.definition))\n}\n\n/**\n * Everything that differs between two schema states, most structural first.\n *\n * Returns an empty array when the two are identical. Each entry names the\n * object and what about it moved, so the caller can print the list as-is.\n */\nexport function diffState(before: SchemaState, after: SchemaState): string[] {\n const out: string[] = []\n\n compareKeyed(out, 'table', before.tables, after.tables,\n t => qualify(t.schema, t.name),\n (o, s, a, b) => compareTable(o, s, a, b))\n\n compareKeyed(out, 'view', before.views, after.views,\n v => qualify(v.schema, v.name),\n (o, s, a, b) => {\n compareField(o, s, 'materialized', a.materialized, b.materialized)\n compareField(o, s, 'definition', a.definition, b.definition)\n compareField(o, s, 'options', a.options, b.options)\n })\n\n compareKeyed(out, 'sequence', before.sequences, after.sequences,\n q => qualify(q.schema, q.name),\n (o, s, a, b) => {\n for (const k of ['type', 'start', 'increment', 'min', 'max', 'cache', 'cycle', 'owned_by'] as const) {\n compareField(o, s, k.replace('_', ' '), a[k], b[k])\n }\n })\n\n compareKeyed(out, 'routine', before.routines, after.routines,\n r => `${qualify(r.schema, r.name)}(${r.arguments})`,\n (o, s, a, b) => {\n compareField(o, s, 'kind', a.kind, b.kind)\n compareField(o, s, 'definition', a.definition, b.definition)\n })\n\n compareKeyed(out, 'type', before.types, after.types,\n t => qualify(t.schema, t.name),\n (o, s, a, b) => {\n compareField(o, s, 'kind', a.kind, b.kind)\n compareField(o, s, 'labels', a.labels, b.labels)\n compareField(o, s, 'base type', a.base_type, b.base_type)\n compareField(o, s, 'not null', a.not_null, b.not_null)\n compareField(o, s, 'default', a.default, b.default)\n compareField(o, s, 'constraints', a.constraints, b.constraints)\n compareField(o, s, 'attributes', a.attributes, b.attributes)\n })\n\n compareKeyed(out, 'extension', before.extensions, after.extensions,\n e => e.name,\n (o, s, a, b) => compareField(o, s, 'version', a.version, b.version))\n\n return out\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAS,mBAAmB;AAC5B,SAAS,UAAU,aAAa;AAChC,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB,gBAAkC;;;ACH3D,IAAM,OAAO,CAAC,MAAuB;AACnC,MAAI,MAAM,QAAQ,MAAM,OAAW,QAAO;AAC1C,MAAI,OAAO,MAAM,UAAW,QAAO,IAAI,QAAQ;AAC/C,MAAI,MAAM,QAAQ,CAAC,EAAG,QAAO,EAAE,SAAS,EAAE,KAAK,IAAI,IAAI;AACvD,MAAI,OAAO,MAAM,SAAU,QAAO,KAAK,UAAU,CAAC;AAClD,SAAO,OAAO,CAAC;AACjB;AAGA,IAAM,U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GAAG,KAAK,IAAI,CAAC;AAClD;","names":["residual","knownParameters"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/strings.ts"],"sourcesContent":["/**\n * Shared string manipulation utilities.\n */\n\n/** Maximum length for generated slugs. */\nconst MAX_SLUG_LENGTH = 60\n\n/**\n * Convert a human-readable string to a filename-safe slug.\n * Lowercases, replaces non-alphanumeric chars with separator, trims edges.\n */\nexport function slugify(name: string, separator = '_'): string {\n const pattern = new RegExp(`[^a-z0-9]+`, 'g')\n const edgePattern = new RegExp(`^${escapeRegex(separator)}|${escapeRegex(separator)}$`, 'g')\n return name\n .toLowerCase()\n .replace(pattern, separator)\n .replace(edgePattern, '')\n .slice(0, MAX_SLUG_LENGTH)\n}\n\n/** Escape every regex metacharacter, so a value can be matched literally. */\nexport function escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Split a repeatable CLI flag into individual values.\n *\n * `--x=a,b --x=c` and `--x=a --x=b --x=c` mean the same thing; oclif hands over\n * the raw strings, and a comma is the natural separator for the lists these\n * flags take — table names, issue ids — none of which can contain one.\n */\nexport function parseFlagList(values?: string[]): string[] {\n if (!Array.isArray(values)) return []\n return values\n .flatMap(v => String(v).split(','))\n .map(v => v.trim())\n .filter(v => v.length > 0)\n}\n\n/**\n * Compile a `*`/`?` glob to an anchored regular expression.\n *\n * The same two wildcards `@dbdiff/cli` supports, so a pattern means one thing\n * whether it reaches dbdiff or is matched here. Every other character is\n * escaped, so a value containing regex metacharacters cannot turn a filter into\n * a different pattern. Both are linear: the pattern is anchored and has no\n * nested quantifiers.\n */\nexport function globToRegExp(pattern: string): RegExp {\n let out = '^'\n for (const ch of pattern) {\n if (ch === '*') out += '.*'\n else if (ch === '?') out += '.'\n else out += escapeRegex(ch)\n }\n return new RegExp(out + '$')\n}\n\n/** Does `value` match a `*`/`?` glob? Case-insensitive. */\nexport function matchesGlob(value: string, pattern: string): boolean {\n return globToRegExp(pattern.toLowerCase()).test(value.toLowerCase())\n}\n\n/**\n * Parse Postgres name[] which may arrive as a JS array or Postgres literal `{a,b}`.\n * Returns a sorted, deduplicated array of role names.\n *\n * An element with a space, comma or quote in it is double-quoted in the\n * literal, with `\\\\` escaping a quote or backslash: `{\"Admins \\\\\"A\\\\\"\",anon}`.\n * Split on commas, such a role kept its literal quoting and was then quoted\n * again as a name, so the policy went to a role that did not exist.\n */\nexport function normalizeRoles(roles: string[] | string): string[] {\n const arr = Array.isArray(roles) ? roles : [roles]\n return [...new Set(\n arr\n .flatMap(r => /^\\{.*\\}$/s.test(r) ? arrayLiteralElements(r) : [r])\n .map(r => r.trim())\n .filter(Boolean),\n )].sort()\n}\n\n/** The elements of a one-dimensional PostgreSQL array literal. */\nfunction arrayLiteralElements(literal: string): string[] {\n const inner = literal.slice(1, -1)\n const out: string[] = []\n let i = 0\n while (i < inner.length) {\n let value = ''\n if (inner[i] === '\"') {\n for (i++; i < inner.length && inner[i] !== '\"'; i++) {\n if (inner[i] === '\\\\') i++\n value += inner[i]\n }\n i++\n } else {\n const end = inner.indexOf(',', i)\n value = inner.slice(i, end === -1 ? inner.length : end)\n i = end === -1 ? inner.length : end\n }\n out.push(value)\n if (inner[i] === ',') i++\n }\n return out\n}\n"],"mappings":";AAKA,IAAM,kBAAkB;AAMjB,SAAS,QAAQ,MAAc,YAAY,KAAa;AAC7D,QAAM,UAAU,IAAI,OAAO,cAAc,GAAG;AAC5C,QAAM,cAAc,IAAI,OAAO,IAAI,YAAY,SAAS,CAAC,IAAI,YAAY,SAAS,CAAC,KAAK,GAAG;AAC3F,SAAO,KACJ,YAAY,EACZ,QAAQ,SAAS,SAAS,EAC1B,QAAQ,aAAa,EAAE,EACvB,MAAM,GAAG,eAAe;AAC7B;AAGO,SAAS,YAAY,GAAmB;AAC7C,SAAO,EAAE,QAAQ,uBAAuB,MAAM;AAChD;AASO,SAAS,cAAc,QAA6B;AACzD,MAAI,CAAC,MAAM,QAAQ,MAAM,EAA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AS,GAAG;AACtD,UAAI,QAAQ,KAAK,MAAM,SAAS;AAAA,IAClC;AACA,QAAI,KAAK,KAAK;AACd,QAAI,MAAM,CAAC,MAAM,IAAK;AAAA,EACxB;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/sql-split.ts"],"sourcesContent":["/**\n * Splitting SQL text into statements.\n *\n * Kept apart from the quoting helpers in `sql.ts` because this is a scanner\n * rather than an escaper, and it is only needed where SQL arrives from outside\n * — a pg_dump, a migration file — rather than being generated here.\n */\n\n/** `$$` or `$tag$`, anchored at the current position. */\nconst DOLLAR_TAG = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/\n\n/**\n * Split SQL into individual statements.\n *\n * Splitting on `;` alone breaks the moment the SQL contains a routine body: a\n * `CREATE FUNCTION ... AS $$ BEGIN ... ; ... END; $$;` is shredded into three\n * fragments, none of which parse, and whatever depends on the function fails\n * after them. That is what `restore` did to a pg_dump's functions and their\n * triggers (issue #80).\n *\n * The text is walked once, tracking the four things that can hold a semicolon\n * without ending a statement:\n *\n * - `'single quoted'`, where `''` is an escaped quote and not a close\n * - `\"quoted identifiers\"`, same doubling rule\n * - `$tag$ dollar quoted $tag$`, which is how routine bodies arrive\n * - line comments, and block comments, which nest in PostgreSQL\n *\n * Statements come back trimmed with the trailing `;` removed, and empty\n * fragments dropped. Comments are left in place: they are part of the\n * statement's text, and a caller wanting a bare statement can say so.\n */\nexport function splitSqlStatements(sql: string): string[] {\n const statements: string[] = []\n let start = 0\n let i = 0\n let blockDepth = 0\n\n const push = (end: number) => {\n const piece = sql.slice(start, end).trim()\n if (piece.length > 0) statements.push(piece)\n }\n\n while (i < sql.length) {\n if (blockDepth > 0) {\n if (sql.startsWith('/*', i)) { blockDepth++; i += 2; continue }\n if (sql.startsWith('*/', i)) { blockDepth--; i += 2; continue }\n i++\n continue\n }\n\n if (sql.startsWith('/*', i)) { blockDepth = 1; i += 2; continue }\n\n if (sql.startsWith('--', i)) {\n const newline = sql.indexOf('\\n', i)\n i = newline === -1 ? sql.length : newline + 1\n continue\n }\n\n const ch = sql[i]\n\n if (ch === \"'\" || ch === '\"') {\n i++\n while (i < sql.length) {\n if (sql[i] !== ch) { i++; continue }\n // A doubled quote is an escape, not the end of the run.\n if (sql[i + 1] === ch) { i += 2; continue }\n i++\n break\n }\n continue\n }\n\n if (ch === '$') {\n const tag = DOLLAR_TAG.exec(sql.slice(i))\n if (tag) {\n const close = sql.indexOf(tag[0], i + tag[0].length)\n i = close === -1 ? sql.length : close + tag[0].length\n continue\n }\n i++\n continue\n }\n\n if (ch === ';') {\n push(i)\n i++\n start = i\n continue\n }\n\n i++\n }\n\n push(sql.length)\n return statements\n}\n\n/** Whether a statement is nothing but comments and whitespace. */\nexport function isCommentOnly(statement: string): boolean {\n const meaningful = statement\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0 && !line.startsWith('--'))\n return meaningful.length === 0\n}\n\n/**\n * The `\\restrict` / `\\unrestrict` wrappers pg_dump 16 and later emit.\n *\n * Matched as whole lines, and only these two commands rather than anything\n * beginning with a backslash: a line inside a dollar-quoted routine body could\n * start with one, and rewriting a function's body would be worse than the\n * problem being solved.\n */\nconst PSQL_WRAPPER_LINE = /^[ \\t]*\\\\(?:un)?restrict\\b[^\\n]*$/gm\n\n/**\n * Remove psql meta-commands, which only psql understands.\n *\n * Done to the text *before* it is split, because these commands are terminated\n * by the end of the line rather than by a semicolon. Dropping them afterwards\n * as whole statements took the following statement with them — `\\restrict abc`\n * and the `CREATE TABLE` under it are one fragment when nothing separates them\n * (issue #80). Sent to the server they fail with `syntax error at or near \"\\\"`.\n */\nexport function stripPsqlMetaCommands(sql: string): string {\n return sql.replace(PSQL_WRAPPER_LINE, '')\n}\n\n/**\n * Whether a statement is nothing but psql meta-commands and comments.\n *\n * A safety net for anything `stripPsqlMetaCommands` does not cover. It\n * deliberately requires *every* meaningful line to be a meta-command, so a\n * statement that also carries SQL is never discarded wholesale.\n */\nexport function isPsqlMetaCommand(statement: string): boolean {\n const meaningful = statement\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0 && !line.startsWith('--'))\n\n return meaningful.length > 0 && meaningful.every(line => line.startsWith('\\\\'))\n}\n"],"mappings":";AASA,IAAM,aAAa;AAuBZ,SAAS,mBAAmB,KAAuB;AACxD,QAAM,aAAuB,CAAC;AAC9B,MAAI,QAAQ;AACZ,MAAI,IAAI;AACR,MAAI,aAAa;AAEjB,QAAM,OAAO,CAAC,QAAgB;AAC5B,UAAM,QAAQ,IAAI,MAAM,OAAO,GAAG,EAAE,KAAK;AACzC,QAAI,MAAM,SAAS,EAAG,YAAW,KAAK,KAAK;AAAA,EAC7C;AAEA,SAAO,IAAI,IAAI,QAAQ;AACrB,QAAI,aAAa,GAAG;AAClB,UAAI,IAAI,WAAW,MAAM,CAAC,GAAG;AAAE;AAAc,aAAK;AAAG;AAAA,MAAS;AAC9D,UAAI,IAAI,WAAW,MAAM,CAAC,GAAG;AAAE;AAAc,aAAK;AAAG;AAAA,MAAS;AAC9D;AACA;AAAA,IACF;AAEA,QAAI,IAAI,WAAW,MAAM,CAAC,GAAG;AAAE,mBAAa;AAAG,WAAK;AAAG;AAAA,IAAS;AAEhE,QAAI,IAAI,WAAW,MAAM,CAAC,GAAG;AAC3B,YAAM,UAAU,IAAI,QAAQ,MAAM,CAAC;AACnC,UAAI,YAAY,KAAK,IAAI,SAAS,UAAU;AAC5C;AAAA,IACF;AAEA,UAAM,KAAK,IAAI,CAAC;AAEhB,QAAI,OAAO,OAAO,OAAO,KAAK;AAC5B;AACA,aAAO,IAAI,IAAI,QAAQ;AACrB,YAAI,IAAI,CAAC,MAAM,IAAI;AAAE;AAAK;AAAA,QAAS;AAEnC,YAAI,IAAI,IAAI,CAAC,MAAM,IAAI;AAAE,eAAK;AAAG;AAAA,QAAS;AAC1C;AACA;AAAA,MACF;AACA;AAAA,IACF;AAEA,QAAI,OAAO,KAAK;AACd,YAAM,MAAM,WAA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