Composes Scribase's own shipped APIs (the `scribase` SDK's imports/migrations/ database/environments resources, plus the GoTrue admin API every self-hosted Supabase migration tool already uses) rather than reinventing a dump format: - supabase: wraps the real POST /v1/imports one-call migration (Postgres, auth.users with hashes, storage). - neon: pg_dump schema+data as plain SQL, submitted through POST .../migrations (environments.connection() is internal-network-only — verified live — so this is the only path that actually reaches a Scribase env from outside); auto-generates owner-based RLS so the real migration lint's BLOCK on RLS-less public tables is satisfied without ever opening a table to every user; branches land in branch_<name> schemas. - clerk: exports users via the real Backend API, creates them via the destination's GoTrue admin API with a one-time password + reset flag (Clerk never exposes a portable hash on any plan). - resend: exports sending domains + broadcasts (as templates) to a portable JSON bundle; honest about Scribase having no write endpoint for either yet. Verified live end-to-end against a real local Supabase-shaped Postgres (Docker, GoTrue-shaped auth.users with a real bcrypt hash) and a real Scribase project (ereboslab/scribase-migrate-verify-internal): schema+RLS applied with 0 lint blocks, data row counts matched via a real HTTP query (2/2 profiles, 3/3 notes), and a real password-grant login returned a real access_token for the migrated user. Full artifacts in test-fixtures/verification-run/. docs/migrate-page.md is a ready-to-paste scribase.com/migrate page.
148 lines
6.6 KiB
JavaScript
148 lines
6.6 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, MIGRATIONS_DIR } from '../migrationFiles.mjs';
|
|
import { join } from 'node:path';
|
|
|
|
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();
|
|
}
|
|
}
|
|
|
|
async function addStep(dir, name, sql) {
|
|
if (!sql || !sql.trim()) return null;
|
|
const existing = await readMigrationFiles(dir);
|
|
const version = nextVersion(existing, existing.length);
|
|
return writeMigrationFile(dir, { version, name, sql });
|
|
}
|
|
|
|
/**
|
|
* @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 dir = opts.migrationsDir ?? join(process.cwd(), MIGRATIONS_DIR);
|
|
const results = { migrationsDir: dir, authUsers: null, perSchema: [], branches: [], rlsDecisions: [] };
|
|
|
|
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;
|
|
}
|