'use strict'; const fs = require('fs'); const path = require('path'); const { Pool } = require('pg'); const cfg = require('./config'); const pool = new Pool({ connectionString: cfg.databaseUrl, max: 10 }); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** Venter på databasen og kjører SQL-filer i migrations/ som ikke er kjørt før. */ async function migrate() { let client; for (let i = 1; ; i++) { try { client = await pool.connect(); break; } catch (e) { if (i >= 30) throw e; console.log(`Venter på databasen (${i}/30) …`); await sleep(2000); } } try { await client.query('CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())'); const dir = path.join(__dirname, '..', 'migrations'); const files = fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort(); const { rows } = await client.query('SELECT name FROM schema_migrations'); const done = new Set(rows.map((r) => r.name)); for (const f of files) { if (done.has(f)) continue; console.log(`Kjører migrering ${f}`); await client.query('BEGIN'); try { await client.query(fs.readFileSync(path.join(dir, f), 'utf8')); await client.query('INSERT INTO schema_migrations (name) VALUES ($1)', [f]); await client.query('COMMIT'); } catch (e) { await client.query('ROLLBACK'); throw e; } } } finally { client.release(); } } module.exports = { pool, migrate };