'use strict'; const { Pool } = require('pg'); const fs = require('fs'); const path = require('path'); if (!process.env.DATABASE_URL) { console.error('[db] DATABASE_URL is not set — refusing to start'); process.exit(1); } const pool = new Pool({ connectionString: process.env.DATABASE_URL }); async function runMigrations() { await pool.query(` CREATE TABLE IF NOT EXISTS _migrations ( filename TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now() ) `); const dir = path.join(__dirname, 'migrations'); if (!fs.existsSync(dir)) return; const files = fs.readdirSync(dir).filter(f => f.endsWith('.sql')).sort(); for (const f of files) { const { rowCount } = await pool.query('SELECT 1 FROM _migrations WHERE filename = $1', [f]); if (rowCount > 0) continue; const sql = fs.readFileSync(path.join(dir, f), 'utf8'); const client = await pool.connect(); try { await client.query('BEGIN'); await client.query(sql); await client.query('INSERT INTO _migrations (filename) VALUES ($1)', [f]); await client.query('COMMIT'); console.log(`[db] applied migration ${f}`); } catch (e) { await client.query('ROLLBACK'); throw e; } finally { client.release(); } } } module.exports = { pool, runMigrations };