@akal/supaforge 0.0.31 → 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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -11
  3. package/dist/base-command.d.ts +1 -0
  4. package/dist/base-command.js +2 -2
  5. package/dist/{chunk-BHYLBKYD.js → chunk-2SELREHW.js} +5 -5
  6. package/dist/{chunk-5Z3SAIQS.js → chunk-3HGAV5CC.js} +97 -831
  7. package/dist/{chunk-XMYMIURR.js → chunk-4IVN7QVY.js} +119 -39
  8. package/dist/{chunk-NXRSAVRU.js → chunk-6LJERPUN.js} +28 -7
  9. package/dist/{chunk-4OU7KO5Y.js → chunk-6Q7MHFBM.js} +2 -2
  10. package/dist/{chunk-PARSNTBD.js → chunk-7NAZGZPV.js} +56 -25
  11. package/dist/{chunk-VOXZWQ3N.js → chunk-BUOWHE36.js} +372 -9
  12. package/dist/{chunk-TQJSQLWA.js → chunk-DMIWAJRB.js} +38 -10
  13. package/dist/{chunk-LQXF65MC.js → chunk-GEHPTPNZ.js} +3 -3
  14. package/dist/chunk-GZREXCQZ.js +207 -0
  15. package/dist/{chunk-YVDSR4GM.js → chunk-MIRLB5JM.js} +51 -23
  16. package/dist/{chunk-KIFJGON5.js → chunk-NTUASFQ3.js} +2 -2
  17. package/dist/{chunk-5QQBTLWO.js → chunk-ORQJVE57.js} +3 -3
  18. package/dist/{chunk-VMTBLHN2.js → chunk-SC2XHGIS.js} +2 -2
  19. package/dist/{chunk-X6V2GGDZ.js → chunk-SQPCWGQO.js} +388 -64
  20. package/dist/chunk-UWAVXC57.js +916 -0
  21. package/dist/commands/clone.js +10 -10
  22. package/dist/commands/diff.d.ts +16 -0
  23. package/dist/commands/diff.js +11 -12
  24. package/dist/commands/hukam.js +11 -12
  25. package/dist/commands/mcp.d.ts +1 -0
  26. package/dist/commands/mcp.js +18 -9
  27. package/dist/commands/migrate/baseline.js +3 -3
  28. package/dist/commands/migrate/create.js +5 -6
  29. package/dist/commands/migrate/list.js +4 -4
  30. package/dist/commands/migrate/run.js +5 -6
  31. package/dist/commands/report.js +3 -3
  32. package/dist/commands/restore.js +11 -13
  33. package/dist/commands/snapshot.js +6 -8
  34. package/dist/commands/sync.js +11 -12
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +16 -16
  37. package/package.json +10 -8
  38. package/bin/dev.js +0 -10
  39. package/dist/base-command.js.map +0 -1
  40. package/dist/chunk-4OU7KO5Y.js.map +0 -1
  41. package/dist/chunk-5QQBTLWO.js.map +0 -1
  42. package/dist/chunk-5Z3SAIQS.js.map +0 -1
  43. package/dist/chunk-6WAMNZLO.js.map +0 -1
  44. package/dist/chunk-BHYLBKYD.js.map +0 -1
  45. package/dist/chunk-BLKJWDTL.js.map +0 -1
  46. package/dist/chunk-DQQ5E563.js.map +0 -1
  47. package/dist/chunk-G2DIPIYU.js.map +0 -1
  48. package/dist/chunk-H5MJ5DFX.js +0 -16
  49. package/dist/chunk-H5MJ5DFX.js.map +0 -1
  50. package/dist/chunk-KIFJGON5.js.map +0 -1
  51. package/dist/chunk-LQXF65MC.js.map +0 -1
  52. package/dist/chunk-NXRSAVRU.js.map +0 -1
  53. package/dist/chunk-PARSNTBD.js.map +0 -1
  54. package/dist/chunk-RRMI5CZD.js +0 -376
  55. package/dist/chunk-RRMI5CZD.js.map +0 -1
  56. package/dist/chunk-SF3YA42C.js +0 -506
  57. package/dist/chunk-SF3YA42C.js.map +0 -1
  58. package/dist/chunk-TQJSQLWA.js.map +0 -1
  59. package/dist/chunk-VMTBLHN2.js.map +0 -1
  60. package/dist/chunk-VOXZWQ3N.js.map +0 -1
  61. package/dist/chunk-X6V2GGDZ.js.map +0 -1
  62. package/dist/chunk-XMYMIURR.js.map +0 -1
  63. package/dist/chunk-YVDSR4GM.js.map +0 -1
  64. package/dist/commands/clone.js.map +0 -1
  65. package/dist/commands/diff.js.map +0 -1
  66. package/dist/commands/help.js.map +0 -1
  67. package/dist/commands/hukam.js.map +0 -1
  68. package/dist/commands/init.js.map +0 -1
  69. package/dist/commands/mcp.js.map +0 -1
  70. package/dist/commands/migrate/baseline.js.map +0 -1
  71. package/dist/commands/migrate/create.js.map +0 -1
  72. package/dist/commands/migrate/list.js.map +0 -1
  73. package/dist/commands/migrate/run.js.map +0 -1
  74. package/dist/commands/report.js.map +0 -1
  75. package/dist/commands/restore.js.map +0 -1
  76. package/dist/commands/snapshot.js.map +0 -1
  77. package/dist/commands/sync.js.map +0 -1
  78. package/dist/help.js.map +0 -1
  79. package/dist/index.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/base-command.ts","../src/preflight.ts","../src/local-pg.ts","../src/run-log.ts"],"sourcesContent":["import { formatWithOptions } from 'node:util'\nimport { Command } from '@oclif/core'\nimport { loadConfig, validateConfig, validateSingleEnvConfig } from './config.js'\nimport { Preflight } from './preflight.js'\nimport { DEFAULT_MIGRATIONS_DIR } from './checks/migrations.js'\nimport type { SupaForgeConfig, EnvironmentConfig } from './types/config.js'\nimport type { PreflightReport } from './preflight.js'\nimport { appendRunLog, redactArgs, type RunLogCheckSummary } from './run-log.js'\n\n/**\n * Shared base for all supaforge commands.\n * Extracts config loading, env resolution, URL redaction, and run logging.\n */\nexport abstract class BaseCommand extends Command {\n\n private _startTime = 0\n private _logWritten = false\n private _checkSummaries?: RunLogCheckSummary[]\n\n /**\n * Under --json, stdout carries the JSON and nothing else: every other line a\n * command prints — preflight checks, progress — goes to stderr. Before, the\n * text came first and the output did not parse.\n */\n override log(message = '', ...args: unknown[]): void {\n if (this.argv.includes('--json')) {\n process.stderr.write(formatWithOptions({ colors: false }, message, ...args) + '\\n')\n return\n }\n super.log(message, ...args)\n }\n\n /** The command's result as JSON, on stdout. */\n protected json(value: unknown): void {\n process.stdout.write(JSON.stringify(value, null, 2) + '\\n')\n }\n\n /** Call after scan() to attach per-check metadata to the run log entry. */\n protected setCheckSummaries(summaries: RunLogCheckSummary[]): void {\n this._checkSummaries = summaries\n }\n\n override async init(): Promise<void> {\n await super.init()\n this._startTime = Date.now()\n }\n\n override async catch(err: Error): Promise<void> {\n this._logWritten = true\n await this._writeRunLog('error', err.message)\n return super.catch(err)\n }\n\n override async finally(err: Error | undefined): Promise<void> {\n if (!this._logWritten) {\n await this._writeRunLog(err ? 'error' : 'success', err?.message)\n }\n return super.finally(err)\n }\n\n private async _writeRunLog(exitStatus: 'success' | 'error', error?: string): Promise<void> {\n try {\n const version = this.config?.version\n const argv = this.argv ?? []\n await appendRunLog({\n timestamp: new Date().toISOString(),\n command: this.id ?? 'unknown',\n args: redactArgs(argv),\n durationMs: Date.now() - this._startTime,\n exitStatus,\n error,\n version,\n checkSummaries: this._checkSummaries,\n })\n } catch {\n // Never let logging failures surface to users\n }\n }\n\n /** Load config or exit with a helpful error. */\n protected async loadConfigOrFail(): Promise<SupaForgeConfig> {\n try {\n return await loadConfig()\n } catch {\n this.error(\n 'Could not load supaforge.config.json. Run \"supaforge init\" first.',\n )\n }\n }\n\n /**\n * Resolve a single environment by name.\n * Accepts an explicit flag value or falls back to config.source.\n */\n protected resolveEnv(\n config: SupaForgeConfig,\n envFlag?: string,\n ): { envName: string; env: EnvironmentConfig } {\n const envName = envFlag ?? config.source\n if (!envName) {\n this.error('No environment specified. Use --env=<name> or set \"source\" in your config.')\n }\n\n const errors = validateSingleEnvConfig(config, envName)\n if (errors.length > 0) {\n this.error(`Invalid configuration:\\n ${errors.join('\\n ')}`)\n }\n\n return { envName, env: config.environments[envName] }\n }\n\n /**\n * Validate a two-env (source + target) config.\n * Applies flag overrides before validation.\n */\n protected validateDualEnvConfig(\n config: SupaForgeConfig,\n sourceFlag?: string,\n targetFlag?: string,\n ): void {\n if (sourceFlag) config.source = sourceFlag\n if (targetFlag) config.target = targetFlag\n\n const errors = validateConfig(config)\n if (errors.length > 0) {\n this.error(`Invalid configuration:\\n ${errors.join('\\n ')}`)\n }\n }\n\n /** Redact password from a database URL for display. */\n protected redactUrl(url: string): string {\n return url.replace(/:([^@/]{1,})@/, ':***@')\n }\n\n /** Resolve the migrations directory from config (with default fallback). */\n protected resolveMigrationsDir(config: SupaForgeConfig): string {\n return config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR\n }\n\n /**\n * Create, run, and enforce a preflight check.\n * Returns the Preflight instance for commands that need to add custom checks.\n * When `abortMessage` is provided, exits with an error if checks fail.\n */\n protected createPreflight(title: string): Preflight {\n return new Preflight(title, (m) => this.log(m))\n }\n\n /**\n * Run a preflight and abort with a user-friendly message if it fails.\n * Returns the report for commands that inspect individual check results.\n */\n protected async runPreflight(preflight: Preflight, commandName: string): Promise<PreflightReport> {\n const report = await preflight.run()\n if (!report.passed) {\n this.error(`${commandName} aborted — fix the issues above first.`, { exit: 1 })\n }\n return report\n }\n}\n","import pg from 'pg'\nimport { detectRuntime } from './local-pg.js'\nimport { pgClientConfig, resolveConnectTimeoutMs } from './db.js'\nimport { DB_PROBE_TIMEOUT_MS } from './constants.js'\nimport { ok, warn, dim, cmd, bold } from './ui.js'\nimport { redactUrls, describeFailure } from './utils/error.js'\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Result of a single connectivity check. */\nexport interface ConnCheckResult {\n reachable: boolean\n version?: string\n error?: string\n}\n\n/** Outcome of a single preflight check (DB connectivity or custom). */\nexport interface CheckEntry {\n label: string\n passed: boolean\n detail?: string\n error?: string\n hints?: string[]\n}\n\n/** Full report returned by Preflight.run(). */\nexport interface PreflightReport {\n passed: boolean\n checks: CheckEntry[]\n}\n\n/** Supabase CLI default PostgreSQL port. */\nconst SUPABASE_LOCAL_PORT = '54322'\n\n/** Standard PostgreSQL port. */\nconst DEFAULT_PG_PORT = '5432'\n\n// ─── Standalone helpers (remain exported for direct use / tests) ─────────────\n\n/**\n * `pg`'s messages for the two bounds this module sets. Neither says what was\n * being waited for, and \"timeout expired\" in particular reads like a bug\n * rather than a diagnosis.\n */\nconst CONNECT_TIMEOUT_RE = /timeout expired|connection timeout/i\nconst QUERY_TIMEOUT_RE = /query read timeout/i\n\n/**\n * Replace a bare driver timeout with something that says which wait elapsed.\n *\n * Left untouched when it is not one of ours: a server-side `statement_timeout`\n * or an OS-level ETIMEDOUT is a different failure and already reads clearly.\n */\nexport function describeTimeout(message: string, connectTimeoutMs: number, probeTimeoutMs: number): string {\n if (CONNECT_TIMEOUT_RE.test(message)) {\n return `timed out after ${Math.round(connectTimeoutMs / 1000)}s connecting — the host accepted the connection but never completed the handshake`\n }\n if (QUERY_TIMEOUT_RE.test(message)) {\n return `timed out after ${Math.round(probeTimeoutMs / 1000)}s waiting for server response — connected, but the server did not answer`\n }\n return message\n}\n\n/**\n * Test that a PostgreSQL database is reachable and return the server version.\n *\n * Both waits are bounded. Without that, a host that accepts the connection and\n * then goes silent blocks here forever, and the command produces no output at\n * all past the `Checks:` header (issue #44).\n */\nexport async function checkConnection(dbUrl: string): Promise<ConnCheckResult> {\n const connectTimeoutMs = resolveConnectTimeoutMs()\n let client: pg.Client | undefined\n try {\n client = new pg.Client(pgClientConfig(dbUrl, DB_PROBE_TIMEOUT_MS))\n await client.connect()\n const { rows } = await client.query('SHOW server_version')\n const version = (rows[0] as Record<string, string>).server_version\n return { reachable: true, version }\n } catch (err) {\n return {\n reachable: false,\n error: describeTimeout(describeFailure(err), connectTimeoutMs, DB_PROBE_TIMEOUT_MS),\n }\n } finally {\n // A client that timed out mid-handshake still holds an open socket, which\n // keeps the event loop alive and hangs the process after the report has\n // already printed. end() on a never-connected client is a no-op, and a\n // failure closing it must not mask the real error above.\n try {\n await client?.end()\n } catch {\n // ignore\n }\n }\n}\n\n/** Errors that indicate the server IS running but rejecting the connection. */\nconst SERVER_REACHABLE_RE = /password authentication failed|does not exist|database .* does not exist|SSL.*required|no pg_hba\\.conf entry/i\n\n/**\n * Build context-aware hints when a local PostgreSQL is not reachable.\n * Detects Supabase CLI port, available container runtimes, etc.\n *\n * When `error` is provided and indicates the server IS running (auth failure,\n * missing database, SSL rejection), startup hints are suppressed in favour of\n * configuration hints.\n */\nexport async function buildLocalHints(dbUrl: string, error?: string): Promise<string[]> {\n const hints: string[] = []\n try {\n const urlObj = new URL(dbUrl)\n const isSupabasePort = urlObj.port === SUPABASE_LOCAL_PORT\n const isLocal = ['localhost', '127.0.0.1', '::1', ''].includes(urlObj.hostname)\n\n if (!isLocal) return hints\n\n // Server is reachable but rejecting — suggest config fixes, not startup.\n if (error && SERVER_REACHABLE_RE.test(error)) {\n hints.push(`Check the username and password in your database URL.`)\n if (isSupabasePort) {\n hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. The default password is \"postgres\".`)\n }\n return hints\n }\n\n if (isSupabasePort) {\n hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. Run ${cmd('\"supabase start\"')} to start your local Supabase instance.`)\n }\n\n const runtime = await detectRuntime()\n if (runtime) {\n hints.push(`${bold(runtime)} detected — you can start a PostgreSQL container manually.`)\n }\n\n if (!isSupabasePort) {\n hints.push(`Start PostgreSQL manually on port ${urlObj.port || DEFAULT_PG_PORT}.`)\n }\n } catch {\n // Invalid URL — no hints\n }\n return hints\n}\n\n/**\n * Hints for a connection that was bounded rather than refused.\n *\n * These apply to any host, unlike the local-startup hints — a stalled server\n * is just as likely to be a remote one behind a dropped tunnel, which is the\n * case that motivated bounding the wait at all (issue #44).\n */\nexport function buildTimeoutHints(): string[] {\n return [\n 'The host is listening but the database did not answer.',\n 'Check the database process is running and not paused, restarting, or overloaded.',\n 'Over a VPN or tunnel, check the connection is still up.',\n `Raise the bound with ${cmd('SUPAFORGE_CONNECT_TIMEOUT')} (in seconds) if the link is simply slow.`,\n ]\n}\n\n/**\n * Pick the right hints for a failed connection.\n *\n * A timeout and a refusal need different advice, and the local-startup hints\n * are actively misleading for a remote host that stalled.\n */\nexport async function buildConnectionHints(dbUrl: string, error?: string): Promise<string[]> {\n if (error && /timed out after \\d+s/.test(error)) return buildTimeoutHints()\n return buildLocalHints(dbUrl, error)\n}\n\n// ─── Preflight class ─────────────────────────────────────────────────────────\n\ntype LogFn = (msg: string) => void\n\n/**\n * Render a transient \"in progress\" line, or clear it when passed null.\n *\n * Separate from LogFn because these lines are overwritten rather than kept:\n * on a TTY the finished result replaces them, and off a TTY they are dropped\n * entirely so piped output and CI logs stay one line per check.\n */\nexport type PendingFn = (msg: string | null) => void\n\nconst defaultPending: PendingFn = (msg) => {\n if (!process.stdout.isTTY) return\n process.stdout.write(msg === null ? '\\r\\u001b[2K' : `\\r\\u001b[2K${msg}`)\n}\n\n/** Queued database to check during run(). */\ninterface DbEntry {\n label: string\n envName: string\n dbUrl: string\n}\n\n/** Custom check callback. Return null on success, or an error string on failure. */\nexport type CustomCheckFn = () => Promise<{ error?: string; detail?: string; hints?: string[] }>\n\n/** Queued custom check. */\ninterface CustomEntry {\n label: string\n fn: CustomCheckFn\n}\n\n/**\n * Composable preflight check runner.\n *\n * Usage:\n * ```ts\n * const pre = new Preflight('Diff preflight checks', (m) => this.log(m))\n * pre.addDatabase('Source', 'local', sourceUrl)\n * pre.addDatabase('Target', 'prod', targetUrl)\n * const report = await pre.run()\n * if (!report.passed) this.error('Aborted.', { exit: 1 })\n * ```\n *\n * For commands with extra checks (e.g. clone's pg_dump compat):\n * ```ts\n * pre.addCheck('pg_dump compatibility', async () => { ... })\n * ```\n */\nexport class Preflight {\n private readonly title: string\n private readonly log: LogFn\n private readonly pending: PendingFn\n private readonly databases: DbEntry[] = []\n private readonly customs: CustomEntry[] = []\n private readonly infoLines: Array<{ label: string; value: string }> = []\n\n constructor(title: string, log: LogFn, pending: PendingFn = defaultPending) {\n this.title = title\n this.log = log\n this.pending = pending\n }\n\n /** Register a database connectivity check. */\n addDatabase(label: string, envName: string, dbUrl: string): this {\n this.databases.push({ label, envName, dbUrl })\n return this\n }\n\n /** Add an informational line to the header (displayed after database lines). */\n addInfo(label: string, value: string): this {\n this.infoLines.push({ label, value })\n return this\n }\n\n /** Register a custom check (runs after all DB connectivity checks). */\n addCheck(label: string, fn: CustomCheckFn): this {\n this.customs.push({ label, fn })\n return this\n }\n\n /** Execute all registered checks, render results, and return the report. */\n async run(): Promise<PreflightReport> {\n const entries: CheckEntry[] = []\n const log = this.log\n\n // Header\n log(`\\n ${bold(this.title)}\\n`)\n for (const db of this.databases) {\n log(` ${db.label}: ${db.envName} ${dim(`(${redactUrls(db.dbUrl)})`)}`)\n }\n for (const info of this.infoLines) {\n log(` ${info.label}: ${info.value}`)\n }\n log('')\n log(' Checks:')\n\n // Database connectivity checks\n for (const db of this.databases) {\n // Named before the wait, not after: a connection that is merely slow\n // otherwise leaves the header on screen with no clue which of the two\n // environments is holding things up (issue #44).\n // The label is already the noun — \"Database\", \"Target\", \"Source\" — so\n // appending \"database\" gave \"Database database reachable\" (issue #97).\n this.pending(` ${dim(`… connecting to ${db.label.toLowerCase()}`)}`)\n const result = await checkConnection(db.dbUrl)\n this.pending(null)\n if (result.reachable) {\n log(` ${ok('✓')} ${db.label} reachable ${dim(`(PostgreSQL ${result.version})`)}`)\n entries.push({ label: db.label, passed: true, detail: `PostgreSQL ${result.version}` })\n } else {\n log(` ${warn('✗')} ${db.label} not reachable: ${redactUrls(describeFailure(result.error))}`)\n const hints = await buildConnectionHints(db.dbUrl, result.error)\n if (hints.length > 0) {\n log(`\\n ${dim('Hints:')}`)\n for (const h of hints) log(` ${dim('•')} ${h}`)\n }\n entries.push({ label: db.label, passed: false, error: result.error, hints })\n }\n }\n\n // Custom checks\n for (const custom of this.customs) {\n this.pending(` ${dim(`… ${custom.label}`)}`)\n const result = await custom.fn()\n this.pending(null)\n if (!result.error) {\n const suffix = result.detail ? ` ${dim(result.detail)}` : ''\n log(` ${ok('✓')} ${custom.label}${suffix}`)\n entries.push({ label: custom.label, passed: true, detail: result.detail })\n } else {\n log(` ${warn('✗')} ${custom.label}: ${redactUrls(describeFailure(result.error))}`)\n if (result.hints?.length) {\n log(`\\n ${dim('Hints:')}`)\n for (const h of result.hints) log(` ${dim('•')} ${h}`)\n }\n entries.push({ label: custom.label, passed: false, error: result.error, hints: result.hints })\n }\n }\n\n const passed = entries.every(e => e.passed)\n log('')\n if (!passed) {\n log(` ${warn('Some checks failed.')} Fix the issues above first.\\n`)\n } else {\n log(` ${ok('All checks passed.')}\\n`)\n }\n\n return { passed, checks: entries }\n }\n}\n","import { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport pg from 'pg'\nimport { pgClientConfig } from './db.js'\nimport { RUNTIME_DETECT_TIMEOUT_MS, CONTAINER_RM_TIMEOUT_MS, CONTAINER_START_TIMEOUT_MS } from './constants'\n\nconst defaultExecFile = promisify(execFile)\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Injected exec function for testability. */\nexport type ExecFn = (\n cmd: string,\n args: string[],\n opts?: { timeout?: number },\n) => Promise<{ stdout: string; stderr: string }>\n\n/** Injected PostgreSQL connect function for readiness polling. */\nexport type ConnectFn = (url: string) => Promise<void>\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\n/** Default PostgreSQL image used for local containers. */\nexport const PG_IMAGE = 'docker.io/library/postgres:17'\n\n/** Default host port for the local PostgreSQL container. */\nexport const DEFAULT_LOCAL_PORT = 5432\n\n/** Default container name. */\nexport const CONTAINER_NAME = 'supaforge-local-pg'\n\n/** Default credentials for the local container. */\nexport const LOCAL_PG_USER = 'postgres'\nexport const LOCAL_PG_PASSWORD = 'postgres'\n\n/** Maximum retries when waiting for PostgreSQL readiness. */\nexport const READINESS_RETRIES = 30\n\n/** Delay between readiness checks (ms). */\nexport const READINESS_INTERVAL_MS = 2000\n\n// ─── Default implementations ────────────────────────────────────────────────\n\nasync function defaultConnectFn(url: string): Promise<void> {\n const client = new pg.Client(pgClientConfig(url))\n await client.connect()\n await client.end()\n}\n\n// ─── Container Runtime Detection ─────────────────────────────────────────────\n\nexport type ContainerRuntime = 'podman' | 'docker'\n\n/**\n * Detect the available container runtime.\n * Prefers podman (rootless, daemonless) over docker.\n * Returns null if neither is available.\n */\nexport async function detectRuntime(execFn: ExecFn = defaultExecFile): Promise<ContainerRuntime | null> {\n for (const rt of ['podman', 'docker'] as const) {\n try {\n await execFn(rt, ['--version'], { timeout: RUNTIME_DETECT_TIMEOUT_MS })\n return rt\n } catch {\n continue\n }\n }\n return null\n}\n\n// ─── Container Lifecycle ─────────────────────────────────────────────────────\n\nexport interface StartLocalPgOptions {\n /** Container runtime to use. Auto-detected if not provided. */\n runtime?: ContainerRuntime\n /** Host port to bind (default: 5432). */\n port?: number\n /** PostgreSQL password (default: 'postgres'). */\n password?: string\n /** Container name (default: 'supaforge-local-pg'). */\n name?: string\n /** PostgreSQL image (default: PG_IMAGE). */\n image?: string\n /** Injected exec function for testability. */\n execFn?: ExecFn\n /** Injected connect function for testability. */\n connectFn?: ConnectFn\n}\n\nexport interface LocalPgInfo {\n runtime: ContainerRuntime\n containerName: string\n port: number\n url: string\n}\n\n/**\n * Start a local PostgreSQL container using the detected runtime.\n *\n * Uses tmpfs for ephemeral storage (fast, no disk writes).\n * Waits for PostgreSQL to accept connections before returning.\n */\nexport async function startLocalPg(options: StartLocalPgOptions = {}): Promise<LocalPgInfo> {\n const exec = options.execFn ?? defaultExecFile\n const connect = options.connectFn ?? defaultConnectFn\n const runtime = options.runtime ?? await detectRuntime(exec)\n if (!runtime) {\n throw new Error(\n 'No container runtime found. Install Podman (recommended) or Docker.\\n' +\n ' Podman: https://podman.io/docs/installation\\n' +\n ' Docker: https://docs.docker.com/engine/install/',\n )\n }\n\n const port = options.port ?? DEFAULT_LOCAL_PORT\n const password = options.password ?? LOCAL_PG_PASSWORD\n const name = options.name ?? CONTAINER_NAME\n const image = options.image ?? PG_IMAGE\n\n // Check if container already exists and is running\n const existing = await getContainerStatus(runtime, name, exec)\n if (existing === 'running') {\n return {\n runtime,\n containerName: name,\n port,\n url: buildLocalUrl(port, password),\n }\n }\n\n // Remove stopped container with same name\n if (existing === 'stopped') {\n await exec(runtime, ['rm', '-f', name], { timeout: CONTAINER_RM_TIMEOUT_MS })\n }\n\n // Start the container\n const args = [\n 'run', '-d',\n '--name', name,\n '-p', `${port}:5432`,\n '-e', `POSTGRES_PASSWORD=${password}`,\n '-e', `POSTGRES_USER=${LOCAL_PG_USER}`,\n '--tmpfs', '/var/lib/postgresql/data',\n '--health-cmd', `pg_isready -U ${LOCAL_PG_USER}`,\n '--health-interval', '5s',\n '--health-timeout', '5s',\n '--health-retries', '20',\n '--health-start-period', '10s',\n image,\n ]\n\n try {\n await exec(runtime, args, { timeout: CONTAINER_START_TIMEOUT_MS })\n } catch (err) {\n throw new Error(\n `Failed to start PostgreSQL container via ${runtime}: ${(err as Error).message}`,\n )\n }\n\n // Wait for readiness using actual pg connection\n const url = buildLocalUrl(port, password)\n await waitForPg(url, connect)\n\n return { runtime, containerName: name, port, url }\n}\n\n/**\n * Stop and remove the local PostgreSQL container.\n */\nexport async function stopLocalPg(\n runtime?: ContainerRuntime,\n name: string = CONTAINER_NAME,\n execFn: ExecFn = defaultExecFile,\n): Promise<void> {\n const rt = runtime ?? await detectRuntime(execFn)\n if (!rt) return\n\n try {\n await execFn(rt, ['rm', '-f', name], { timeout: CONTAINER_RM_TIMEOUT_MS })\n } catch {\n // Container may not exist — ignore\n }\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nasync function getContainerStatus(\n runtime: ContainerRuntime,\n name: string,\n execFn: ExecFn,\n): Promise<'running' | 'stopped' | 'none'> {\n try {\n const { stdout } = await execFn(\n runtime,\n ['inspect', '--format', '{{.State.Running}}', name],\n { timeout: RUNTIME_DETECT_TIMEOUT_MS },\n )\n return stdout.trim() === 'true' ? 'running' : 'stopped'\n } catch {\n return 'none'\n }\n}\n\nfunction buildLocalUrl(port: number, password: string): string {\n return `postgres://${LOCAL_PG_USER}:${password}@localhost:${port}/postgres`\n}\n\n/**\n * Poll PostgreSQL until it accepts connections.\n * Uses actual pg.Client connection rather than relying on container health checks\n * (which may not work on all runtimes).\n */\nasync function waitForPg(url: string, connectFn: ConnectFn): Promise<void> {\n for (let i = 0; i < READINESS_RETRIES; i++) {\n try {\n await connectFn(url)\n return\n } catch {\n await sleep(READINESS_INTERVAL_MS)\n }\n }\n throw new Error(\n `PostgreSQL at ${url} did not become ready within ${READINESS_RETRIES * READINESS_INTERVAL_MS / 1000}s`,\n )\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n","/**\n * Persistent command run log stored at ~/.supaforge/run-log.jsonl.\n *\n * Each entry is one JSON object per line (JSONL format) recording:\n * timestamp, command, args (with URLs redacted), duration, exitStatus, error.\n *\n * Used by `supaforge report` to show recent command history.\n * Entries older than RUN_LOG_MAX_ENTRIES are pruned automatically on append.\n */\nimport { readFile, writeFile, mkdir, appendFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { redactUrls } from './utils/error.js'\nimport { RUN_LOG_MAX_ENTRIES, RUN_LOG_DIR, RUN_LOG_FILE } from './constants.js'\n\n/**\n * Per-check summary attached to diff/apply run log entries.\n * Contains only operational metadata — never SQL, table names, or data values.\n * Error strings are sanitized (URLs and file paths stripped) before storage.\n */\nexport interface RunLogCheckSummary {\n check: string\n status: string\n issueCount: number\n durationMs: number\n error?: string\n}\n\nexport interface RunLogEntry {\n timestamp: string\n command: string\n args: string[]\n durationMs: number\n exitStatus: 'success' | 'error'\n error?: string\n /** supaforge version that produced this entry */\n version?: string\n /** Populated by diff/apply: per-check status and counts, no SQL content. */\n checkSummaries?: RunLogCheckSummary[]\n}\n\n/** Full path to the run log file. */\nexport function runLogPath(): string {\n return join(homedir(), RUN_LOG_DIR, RUN_LOG_FILE)\n}\n\n/** Full path to the run log directory. */\nexport function runLogDir(): string {\n return join(homedir(), RUN_LOG_DIR)\n}\n\n/** Append a single run entry to the log. Prunes old entries if needed. */\nexport async function appendRunLog(entry: RunLogEntry): Promise<void> {\n const dir = runLogDir()\n await mkdir(dir, { recursive: true })\n const path = runLogPath()\n const line = JSON.stringify(entry) + '\\n'\n await appendFile(path, line, 'utf8')\n // Prune asynchronously — don't block command output\n pruneRunLog(path).catch(() => {})\n}\n\n/** Read all run log entries (most recent last). Returns [] if file doesn't exist. */\nexport async function readRunLog(): Promise<RunLogEntry[]> {\n try {\n const raw = await readFile(runLogPath(), 'utf8')\n return raw\n .split('\\n')\n .filter(Boolean)\n .map(line => {\n try { return JSON.parse(line) as RunLogEntry }\n catch { return null }\n })\n .filter((e): e is RunLogEntry => e !== null)\n } catch {\n return []\n }\n}\n\n/** Remove oldest entries, keeping at most RUN_LOG_MAX_ENTRIES. */\nasync function pruneRunLog(path: string): Promise<void> {\n try {\n const raw = await readFile(path, 'utf8')\n const lines = raw.split('\\n').filter(Boolean)\n if (lines.length <= RUN_LOG_MAX_ENTRIES) return\n const trimmed = lines.slice(lines.length - RUN_LOG_MAX_ENTRIES)\n await writeFile(path, trimmed.join('\\n') + '\\n', 'utf8')\n } catch {\n // Non-fatal\n }\n}\n\n/** Build a redacted args list safe for logging. Strips passwords from URLs. */\nexport function redactArgs(argv: string[]): string[] {\n return argv.map(redactUrls)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,yBAAyB;AAClC,SAAS,eAAe;;;ACDxB,OAAOA,SAAQ;;;ACAf,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,OAAO,QAAQ;AAIf,IAAM,kBAAkB,UAAU,QAAQ;AAiBnC,IAAM,WAAW;AAGjB,IAAM,qBAAqB;AAG3B,IAAM,iBAAiB;AAGvB,IAAM,gBAAgB;AACtB,IAAM,oBAAoB;AAG1B,IAAM,oBAAoB;AAG1B,IAAM,wBAAwB;AAIrC,eAAe,iBAAiB,KAA4B;AAC1D,QAAM,SAAS,IAAI,GAAG,OAAO,eAAe,GAAG,CAAC;AAChD,QAAM,OAAO,QAAQ;AACrB,QAAM,OAAO,IAAI;AACnB;AAWA,eAAsB,cAAc,SAAiB,iBAAmD;AACtG,aAAW,MAAM,CAAC,UAAU,QAAQ,GAAY;AAC9C,QAAI;AACF,YAAM,OAA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@@
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 { diffState } from './state-diff'\nimport { resolvePgDumpPath, getServerMajorVersion } 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 * 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 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: 'pg_dump not available' }\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 await runSql(psql, cloneUrl, opts.migrationSql)\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 { 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 { converged: true, residual: [], cloneName }\n const residual = await describeDifference(roundTripUrl, cloneUrl, schemas, wantRoundTripped, got)\n return 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 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/**\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 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 if (name && dropped.has(name)) 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;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AAG,QAAO;AACtC,SAAO,CAAC,OAAO,KAAK,OAAK,SAAS,CAAC,GAAG,KAAK,IAAI,CAAC;AAClD;","names":["residual","knownParameters"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/migrate.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { QueryFn } from './db.js'\nimport { pgQuery } from './db.js'\nimport type { LocalMigration } from './checks/migrations.js'\nimport { readLocalMigrations } from './checks/migrations.js'\nimport type { ReadDirFn } from './checks/migrations.js'\nimport { MIGRATIONS_SCHEMA, MIGRATIONS_TABLE } from './constants.js'\n\n// ─── Schema bootstrap ────────────────────────────────────────────────────────\n\n/** SQL to ensure the supabase_migrations schema and table exist. */\nexport const BOOTSTRAP_SQL = `\nCREATE SCHEMA IF NOT EXISTS ${MIGRATIONS_SCHEMA};\n\nCREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (\n version text PRIMARY KEY,\n statements text[],\n name text\n);\n`.trim()\n\n/** Whether the history table exists, and what the connecting role may do with it. */\ninterface HistoryAccess {\n exists: boolean\n owner: string | null\n me: string\n can_read: boolean\n can_write: boolean\n}\n\n// Read from the catalogs, which need no privilege: naming the table in a\n// schema the role has no USAGE on fails rather than answering.\nconst HISTORY_ACCESS_SQL = `\n SELECT c.oid IS NOT NULL AS exists, pg_get_userbyid(c.relowner) AS owner, current_user AS me,\n coalesce(has_schema_privilege(n.oid, 'USAGE') AND has_table_privilege(c.oid, 'SELECT'), false) AS can_read,\n coalesce(has_schema_privilege(n.oid, 'USAGE') AND has_table_privilege(c.oid, 'INSERT'), false) AS can_write\n FROM (SELECT 1) one\n LEFT JOIN pg_namespace n ON n.nspname = '${MIGRATIONS_SCHEMA}'\n LEFT JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = '${MIGRATIONS_TABLE.split('.')[1]}'\n`\n\n/** Why the role cannot use a history table that exists, and the grant that fixes it. */\nfunction noAccess(access: HistoryAccess, need: 'read' | 'write'): Error {\n return new Error(\n `${MIGRATIONS_TABLE} is owned by ${access.owner}, and ${access.me} cannot ${need} it. `\n + `As ${access.owner} or a superuser, run: GRANT USAGE ON SCHEMA ${MIGRATIONS_SCHEMA} TO ${access.me}; `\n + `GRANT SELECT, INSERT ON ${MIGRATIONS_TABLE} TO ${access.me};`)\n}\n\n/**\n * Ensure the supabase_migrations schema and table exist, and that this role\n * can record a migration in them.\n *\n * Only created when missing: `CREATE ... IF NOT EXISTS` checks the CREATE\n * privilege on the schema before it notices the table is there, and on a\n * self-hosted stack, where the platform's admin role owns the schema, that\n * failed every run with \"permission denied for schema supabase_migrations\".\n */\nexport async function ensureMigrationsTable(\n dbUrl: string,\n queryFn: QueryFn = pgQuery,\n): Promise<void> {\n const [access] = await queryFn(dbUrl, HISTORY_ACCESS_SQL) as unknown as HistoryAccess[]\n if (!access?.exists) {\n await queryFn(dbUrl, BOOTSTRAP_SQL)\n return\n }\n if (!access.can_write) throw noAccess(access, 'write')\n}\n\n// ─── Applied versions ────────────────────────────────────────────────────────\n\nconst APPLIED_SQL = `\n SELECT version FROM ${MIGRATIONS_TABLE} ORDER BY version\n`\n\n/**\n * The migration versions already applied to the target. No table yet means\n * none, so a preview reads the history without creating anything.\n */\nexport async function getAppliedVersions(\n dbUrl: string,\n queryFn: QueryFn = pgQuery,\n): Promise<Set<string>> {\n const [access] = await queryFn(dbUrl, HISTORY_ACCESS_SQL) as unknown as HistoryAccess[]\n if (access && !access.exists) return new Set()\n if (access && !access.can_read) throw noAccess(access, 'read')\n const rows = await queryFn(dbUrl, APPLIED_SQL) as { version: string }[]\n return new Set(rows.map(r => r.version))\n}\n\n// ─── Pending migrations ──────────────────────────────────────────────────────\n\nexport interface PendingMigration extends LocalMigration {\n /** Full path to the migration file. */\n path: string\n}\n\n/**\n * Determine which local migration files are pending (not yet applied in DB).\n * Returns them in sorted order.\n */\nexport async function getPendingMigrations(\n dir: string,\n applied: Set<string>,\n readDirFn?: ReadDirFn,\n): Promise<PendingMigration[]> {\n const local = await readLocalMigrations(dir, readDirFn)\n return local\n .filter(m => !applied.has(m.version))\n .map(m => ({ ...m, path: join(dir, m.filename) }))\n}\n\n// ─── Execute a single migration ──────────────────────────────────────────────\n\nexport type ReadFileFn = (path: string) => Promise<string>\n\nconst defaultReadFile: ReadFileFn = (path) => readFile(path, 'utf8')\n\nexport interface RunMigrationResult {\n version: string\n name: string\n filename: string\n durationMs: number\n}\n\n/**\n * Execute a single migration file against the target DB, then record it\n * in schema_migrations.\n */\nexport async function runMigration(\n dbUrl: string,\n migration: PendingMigration,\n queryFn: QueryFn = pgQuery,\n readFileFn: ReadFileFn = defaultReadFile,\n): Promise<RunMigrationResult> {\n const sql = await readFileFn(migration.path)\n const start = performance.now()\n\n // Execute the migration SQL\n await queryFn(dbUrl, sql)\n\n // Record in schema_migrations\n await queryFn(\n dbUrl,\n `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)\n VALUES ($1, $2, $3)\n ON CONFLICT (version) DO NOTHING`,\n [migration.version, migration.name, [sql]],\n )\n\n return {\n version: migration.version,\n name: migration.name,\n filename: migration.filename,\n durationMs: Math.round(performance.now() - start),\n }\n}\n\n/**\n * Applied versions, or an empty set when the tracking table does not exist.\n *\n * For read-only paths that must not bring the table into being as a side\n * effect of looking.\n */\nasync function readAppliedVersionsIfPresent(\n dbUrl: string,\n queryFn: QueryFn,\n): Promise<Set<string>> {\n try {\n return await getAppliedVersions(dbUrl, queryFn)\n } catch {\n return new Set()\n }\n}\n\n// ─── Baseline (mark all as applied without executing) ────────────────────────\n\nexport interface BaselineResult {\n marked: { version: string; name: string }[]\n skipped: { version: string; reason: string }[]\n}\n\n/**\n * Mark all local migration files as applied in schema_migrations\n * without actually executing their SQL.\n */\nexport async function baselineMigrations(\n dbUrl: string,\n dir: string,\n queryFn: QueryFn = pgQuery,\n readDirFn?: ReadDirFn,\n options: { dryRun?: boolean } = {},\n): Promise<BaselineResult> {\n const local = await readLocalMigrations(dir, readDirFn)\n\n // A preview writes nothing at all — not even the tracking table, which on\n // Supabase means creating a schema the project did not have. So under dryRun\n // the applied set is read defensively instead: no table yet means nothing is\n // recorded yet, which is the right answer.\n let applied: Set<string>\n if (options.dryRun) {\n applied = await readAppliedVersionsIfPresent(dbUrl, queryFn)\n } else {\n await ensureMigrationsTable(dbUrl, queryFn)\n applied = await getAppliedVersions(dbUrl, queryFn)\n }\n\n const result: BaselineResult = { marked: [], skipped: [] }\n\n for (const migration of local) {\n if (applied.has(migration.version)) {\n result.skipped.push({\n version: migration.version,\n reason: 'already recorded in schema_migrations',\n })\n continue\n }\n\n // `marked` is what *would* be recorded under dryRun, so the caller can\n // print the same list either way (issue #88).\n if (!options.dryRun) {\n await queryFn(\n dbUrl,\n `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)\n VALUES ($1, $2, '{}')\n ON CONFLICT (version) DO NOTHING`,\n [migration.version, migration.name],\n )\n }\n result.marked.push({ version: migration.version, name: migration.name })\n }\n\n return result\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,YAAY;AAWd,IAAM,gBAAgB;AAAA,8BACC,iBAAiB;AAAA;AAAA,6BAElB,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA,EAK3C,KAAK;AAaP,IAAM,qBAAqB;AAAA;AAAA;AAAA;AAAA;AAAA,6CAKkB,iBAAiB;AAAA,oEACM,iBAAiB,MAAM,GAAG,EAAE,CAAC,CAAC;AAAA;AAIlG,SAAS,SAAS,QAAuB,MAA+B;AACtE,SAAO,IAAI;AAAA,IACT,GAAG,gBAAgB,gBAAgB,OAAO,KAAK,SAAS,OAAO,EAAE,WAAW,IAAI,WACxE,OAAO,KAAK,+CAA+C,iBAAiB,OAAO,OAAO,EAAE,6BACvE,gBAAgB,OAAO,OAAO,EAAE;AAAA,EAAG;AACpE;AAWA,eAAsB,sBACpB,OACA,UAAmB,SACJ;AACf,QAAM,CAAC,MAAM,IAAI,MAAM,QAAQ,OAAO,kBAAkB;AACxD,MAA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A,EAClD;AACF;AAQA,eAAe,6BACb,OACA,SACsB;AACtB,MAAI;AACF,WAAO,MAAM,mBAAmB,OAAO,OAAO;AAAA,EAChD,QAAQ;AACN,WAAO,oBAAI,IAAI;AAAA,EACjB;AACF;AAaA,eAAsB,mBACpB,OACA,KACA,UAAmB,SACnB,WACA,UAAgC,CAAC,GACR;AACzB,QAAM,QAAQ,MAAM,oBAAoB,KAAK,SAAS;AAMtD,MAAI;AACJ,MAAI,QAAQ,QAAQ;AAClB,cAAU,MAAM,6BAA6B,OAAO,OAAO;AAAA,EAC7D,OAAO;AACL,UAAM,sBAAsB,OAAO,OAAO;AAC1C,cAAU,MAAM,mBAAmB,OAAO,OAAO;AAAA,EACnD;AAEA,QAAM,SAAyB,EAAE,QAAQ,CAAC,GAAG,SAAS,CAAC,EAAE;AAEzD,aAAW,aAAa,OAAO;AAC7B,QAAI,QAAQ,IAAI,UAAU,OAAO,GAAG;AAClC,aAAO,QAAQ,KAAK;AAAA,QAClB,SAAS,UAAU;AAAA,QACnB,QAAQ;AAAA,MACV,CAAC;AACD;AAAA,IACF;AAIA,QAAI,CAAC,QAAQ,QAAQ;AACnB,YAAM;AAAA,QACJ;AAAA,QACA,eAAe,gBAAgB;AAAA;AAAA;AAAA,QAG/B,CAAC,UAAU,SAAS,UAAU,IAAI;AAAA,MACpC;AAAA,IACF;AACA,WAAO,OAAO,KAAK,EAAE,SAAS,UAAU,SAAS,MAAM,UAAU,KAAK,CAAC;AAAA,EACzE;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/dbdiff.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 * 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 (\n combined.includes('ENOENT') ||\n combined.includes('not found') ||\n combined.includes('ERR_MODULE_NOT_FOUND') ||\n combined.includes('could not determine executable') ||\n combined.includes('404')\n ) {\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 * 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,cAAc;AACzC,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,iBAAiB;;;ACyB1B,IAAM,QAAQ;AACd,IAAM,MAAM;AASL,SAAS,WAAW,SAA2C;AACpE,MAAI,CAAC,QAAQ,SAAS,iBAAiB,EAAG,QAAO;AAEjD,QAAM,QAAsB,CAAC;AAC7B,MAAI;AAEJ,aAAW,QAAQ,QAAQ,MAAM,IAAI,GAAG;AACtC,UAAM,QAAQ,MAAM,KAAK,KAAK,QAAQ,C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