diff --git a/packages/store-postgres/scripts/migrate.ts b/packages/store-postgres/scripts/migrate.ts index ec8294b..977967f 100644 --- a/packages/store-postgres/scripts/migrate.ts +++ b/packages/store-postgres/scripts/migrate.ts @@ -1,7 +1,11 @@ -// Applies database migrations: pnpm db:migrate -// Reads DATABASE_URL from the environment or from .env.local at the repo root. +// Applies database migrations: pnpm db:migrate [--status] [--yes] +// Reads DATABASE_URL from the environment or from .env.local at the repo root. Shows which +// database that is and what it would apply, and asks before changing anything. +// --status show the target and pending migrations, change nothing +// --yes apply without asking (scripts, CI) +import { createInterface } from 'node:readline/promises'; import postgres from 'postgres'; -import { migrate } from '../src/migrate.ts'; +import { migrate, pendingMigrations } from '../src/migrate.ts'; import { fromPostgresJs } from '../src/sql.ts'; const url = process.env.DATABASE_URL; @@ -9,11 +13,42 @@ if (!url) { console.error('DATABASE_URL is not set. Add it to .env.local at the repo root.'); process.exit(1); } +const args = new Set(process.argv.slice(2)); +console.log(`Database: ${describeTarget(url)}`); const client = postgres(url, { prepare: false, max: 1, onnotice: () => {} }); try { - const applied = await migrate(fromPostgresJs(client)); - console.log(applied.length ? `applied: ${applied.join(', ')}` : 'already up to date'); + const sql = fromPostgresJs(client); + const pending = await pendingMigrations(sql); + if (pending.length === 0) { + console.log('Already up to date.'); + } else { + console.log(`Pending: ${pending.join(', ')}`); + if (!args.has('--status') && (await confirmed())) { + console.log(`Applied: ${(await migrate(sql)).join(', ')}`); + } + } } finally { await client.end(); } + +// Host, database and user, never the password. Supabase pooler users are postgres.. +function describeTarget(databaseUrl: string): string { + const u = new URL(databaseUrl); + const project = u.username.match(/^postgres\.([a-z0-9]+)$/)?.[1]; + return `${u.host}${u.pathname} as ${u.username}${project ? ` (Supabase project ${project})` : ''}`; +} + +async function confirmed(): Promise { + if (args.has('--yes')) return true; + if (!process.stdin.isTTY) { + console.log('Not applied: no terminal to ask in. Run again with --yes to apply.'); + return false; + } + const rl = createInterface({ input: process.stdin, output: process.stdout }); + const answer = await rl.question('Apply these to this database? [y/N] '); + rl.close(); + if (answer.trim().toLowerCase() === 'y') return true; + console.log('Not applied.'); + return false; +} diff --git a/packages/store-postgres/src/migrate.ts b/packages/store-postgres/src/migrate.ts index d7d3e5f..e360d79 100644 --- a/packages/store-postgres/src/migrate.ts +++ b/packages/store-postgres/src/migrate.ts @@ -3,26 +3,23 @@ import type { Sql } from './sql.ts'; const MIGRATIONS_DIR = new URL('../migrations/', import.meta.url); -// Applies migrations/*.sql in name order, each in its own transaction, skipping those already -// applied. Returns the names it applied. -export async function migrate(sql: Sql): Promise { - await sql.exec(` - create schema if not exists stackprobe; - create table if not exists stackprobe.migrations ( - name text primary key, - applied_at timestamptz not null default now() - ); - alter table stackprobe.migrations enable row level security; - `); +// The migrations in migrations/ not yet applied to this database, in the order they'd run. +export async function pendingMigrations(sql: Sql): Promise { + await ensureMigrationsTable(sql); const applied = new Set( (await sql.query<{ name: string }>('select name from stackprobe.migrations')).map( (row) => row.name, ), ); - const pending = readdirSync(MIGRATIONS_DIR) + return readdirSync(MIGRATIONS_DIR) .filter((file) => file.endsWith('.sql') && !applied.has(file)) .sort(); +} +// Applies migrations/*.sql in name order, each in its own transaction, skipping those already +// applied. Returns the names it applied. +export async function migrate(sql: Sql): Promise { + const pending = await pendingMigrations(sql); for (const name of pending) { const text = readFileSync(new URL(name, MIGRATIONS_DIR), 'utf8'); await sql.transaction(async (tx) => { @@ -32,3 +29,14 @@ export async function migrate(sql: Sql): Promise { } return pending; } + +async function ensureMigrationsTable(sql: Sql): Promise { + await sql.exec(` + create schema if not exists stackprobe; + create table if not exists stackprobe.migrations ( + name text primary key, + applied_at timestamptz not null default now() + ); + alter table stackprobe.migrations enable row level security; + `); +} diff --git a/packages/store-postgres/src/store.test.ts b/packages/store-postgres/src/store.test.ts index b5b7e69..0f03273 100644 --- a/packages/store-postgres/src/store.test.ts +++ b/packages/store-postgres/src/store.test.ts @@ -4,7 +4,7 @@ import { beforeAll, describe, expect, test } from 'vitest'; import { describeAccessStore } from '../../core/test/access-contract.ts'; import { describeStore } from '../../core/test/store-contract.ts'; import { PostgresAccessStore } from './access-store.ts'; -import { migrate } from './migrate.ts'; +import { migrate, pendingMigrations } from './migrate.ts'; import type { Sql } from './sql.ts'; import { PostgresStore } from './store.ts'; @@ -42,6 +42,18 @@ describeAccessStore( ); describe('migrate', () => { + test('lists pending migrations without applying them', async () => { + const sql = fromPGlite(new PGlite()); + expect(await pendingMigrations(sql)).toEqual([ + '0001_scans.sql', + '0002_unwrap_json_strings.sql', + '0003_access.sql', + ]); + expect(await pendingMigrations(sql)).toHaveLength(3); + await migrate(sql); + expect(await pendingMigrations(sql)).toEqual([]); + }); + test('applies each migration once', async () => { const sql = fromPGlite(new PGlite()); expect(await migrate(sql)).toEqual([