@akal/supaforge 0.0.0-stage → 0.0.31

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 (99) hide show
  1. package/README.md +350 -2
  2. package/bin/dev.js +10 -0
  3. package/bin/run.js +18 -0
  4. package/dist/base-command.d.ts +134 -0
  5. package/dist/base-command.js +9 -0
  6. package/dist/base-command.js.map +1 -0
  7. package/dist/branch-C4ndfoj5.d.ts +58 -0
  8. package/dist/chunk-4OU7KO5Y.js +13 -0
  9. package/dist/chunk-4OU7KO5Y.js.map +1 -0
  10. package/dist/chunk-5QQBTLWO.js +642 -0
  11. package/dist/chunk-5QQBTLWO.js.map +1 -0
  12. package/dist/chunk-5Z3SAIQS.js +2807 -0
  13. package/dist/chunk-5Z3SAIQS.js.map +1 -0
  14. package/dist/chunk-6WAMNZLO.js +336 -0
  15. package/dist/chunk-6WAMNZLO.js.map +1 -0
  16. package/dist/chunk-BHYLBKYD.js +156 -0
  17. package/dist/chunk-BHYLBKYD.js.map +1 -0
  18. package/dist/chunk-BLKJWDTL.js +153 -0
  19. package/dist/chunk-BLKJWDTL.js.map +1 -0
  20. package/dist/chunk-DQQ5E563.js +64 -0
  21. package/dist/chunk-DQQ5E563.js.map +1 -0
  22. package/dist/chunk-G2DIPIYU.js +94 -0
  23. package/dist/chunk-G2DIPIYU.js.map +1 -0
  24. package/dist/chunk-H5MJ5DFX.js +16 -0
  25. package/dist/chunk-H5MJ5DFX.js.map +1 -0
  26. package/dist/chunk-KIFJGON5.js +248 -0
  27. package/dist/chunk-KIFJGON5.js.map +1 -0
  28. package/dist/chunk-LQXF65MC.js +240 -0
  29. package/dist/chunk-LQXF65MC.js.map +1 -0
  30. package/dist/chunk-NXRSAVRU.js +478 -0
  31. package/dist/chunk-NXRSAVRU.js.map +1 -0
  32. package/dist/chunk-PARSNTBD.js +837 -0
  33. package/dist/chunk-PARSNTBD.js.map +1 -0
  34. package/dist/chunk-RRMI5CZD.js +376 -0
  35. package/dist/chunk-RRMI5CZD.js.map +1 -0
  36. package/dist/chunk-SF3YA42C.js +506 -0
  37. package/dist/chunk-SF3YA42C.js.map +1 -0
  38. package/dist/chunk-TQJSQLWA.js +574 -0
  39. package/dist/chunk-TQJSQLWA.js.map +1 -0
  40. package/dist/chunk-VMTBLHN2.js +122 -0
  41. package/dist/chunk-VMTBLHN2.js.map +1 -0
  42. package/dist/chunk-VOXZWQ3N.js +948 -0
  43. package/dist/chunk-VOXZWQ3N.js.map +1 -0
  44. package/dist/chunk-X6V2GGDZ.js +333 -0
  45. package/dist/chunk-X6V2GGDZ.js.map +1 -0
  46. package/dist/chunk-XMYMIURR.js +552 -0
  47. package/dist/chunk-XMYMIURR.js.map +1 -0
  48. package/dist/chunk-YVDSR4GM.js +1264 -0
  49. package/dist/chunk-YVDSR4GM.js.map +1 -0
  50. package/dist/commands/clone.d.ts +66 -0
  51. package/dist/commands/clone.js +416 -0
  52. package/dist/commands/clone.js.map +1 -0
  53. package/dist/commands/diff.d.ts +65 -0
  54. package/dist/commands/diff.js +24 -0
  55. package/dist/commands/diff.js.map +1 -0
  56. package/dist/commands/help.d.ts +32 -0
  57. package/dist/commands/help.js +36 -0
  58. package/dist/commands/help.js.map +1 -0
  59. package/dist/commands/hukam.d.ts +13 -0
  60. package/dist/commands/hukam.js +29 -0
  61. package/dist/commands/hukam.js.map +1 -0
  62. package/dist/commands/init.d.ts +47 -0
  63. package/dist/commands/init.js +388 -0
  64. package/dist/commands/init.js.map +1 -0
  65. package/dist/commands/mcp.d.ts +13 -0
  66. package/dist/commands/mcp.js +44 -0
  67. package/dist/commands/mcp.js.map +1 -0
  68. package/dist/commands/migrate/baseline.d.ts +24 -0
  69. package/dist/commands/migrate/baseline.js +69 -0
  70. package/dist/commands/migrate/baseline.js.map +1 -0
  71. package/dist/commands/migrate/create.d.ts +36 -0
  72. package/dist/commands/migrate/create.js +128 -0
  73. package/dist/commands/migrate/create.js.map +1 -0
  74. package/dist/commands/migrate/list.d.ts +23 -0
  75. package/dist/commands/migrate/list.js +110 -0
  76. package/dist/commands/migrate/list.js.map +1 -0
  77. package/dist/commands/migrate/run.d.ts +61 -0
  78. package/dist/commands/migrate/run.js +19 -0
  79. package/dist/commands/migrate/run.js.map +1 -0
  80. package/dist/commands/report.d.ts +27 -0
  81. package/dist/commands/report.js +210 -0
  82. package/dist/commands/report.js.map +1 -0
  83. package/dist/commands/restore.d.ts +26 -0
  84. package/dist/commands/restore.js +268 -0
  85. package/dist/commands/restore.js.map +1 -0
  86. package/dist/commands/snapshot.d.ts +33 -0
  87. package/dist/commands/snapshot.js +251 -0
  88. package/dist/commands/snapshot.js.map +1 -0
  89. package/dist/commands/sync.d.ts +16 -0
  90. package/dist/commands/sync.js +39 -0
  91. package/dist/commands/sync.js.map +1 -0
  92. package/dist/config-CTbeRlJk.d.ts +134 -0
  93. package/dist/help.d.ts +28 -0
  94. package/dist/help.js +64 -0
  95. package/dist/help.js.map +1 -0
  96. package/dist/index.d.ts +493 -0
  97. package/dist/index.js +147 -0
  98. package/dist/index.js.map +1 -0
  99. package/package.json +74 -4
