import 'dotenv/config'; import { readFile, readdir } from 'node:fs/promises'; import { Pool } from 'pg'; if (!process.env.DATABASE_URL) throw new Error('Configura DATABASE_URL antes de ejecutar las migraciones.'); const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { await client.query('BEGIN'); await client.query('SELECT pg_advisory_xact_lock(188413091)'); await client.query( 'CREATE TABLE IF NOT EXISTS schema_migrations(name text PRIMARY KEY,applied_at timestamptz NOT NULL DEFAULT now())', ); const applied = new Set( (await client.query('SELECT name FROM schema_migrations')).rows.map( (r) => r.name, ), ); const files = (await readdir(new URL('../db/', import.meta.url))) .filter((f) => f.endsWith('.sql')) .sort(); for (const name of files) if (!applied.has(name)) { await client.query( await readFile(new URL(`../db/${name}`, import.meta.url), 'utf8'), ); await client.query('INSERT INTO schema_migrations(name) VALUES($1)', [ name, ]); console.log(`Migración aplicada: ${name}`); } await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); throw e; } finally { client.release(); await pool.end(); }