NGU-Web/server/src/db.js
Zaldimmar 2ad65cdc15 Write the site in US English
color, center, canceled, labeled, recognize and the rest, in UI
text, help text, comments, docs and names (ColorInput, QrCenter).
Migration 053 renames the two Site settings color CHECKs, whose
names are the messages the admin shows. Kept: events.status's
stored value 'cancelled' (shown as canceled), aria-labelledby,
schema.org's EventCancelled, and old migrations as they ran.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 13:24:11 -05:00

147 lines
6.1 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.
───────────────────────────────────────────────────────────── */
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;
}