50 lines
1.4 KiB
JavaScript
50 lines
1.4 KiB
JavaScript
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { pool } from './pool.js';
|
|
import { log } from '../log.js';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
const MIG_DIR = path.join(__dirname, 'migrations');
|
|
|
|
export async function migrateUp() {
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query(`
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
name text PRIMARY KEY,
|
|
applied_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
`);
|
|
|
|
const files = (await fs.readdir(MIG_DIR)).filter(f => f.endsWith('.sql')).sort();
|
|
const { rows } = await client.query('SELECT name FROM schema_migrations');
|
|
const applied = new Set(rows.map(r => r.name));
|
|
|
|
for (const file of files) {
|
|
if (applied.has(file)) continue;
|
|
const sql = await fs.readFile(path.join(MIG_DIR, file), 'utf8');
|
|
log.info({ migration: file }, 'applying migration');
|
|
await client.query('BEGIN');
|
|
try {
|
|
await client.query(sql);
|
|
await client.query(
|
|
'INSERT INTO schema_migrations(name) VALUES ($1)', [file]
|
|
);
|
|
await client.query('COMMIT');
|
|
} catch (err) {
|
|
await client.query('ROLLBACK');
|
|
throw err;
|
|
}
|
|
}
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
if (process.argv[2] === 'up') {
|
|
migrateUp().then(() => process.exit(0)).catch((e) => {
|
|
log.error(e); process.exit(1);
|
|
});
|
|
}
|