37 lines
1.1 KiB
JavaScript
37 lines
1.1 KiB
JavaScript
const path = require('path');
|
|
const fs = require('fs');
|
|
const Database = require('better-sqlite3');
|
|
|
|
const dbPath = process.env.DB_PATH || path.join(__dirname, '..', 'tunes.db');
|
|
const db = new Database(dbPath);
|
|
|
|
db.pragma('journal_mode = WAL');
|
|
db.pragma('foreign_keys = ON');
|
|
|
|
function runMigrations() {
|
|
db.exec(`CREATE TABLE IF NOT EXISTS _migrations (
|
|
name TEXT PRIMARY KEY,
|
|
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
)`);
|
|
|
|
const dir = path.join(__dirname, 'migrations');
|
|
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort();
|
|
const applied = new Set(
|
|
db.prepare('SELECT name FROM _migrations').all().map((r) => r.name)
|
|
);
|
|
|
|
const insert = db.prepare('INSERT INTO _migrations (name) VALUES (?)');
|
|
for (const file of files) {
|
|
if (applied.has(file)) continue;
|
|
const sql = fs.readFileSync(path.join(dir, file), 'utf8');
|
|
const tx = db.transaction(() => {
|
|
db.exec(sql);
|
|
insert.run(file);
|
|
});
|
|
tx();
|
|
console.log(`[db] applied migration ${file}`);
|
|
}
|
|
}
|
|
|
|
module.exports = { db, runMigrations };
|