import { readFile, readdir } from 'node:fs/promises'; import path from 'node:path'; import pg from 'pg'; const direction = process.argv[2] === 'down' ? 'down' : 'up'; const connectionString = process.env.DATABASE_URL; if (!connectionString) throw new Error('DATABASE_URL is required'); const files = (await readdir('migrations')).filter((name) => name.endsWith(`.${direction}.sql`)).sort(); if (direction === 'down') files.reverse(); const client = new pg.Client({ connectionString }); await client.connect(); try { for (const file of files) { const sql = await readFile(path.join('migrations', file), 'utf8'); await client.query('BEGIN'); try { await client.query(sql); await client.query('COMMIT'); console.log(`applied ${file}`); } catch (error) { await client.query('ROLLBACK'); throw error; } } } finally { await client.end(); }