@@ -0,0 +1 @@
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;AAGA,IAAM,UAAU,CAAC,QAAgB,SAAyB,GAAG,MAAM,IAAI,IAAI;AAS3E,SAAS,aACP,KAAe,SAAiB,OAAe,QAAiB,OAC1D;AACN,QAAM,IAAI,KAAK,MAAM,GAAG,IAAI,KAAK,KAAK;AACtC,MAAI,MAAM,EAAG,KAAI,KAAK,GAAG,OAAO,KAAK,KAAK,IAAI,CAAC,WAAM,CAAC,EAAE;AAC1D;AAGA,SAAS,aACP,KACA,MACA,QACA,OACA,OACA,SACM;AACN,QAAM,IAAI,IAAI,KAAK,UAAU,CAAC,GAAG,IAAI,OAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AACxD,QAAM,IAAI,IAAI,KAAK,SAAS,CAAC,GAAG,IAAI,OAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AAEvD,aAAW,CAAC,K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,CAAC;AAEzG,QAAM,UAAU,IAAI,IAAI,KAAK,IAAI,OAAK,EAAE,OAAO,CAAC;AAChD,SAAO,MAAM,OAAO,OAAK,CAAC,QAAQ,IAAI,CAAC,CAAC;AAC1C;AAWA,SAAS,YACP,UAAoB,UAAgC,QAAuC,WAC9E;AACb,MAAI,CAAC,YAAY,CAAC,OAAQ,QAAO,EAAE,WAAW,SAAS,WAAW,GAAG,UAAU,UAAU;AACzF,QAAM,MAAM,IAAI,IAAI,QAAQ;AAC5B,QAAM,aAAa,SAAS,OAAO,OAAK,IAAI,IAAI,CAAC,KAAK,cAAc,GAAG,MAAM,CAAC;AAC9E,QAAM,YAAY,SAAS,OAAO,OAAK,CAAC,WAAW,SAAS,CAAC,CAAC;AAC9D,SAAO,EAAE,WAAW,UAAU,WAAW,GAAG,UAAU,WAAW,YAAY,UAAU;AACzF;AAGA,IAAM,WAAmC;AAAA,EACvC,OAAO;AAAA,EACP,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,YAAY;AACd;AAGO,SAAS,cAAc,MAAc,QAAoC;AAC9E,MAAI,OAAO,SAAS,QAAQ,EAAG,QAAO;AACtC,SAAO,CAAC,OAAO,KAAK,OAAK,SAAS,CAAC,GAAG,KAAK,IAAI,CAAC;AAClD;","names":["residual","knownParameters"]}
@@ -0,0 +1,122 @@
1
+ import {
2
+ pgQuery,
3
+ readLocalMigrations
4
+ } from "./chunk-X6V2GGDZ.js";
5
+ import {
6
+ MIGRATIONS_SCHEMA,
7
+ MIGRATIONS_TABLE
8
+ } from "./chunk-6WAMNZLO.js";
9
+
10
+ // src/migrate.ts
11
+ import { readFile } from "fs/promises";
12
+ import { join } from "path";
13
+ var BOOTSTRAP_SQL = `
14
+ CREATE SCHEMA IF NOT EXISTS ${MIGRATIONS_SCHEMA};
15
+
16
+ CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (
17
+ version text PRIMARY KEY,
18
+ statements text[],
19
+ name text
20
+ );
21
+ `.trim();
22
+ var HISTORY_ACCESS_SQL = `
23
+ SELECT c.oid IS NOT NULL AS exists, pg_get_userbyid(c.relowner) AS owner, current_user AS me,
24
+ coalesce(has_schema_privilege(n.oid, 'USAGE') AND has_table_privilege(c.oid, 'SELECT'), false) AS can_read,
25
+ coalesce(has_schema_privilege(n.oid, 'USAGE') AND has_table_privilege(c.oid, 'INSERT'), false) AS can_write
26
+ FROM (SELECT 1) one
27
+ LEFT JOIN pg_namespace n ON n.nspname = '${MIGRATIONS_SCHEMA}'
28
+ LEFT JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = '${MIGRATIONS_TABLE.split(".")[1]}'
29
+ `;
30
+ function noAccess(access, need) {
31
+ return new Error(
32
+ `${MIGRATIONS_TABLE} is owned by ${access.owner}, and ${access.me} cannot ${need} it. As ${access.owner} or a superuser, run: GRANT USAGE ON SCHEMA ${MIGRATIONS_SCHEMA} TO ${access.me}; GRANT SELECT, INSERT ON ${MIGRATIONS_TABLE} TO ${access.me};`
33
+ );
34
+ }
35
+ async function ensureMigrationsTable(dbUrl, queryFn = pgQuery) {
36
+ const [access] = await queryFn(dbUrl, HISTORY_ACCESS_SQL);
37
+ if (!access?.exists) {
38
+ await queryFn(dbUrl, BOOTSTRAP_SQL);
39
+ return;
40
+ }
41
+ if (!access.can_write) throw noAccess(access, "write");
42
+ }
43
+ var APPLIED_SQL = `
44
+ SELECT version FROM ${MIGRATIONS_TABLE} ORDER BY version
45
+ `;
46
+ async function getAppliedVersions(dbUrl, queryFn = pgQuery) {
47
+ const [access] = await queryFn(dbUrl, HISTORY_ACCESS_SQL);
48
+ if (access && !access.exists) return /* @__PURE__ */ new Set();
49
+ if (access && !access.can_read) throw noAccess(access, "read");
50
+ const rows = await queryFn(dbUrl, APPLIED_SQL);
51
+ return new Set(rows.map((r) => r.version));
52
+ }
53
+ async function getPendingMigrations(dir, applied, readDirFn) {
54
+ const local = await readLocalMigrations(dir, readDirFn);
55
+ return local.filter((m) => !applied.has(m.version)).map((m) => ({ ...m, path: join(dir, m.filename) }));
56
+ }
57
+ var defaultReadFile = (path) => readFile(path, "utf8");
58
+ async function runMigration(dbUrl, migration, queryFn = pgQuery, readFileFn = defaultReadFile) {
59
+ const sql = await readFileFn(migration.path);
60
+ const start = performance.now();
61
+ await queryFn(dbUrl, sql);
62
+ await queryFn(
63
+ dbUrl,
64
+ `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)
65
+ VALUES ($1, $2, $3)
66
+ ON CONFLICT (version) DO NOTHING`,
67
+ [migration.version, migration.name, [sql]]
68
+ );
69
+ return {
70
+ version: migration.version,
71
+ name: migration.name,
72
+ filename: migration.filename,
73
+ durationMs: Math.round(performance.now() - start)
74
+ };
75
+ }
76
+ async function readAppliedVersionsIfPresent(dbUrl, queryFn) {
77
+ try {
78
+ return await getAppliedVersions(dbUrl, queryFn);
79
+ } catch {
80
+ return /* @__PURE__ */ new Set();
81
+ }
82
+ }
83
+ async function baselineMigrations(dbUrl, dir, queryFn = pgQuery, readDirFn, options = {}) {
84
+ const local = await readLocalMigrations(dir, readDirFn);
85
+ let applied;
86
+ if (options.dryRun) {
87
+ applied = await readAppliedVersionsIfPresent(dbUrl, queryFn);
88
+ } else {
89
+ await ensureMigrationsTable(dbUrl, queryFn);
90
+ applied = await getAppliedVersions(dbUrl, queryFn);
91
+ }
92
+ const result = { marked: [], skipped: [] };
93
+ for (const migration of local) {
94
+ if (applied.has(migration.version)) {
95
+ result.skipped.push({
96
+ version: migration.version,
97
+ reason: "already recorded in schema_migrations"
98
+ });
99
+ continue;
100
+ }
101
+ if (!options.dryRun) {
102
+ await queryFn(
103
+ dbUrl,
104
+ `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)
105
+ VALUES ($1, $2, '{}')
106
+ ON CONFLICT (version) DO NOTHING`,
107
+ [migration.version, migration.name]
108
+ );
109
+ }
110
+ result.marked.push({ version: migration.version, name: migration.name });
111
+ }
112
+ return result;
113
+ }
114
+
115
+ export {
116
+ ensureMigrationsTable,
117
+ getAppliedVersions,
118
+ getPendingMigrations,
119
+ runMigration,
120
+ baselineMigrations
121
+ };
122
+ //# sourceMappingURL=chunk-VMTBLHN2.js.map
@@ -0,0 +1 @@
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,MAAI,CAAC,Q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