'use strict'; /* * The only module that touches SQLite. Wraps node:sqlite so the driver can be swapped for better-sqlite3 by * rewriting this file. One connection, owned by the one Node process, WAL mode. * * const db = openDb('./data/game.db'); * migrate(db); * db.tx(() => { db.run('INSERT ...', a, b); return db.get('SELECT ...', id); }); * * Parameters are always positional (`?`), never interpolated. `tx` nests through savepoints. */ const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const { DatabaseSync } = require('node:sqlite'); class Db { constructor(file) { this.file = file; if (file !== ':memory:') fs.mkdirSync(path.dirname(path.resolve(file)), { recursive: true }); this.raw = new DatabaseSync(file); this.raw.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;'); this.cache = new Map(); this.depth = 0; } stmt(sql) { let s = this.cache.get(sql); if (!s) { s = this.raw.prepare(sql); this.cache.set(sql, s); } return s; } static params(p) { return p.map((v) => (v === undefined ? null : v)); } run(sql, ...p) { return this.stmt(sql).run(...Db.params(p)); } get(sql, ...p) { return this.stmt(sql).get(...Db.params(p)); } all(sql, ...p) { return this.stmt(sql).all(...Db.params(p)); } exec(sql) { this.raw.exec(sql); } // Runs fn inside a transaction (BEGIN IMMEDIATE at the top level, a savepoint when nested). Rolls back and // rethrows on any exception. fn must be synchronous: a transaction never spans an await. tx(fn) { const top = this.depth === 0; const sp = 'sp' + this.depth; this.raw.exec(top ? 'BEGIN IMMEDIATE' : 'SAVEPOINT ' + sp); this.depth++; let out; try { out = fn(); if (out && typeof out.then === 'function') throw new Error('db.tx callback must not be async'); } catch (err) { this.depth--; this.raw.exec(top ? 'ROLLBACK' : 'ROLLBACK TO ' + sp + '; RELEASE ' + sp); throw err; } this.depth--; this.raw.exec(top ? 'COMMIT' : 'RELEASE ' + sp); return out; } // Consistent snapshot into a new file (docs/DEPLOY.md: a systemd timer calls tools/admin.js backup). backup(dest) { if (fs.existsSync(dest)) throw new Error('backup target exists: ' + dest); this.raw.exec("VACUUM INTO '" + dest.replace(/'/g, "''") + "'"); } close() { this.cache.clear(); this.raw.close(); } } function openDb(file) { return new Db(file); } // Applies server/migrations/NNN_name.sql in order. Applied migrations are recorded with a checksum: editing one // after the fact is an error ("never edited after merge"). function migrate(db, dir) { dir = dir || path.join(__dirname, 'migrations'); db.exec('CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY, sha TEXT NOT NULL, applied_at INTEGER NOT NULL)'); const files = fs.readdirSync(dir).filter((f) => /^\d+.*\.sql$/.test(f)).sort(); const applied = []; for (const f of files) { const sql = fs.readFileSync(path.join(dir, f), 'utf8'); const sha = crypto.createHash('sha256').update(sql).digest('hex'); const row = db.get('SELECT sha FROM schema_migrations WHERE name = ?', f); if (row) { if (row.sha !== sha) throw new Error('migration ' + f + ' was edited after it was applied'); continue; } db.tx(() => { db.exec(sql); db.run('INSERT INTO schema_migrations (name, sha, applied_at) VALUES (?, ?, ?)', f, sha, Date.now()); }); applied.push(f); } return applied; } module.exports = { openDb, migrate, Db };