Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 40 additions & 5 deletions packages/store-postgres/scripts/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,54 @@
// 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;
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.<project ref>.
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<boolean> {
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;
}
32 changes: 20 additions & 12 deletions packages/store-postgres/src/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string[]> {
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<string[]> {
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<string[]> {
const pending = await pendingMigrations(sql);
for (const name of pending) {
const text = readFileSync(new URL(name, MIGRATIONS_DIR), 'utf8');
await sql.transaction(async (tx) => {
Expand All @@ -32,3 +29,14 @@ export async function migrate(sql: Sql): Promise<string[]> {
}
return pending;
}

async function ensureMigrationsTable(sql: Sql): Promise<void> {
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;
`);
}
14 changes: 13 additions & 1 deletion packages/store-postgres/src/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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([
Expand Down
Loading