fertig-classic-games/server/db/migrate.js

44 lines
1.2 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import db from './index.js';
import config from '../config.js';
db.exec(`
CREATE TABLE IF NOT EXISTS schema_migrations (
name TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
);
`);
const applied = new Set(
db.prepare('SELECT name FROM schema_migrations').all().map((r) => r.name),
);
const files = fs
.readdirSync(config.db.migrationsDir)
.filter((f) => f.endsWith('.sql'))
.sort();
let ran = 0;
for (const file of files) {
if (applied.has(file)) continue;
const sql = fs.readFileSync(path.join(config.db.migrationsDir, file), 'utf8');
// Disable FK enforcement for the duration of the migration so table-recreation
// migrations can drop and rebuild tables that have FK dependents.
db.pragma('foreign_keys = OFF');
try {
const tx = db.transaction(() => {
db.exec(sql);
db.prepare('INSERT INTO schema_migrations (name) VALUES (?)').run(file);
});
tx();
} finally {
db.pragma('foreign_keys = ON');
}
console.log(`[migrate] applied ${file}`);
ran += 1;
}
if (ran === 0) console.log('[migrate] nothing to do');
else console.log(`[migrate] applied ${ran} migration(s)`);