75 lines
2.7 KiB
TypeScript
75 lines
2.7 KiB
TypeScript
import { getPool } from './db';
|
|
|
|
// Migrations are embedded in code (not .sql files) so they are always present in
|
|
// Next.js' standalone output, which only traces files that are imported.
|
|
export const migrations: { id: string; sql: string }[] = [
|
|
{
|
|
id: '001_create_tasks',
|
|
sql: `
|
|
CREATE TABLE IF NOT EXISTS tasks (
|
|
id SERIAL PRIMARY KEY,
|
|
title VARCHAR(200) NOT NULL,
|
|
status VARCHAR(10) NOT NULL DEFAULT 'todo' CHECK (status IN ('todo','doing','done')),
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
)`,
|
|
},
|
|
{
|
|
id: '002_tasks_status_index',
|
|
sql: `CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks (status, id)`,
|
|
},
|
|
{
|
|
id: '003_tasks_assignee_notes',
|
|
sql: `
|
|
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS assignee VARCHAR(80);
|
|
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS notes TEXT`,
|
|
},
|
|
];
|
|
|
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
|
|
/** Idempotent: safe to run on every start and from several instances at once. */
|
|
export async function runMigrations(log: Pick<Console, 'log' | 'warn'> = console) {
|
|
const retries = Number(process.env.DB_CONNECT_RETRIES || 30);
|
|
const delay = Number(process.env.DB_CONNECT_RETRY_MS || 2000);
|
|
|
|
let client;
|
|
for (let i = 1; ; i++) {
|
|
try {
|
|
client = await getPool().connect();
|
|
break;
|
|
} catch (e) {
|
|
log.warn(`[migrate] DB connect attempt ${i}/${retries} failed: ${(e as { code?: string; message: string }).code || (e as Error).message}`);
|
|
if (i >= retries) throw e;
|
|
await sleep(delay);
|
|
}
|
|
}
|
|
try {
|
|
await client.query('SELECT pg_advisory_lock(727001)');
|
|
await client.query(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
id TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
|
|
const { rows } = await client.query('SELECT id FROM schema_migrations');
|
|
const done = new Set(rows.map((r) => r.id));
|
|
let ran = 0;
|
|
for (const m of migrations) {
|
|
if (done.has(m.id)) continue;
|
|
await client.query('BEGIN');
|
|
try {
|
|
for (const stmt of m.sql.split(';').map((s) => s.trim()).filter(Boolean)) await client.query(stmt);
|
|
await client.query('INSERT INTO schema_migrations (id) VALUES ($1)', [m.id]);
|
|
await client.query('COMMIT');
|
|
log.log(`[migrate] applied ${m.id}`);
|
|
ran++;
|
|
} catch (e) {
|
|
await client.query('ROLLBACK');
|
|
throw new Error(`migration ${m.id} failed: ${(e as Error).message}`);
|
|
}
|
|
}
|
|
if (!ran) log.log('[migrate] schema up to date');
|
|
return ran;
|
|
} finally {
|
|
await client.query('SELECT pg_advisory_unlock(727001)').catch(() => {});
|
|
client.release();
|
|
}
|
|
}
|