NGU-Web/server/src/db.js
Zaldimmar 635dd21083 Consolidate migrations 023 to 066 into one baseline plus a minimal seed
066_schema.sql is generated from the live v66 schema (checked identical
to the old migrations' result: every object, every table's columns);
066_seed.sql holds only what pages need: the single rows, event scopes,
home sections, site pages and their sections, the Musicians tag. Sample
content (hero words, paths, stats, the Organization address) is no
longer seeded. Both share version 66, so a database at v66 skips them;
one below v66 is refused and has to be brought up by 33be618 first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:01:55 -05:00

150 lines
6.3 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
DATABASE
One SQLite file, opened once at boot and held for the life of
the process, through Node's own node:sqlite (Node 22.13+).
House rules:
• use positional ? parameters, never named ones
• pass 0/1 for booleans, never true/false
• use tx(): node:sqlite has no db.transaction()
═══════════════════════════════════════════════════════════════ */
import { readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const HERE = dirname(fileURLToPath(import.meta.url));
const MIGRATIONS_DIR = join(HERE, "migrations");
/* ── Open ──────────────────────────────────────────────────────
WAL readers never block the writer, which matters the
moment a feedback POST lands mid page-load
NORMAL fsync on checkpoint rather than every commit; safe
under WAL, and much faster
busy wait rather than throw if something else holds the
write lock (a backup, usually)
───────────────────────────────────────────────────────────── */
export async function openDatabase(path) {
const { DatabaseSync } = await import("node:sqlite");
const db = new DatabaseSync(path);
db.exec("PRAGMA journal_mode = WAL");
db.exec("PRAGMA foreign_keys = ON");
db.exec("PRAGMA synchronous = NORMAL");
db.exec("PRAGMA busy_timeout = 5000");
db.driverName = "node:sqlite";
return db;
}
/* ── Transactions ──────────────────────────────────────────────
node:sqlite has no db.transaction(), so do it by hand. Runs
fn() and commits, or rolls back and rethrows.
───────────────────────────────────────────────────────────── */
export function tx(db, fn) {
db.exec("BEGIN");
try {
const result = fn();
db.exec("COMMIT");
return result;
} catch (err) {
try {
db.exec("ROLLBACK");
} catch {
/* already rolled back */
}
throw err;
}
}
/* ── Migrations ────────────────────────────────────────────────
Files are NNN_name.sql. The leading number is the version.
PRAGMA user_version tracks how far we've got, so there's no
bookkeeping table and no ordering ambiguity.
Migrations only ever go forward. To undo something, write a
new migration.
Foreign keys are off while migrations run, the recipe from
the SQLite docs for changing a table's shape. PRAGMA
foreign_keys is a no-op inside a transaction, so it has to be
set here, around the per-file transactions, rather than in
the file. With it on, rebuilding a table something references
(drop the old one, rename the new one into place) either
cascades into the children or fails the commit. Instead each
file ends with a foreign_key_check, and any orphan it leaves
rolls that file back.
The first file is the baseline: the whole schema as of its
version, consolidated from the migrations before it. It only
ever runs on an empty database. One stuck between v1 and the
baseline was built by those older files and has to be brought
up by a release that still has them; running the baseline over
it would fail halfway on CREATE TABLE, so this refuses first.
The baseline's seed shares its version (066_schema.sql, then
066_seed.sql): `current` is read once, so an empty database
runs both and one already at that version skips both.
───────────────────────────────────────────────────────────── */
export function migrate(db, { log = console.log } = {}) {
const current = db.prepare("PRAGMA user_version").get().user_version;
const files = readdirSync(MIGRATIONS_DIR)
.filter((f) => f.endsWith(".sql"))
.sort();
const baseline = files.length > 0 ? Number.parseInt(files[0].slice(0, 3), 10) : 0;
if (current > 0 && current < baseline) {
throw new Error(
`Database is at schema v${current}, older than the v${baseline} baseline ` +
`(${files[0]}). Upgrade it to v${baseline} with a release from before the ` +
`migrations were consolidated, then run this one.`,
);
}
let applied = 0;
const enforced = db.prepare("PRAGMA foreign_keys").get().foreign_keys;
db.exec("PRAGMA foreign_keys = OFF");
try {
for (const file of files) {
const version = Number.parseInt(file.slice(0, 3), 10);
if (!Number.isInteger(version) || version < 1) {
throw new Error(`Migration "${file}" must start with a number, e.g. 001_`);
}
if (version <= current) continue;
const sql = readFileSync(join(MIGRATIONS_DIR, file), "utf8");
tx(db, () => {
db.exec(sql);
const orphans = db.prepare("PRAGMA foreign_key_check").all();
if (orphans.length > 0) {
const where = orphans
.slice(0, 5)
.map((o) => `${o.table} row ${o.rowid} → ${o.parent}`)
.join(", ");
throw new Error(`${file} leaves ${orphans.length} foreign key violation(s): ${where}`);
}
// Not parameterizable, but version is a validated integer.
db.exec(`PRAGMA user_version = ${version}`);
});
log(`migrated → ${file}`);
applied += 1;
}
} finally {
if (enforced) db.exec("PRAGMA foreign_keys = ON");
}
const final = db.prepare("PRAGMA user_version").get().user_version;
if (applied === 0) log(`schema up to date (v${final})`);
return final;
}