- resend no longer demands --to or a Scribase token (it only exports JSON) - --create-project read --region from argv[0] when the flag was absent - --create-project --kind preview now creates an empty schema_only env; a snapshot failed with source_environment_missing on a new project - clerk --dry-run created users; neon --dry-run wrote into the real supabase/migrations folder - a second neon run re-added the schema step; identical steps are reused and pg_dump version banners are stripped so identical dumps stay identical - <source> --help, --version, clear errors for a missing pg_dump, a reused deleted environment name and a missing token (with the signup link) - output ends with one plain line pointing at scribase.com/migrate - README: quickstart that works today (npx from Rithub, not the unpublished npm name), real output sample, verified/not-verified split; add LICENSE Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
187 lines
8.1 KiB
JavaScript
187 lines
8.1 KiB
JavaScript
/**
|
|
* Neon -> Scribase: Neon is vanilla Postgres (a branch is just another
|
|
* connection string on the same project), so this source needs no
|
|
* control-plane-side magic. It builds the same kind of SQL
|
|
* `scribase migrate` would apply by hand — an `auth.users` data step
|
|
* (only if the source has its own GoTrue-shaped auth table), a schema step
|
|
* with generated RLS (see `lib/rls.mjs`), and a data step — writes them as
|
|
* files into `supabase/migrations/` (see `lib/migrationFiles.mjs` for why
|
|
* that folder, and why every call resends the whole thing), and submits
|
|
* through the real `client.migrations.run()` endpoint: the one HTTPS path
|
|
* that can actually write into a Scribase environment from outside its
|
|
* network (see `lib/postgres.mjs` header for why `pg_restore` cannot).
|
|
*/
|
|
|
|
import pg from 'pg';
|
|
import { dumpSchemaSql, dumpDataSql, dumpAuthUsersSql, countRowsDirect } from '../postgres.mjs';
|
|
import { introspectSchema, generateRlsStatements } from '../rls.mjs';
|
|
import { readMigrationFiles, writeMigrationFile, nextVersion, submitMigrationsDir, slugify, MIGRATIONS_DIR } from '../migrationFiles.mjs';
|
|
import { join } from 'node:path';
|
|
import { cp, mkdtemp, rm } from 'node:fs/promises';
|
|
import { existsSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
|
|
async function hasAuthUsersTable(sourceUrl) {
|
|
const client = new pg.Client({ connectionString: sourceUrl });
|
|
await client.connect();
|
|
try {
|
|
const result = await client.query(
|
|
`select 1 from information_schema.tables where table_schema = 'auth' and table_name = 'users' limit 1`,
|
|
);
|
|
return result.rows.length > 0;
|
|
} finally {
|
|
await client.end();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Adds one step file, unless the folder already holds a step with the same
|
|
* name and byte-identical SQL. Without that check a second run against the
|
|
* same source wrote the schema step again under a new version, and the
|
|
* control plane then tried to create every table twice.
|
|
*/
|
|
async function addStep(dir, name, sql) {
|
|
if (!sql || !sql.trim()) return null;
|
|
const existing = await readMigrationFiles(dir);
|
|
const same = existing.find((f) => f.name === slugify(name) && f.up === sql);
|
|
if (same) return { path: join(dir, `${same.version}_${same.name}.sql`), written: false };
|
|
const version = nextVersion(existing, existing.length);
|
|
return writeMigrationFile(dir, { version, name, sql });
|
|
}
|
|
|
|
/**
|
|
* A dry run must leave the app's real `supabase/migrations/` folder
|
|
* untouched: a leftover planned step would be picked up, stale, by the next
|
|
* real run. The plan is built in a throwaway copy instead.
|
|
*/
|
|
async function dryRunCopy(realDir) {
|
|
const scratch = await mkdtemp(join(tmpdir(), 'scribase-migrate-dry-run-'));
|
|
if (existsSync(realDir)) await cp(realDir, scratch, { recursive: true });
|
|
return scratch;
|
|
}
|
|
|
|
/**
|
|
* @param {import('scribase').ScribaseClient} client
|
|
* @param {{
|
|
* sourceUrl: string,
|
|
* destination: { organizationId: string, projectId: string, environmentId: string },
|
|
* schemas?: string[],
|
|
* migrateAuthUsers?: boolean,
|
|
* branches?: { name: string, url: string }[],
|
|
* apply?: boolean,
|
|
* migrationsDir?: string,
|
|
* onLog?: (line: string) => void,
|
|
* }} opts
|
|
*/
|
|
export async function migrateNeon(client, opts) {
|
|
const onLog = opts.onLog ?? (() => {});
|
|
const apply = opts.apply ?? true;
|
|
const schemas = opts.schemas?.length ? opts.schemas : ['public'];
|
|
const ref = opts.destination;
|
|
const realDir = opts.migrationsDir ?? join(process.cwd(), MIGRATIONS_DIR);
|
|
const dir = apply ? realDir : await dryRunCopy(realDir);
|
|
const results = {
|
|
migrationsDir: realDir,
|
|
dryRun: !apply,
|
|
...(apply ? {} : { note: 'dry run: nothing applied, nothing written to the migrations folder' }),
|
|
authUsers: null,
|
|
perSchema: [],
|
|
branches: [],
|
|
rlsDecisions: [],
|
|
};
|
|
try {
|
|
return await runSteps(client, opts, { onLog, apply, schemas, ref, dir, results });
|
|
} finally {
|
|
if (!apply) await rm(dir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
async function runSteps(client, opts, { onLog, apply, schemas, ref, dir, results }) {
|
|
|
|
if (opts.migrateAuthUsers) {
|
|
if (await hasAuthUsersTable(opts.sourceUrl)) {
|
|
onLog('exporting auth.users rows');
|
|
const { sql, count } = await dumpAuthUsersSql(opts.sourceUrl);
|
|
if (count > 0) {
|
|
await addStep(dir, 'import_auth_users', sql);
|
|
results.authUsers = await submitMigrationsDir(client, ref, dir, { apply });
|
|
onLog(`auth.users: ${count} rows, applied=${results.authUsers.applied.length > 0}`);
|
|
} else {
|
|
results.authUsers = { note: 'source has 0 auth.users rows' };
|
|
}
|
|
} else {
|
|
results.authUsers = { skipped: true, reason: 'source has no auth.users table' };
|
|
}
|
|
}
|
|
|
|
for (const schema of schemas) {
|
|
onLog(`dumping ${schema} schema`);
|
|
const schemaSource = new pg.Client({ connectionString: opts.sourceUrl });
|
|
await schemaSource.connect();
|
|
const { tables } = await introspectSchema(schemaSource, schema).finally(() => schemaSource.end());
|
|
const rls = generateRlsStatements(tables);
|
|
results.rlsDecisions.push(...rls.decisions.map((d) => ({ schema, ...d })));
|
|
|
|
const ddl = await dumpSchemaSql(opts.sourceUrl, schema, { schemaExists: schema === 'public', onLog });
|
|
const schemaSql = [ddl, rls.sql].filter(Boolean).join('\n\n');
|
|
await addStep(dir, `import_${schema}_schema`, schemaSql);
|
|
const schemaResult = await submitMigrationsDir(client, ref, dir, { apply });
|
|
onLog(`${schema} schema: ${schemaResult.lintFindings.length} lint findings, applied=${schemaResult.applied.length > 0}`);
|
|
|
|
const entry = { schema, schemaResult, dataResult: null };
|
|
if (schemaResult.lintFindings.some((f) => f.severity === 'BLOCK')) {
|
|
onLog(`${schema} schema BLOCKED by lint — data step skipped for this schema`);
|
|
results.perSchema.push(entry);
|
|
continue;
|
|
}
|
|
|
|
onLog(`dumping ${schema} data`);
|
|
const dataSql = await dumpDataSql(opts.sourceUrl, schema, { onLog });
|
|
if (dataSql.trim()) {
|
|
await addStep(dir, `import_${schema}_data`, dataSql);
|
|
entry.dataResult = await submitMigrationsDir(client, ref, dir, { apply });
|
|
onLog(`${schema} data: applied=${entry.dataResult.applied.length > 0}`);
|
|
} else {
|
|
entry.dataResult = { note: `${schema} has no rows to insert` };
|
|
}
|
|
results.perSchema.push(entry);
|
|
}
|
|
|
|
// Neon branches: each lands in its own `branch_<name>` schema so a
|
|
// dev/staging branch never collides with main's public schema.
|
|
for (const branch of opts.branches ?? []) {
|
|
const targetSchema = `branch_${branch.name.replace(/[^a-z0-9_]/gi, '_')}`;
|
|
onLog(`branch ${branch.name} -> schema ${targetSchema}`);
|
|
await addStep(dir, `${targetSchema}_create`, `create schema if not exists ${targetSchema};`);
|
|
const createResult = await submitMigrationsDir(client, ref, dir, { apply });
|
|
|
|
const ddl = await dumpSchemaSql(branch.url, 'public', { schemaExists: false, onLog });
|
|
const rewritten = ddl.replace(/\bpublic\./g, `${targetSchema}.`);
|
|
await addStep(dir, `${targetSchema}_schema`, rewritten);
|
|
const schemaResult = await submitMigrationsDir(client, ref, dir, { apply });
|
|
|
|
const dataSql = await dumpDataSql(branch.url, 'public', { onLog });
|
|
const rewrittenData = dataSql.replace(/\bpublic\./g, `${targetSchema}.`);
|
|
let dataResult = null;
|
|
if (rewrittenData.trim()) {
|
|
await addStep(dir, `${targetSchema}_data`, rewrittenData);
|
|
dataResult = await submitMigrationsDir(client, ref, dir, { apply });
|
|
}
|
|
results.branches.push({ name: branch.name, schema: targetSchema, createResult, schemaResult, dataResult });
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
/** Row-count parity: source read directly, target read through `client.database.query` (HTTP). */
|
|
export async function verifyRowCounts(client, destination, sourceUrl, tables) {
|
|
const rows = [];
|
|
for (const table of tables) {
|
|
const sourceRows = await countRowsDirect(sourceUrl, table);
|
|
const targetResult = await client.database.query(destination, `select count(*)::bigint as n from ${table}`);
|
|
const targetRows = targetResult.kind === 'rows' ? Number(targetResult.rows[0]?.n ?? 0) : null;
|
|
rows.push({ table, sourceRows, targetRows, match: sourceRows === targetRows });
|
|
}
|
|
return rows;
|
|
}
|