import type { DbUser, PsqlRunner } from './local-db' import { spawnSync } from 'node:child_process' import { fileURLToPath } from 'node:url' import { bootstrapAndMigrate, psqlFailure } from './local-db' /** * Entrypoint of the capgo-setup image (selfhost/capgo-setup/Dockerfile), the one-shot job of * the self-host stack. Same steps as `bun run db:provision`, without the seed, against URLs * instead of a local container: supabase/bootstrap.sql as supabase_admin, then every pending * migration as postgres, recorded in supabase_migrations.schema_migrations. A second run * applies only migrations added since. * * DATABASE_URL postgresql://postgres:@:5432/postgres * SUPABASE_ADMIN_URL postgresql://supabase_admin:@:5432/postgres * * Two URLs, not one URL plus SET ROLE: migrationsScript runs DISCARD ALL between migrations, * which would reset the role. */ export type SetupUrls = Record const URL_HINT = 'postgresql://:@:/' function requireUrl(env: Readonly>, name: string): string { const value = env[name]?.trim() if (!value) throw new Error(`${name} is not set (${URL_HINT})`) let url: URL try { url = new URL(value) } catch { // Never echo the value: it holds the password. throw new Error(`${name} is not a valid URL (${URL_HINT})`) } if (url.protocol !== 'postgresql:' && url.protocol !== 'postgres:') throw new Error(`${name} must start with postgresql:// (${URL_HINT})`) return value } export function readSetupUrls(env: Readonly>): SetupUrls { return { postgres: requireUrl(env, 'DATABASE_URL'), supabase_admin: requireUrl(env, 'SUPABASE_ADMIN_URL'), } } function urlRunner(urls: SetupUrls): PsqlRunner { return (user, sql, label, psqlArgs) => { const res = spawnSync('psql', ['-X', '-q', '-v', 'ON_ERROR_STOP=1', '-d', urls[user], ...psqlArgs, '-f', '-'], { input: sql, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, }) if (res.error) throw new Error(`${label}: could not run psql: ${res.error.message}`) if (res.status !== 0) throw new Error(psqlFailure(label, res.stdout || '', res.stderr || '')) return res.stdout || '' } } function main(): number { try { const urls = readSetupUrls(process.env) const { applied, total } = bootstrapAndMigrate(urlRunner(urls), fileURLToPath(new URL('../supabase', import.meta.url))) console.log(`Migrations: ${applied} applied, ${total - applied} already there.`) return 0 } catch (error) { console.error(error instanceof Error ? error.message : String(error)) return 1 } } if (import.meta.main) process.exit(main())