NGU-Web/server/src/db.js
Zaldimmar 625329fa7c Consolidate migrations 001–023 into one baseline schema
023_schema.sql is the whole database as the 23 migrations left it:
every table in its final shape (columns added by ALTER folded into
their CREATE), its indexes, the five views, the seed rows (event
scopes, the shipped front page) and the triggers, last. The reasoning
from the old files that still applies sits next to what it explains;
the rest is in git history.

A fresh database runs it and lands at v23; one already at v23 skips
it. migrate() now treats the first file as a baseline and refuses a
database between v1 and v22 with a message saying to upgrade it on
an older release first, rather than failing halfway on CREATE TABLE.
Production is at v19, so the previous commits on this branch
(020–023) have to be deployed before this one.

Checked by building a database from the old files and one from this
file and comparing them: strictness, columns, types, defaults,
nullability, keys, foreign keys and their actions, CHECK constraints,
index definitions, view and trigger SQL, and seed rows all match.

Comments that cited migration numbers now point at the schema, and
CLAUDE.md describes the baseline and where new migrations go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 17:34:23 -05:00

162 lines
6.7 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
DATABASE
One SQLite file, opened once at boot and held for the life of
the process. Node's own sqlite module is used when it's there
(Node 24+), better-sqlite3 otherwise. Their APIs overlap enough
that everything below works against either, as long as you:
• use positional ? parameters, never named ones
• pass 0/1 for booleans, never true/false
• use tx() rather than db.transaction()
Those three rules are the whole compatibility story.
═══════════════════════════════════════════════════════════════ */
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");
/* ── Driver selection ──────────────────────────────────────── */
async function loadDriver() {
try {
const { DatabaseSync } = await import("node:sqlite");
return { Driver: DatabaseSync, name: "node:sqlite" };
} catch {
const { default: BetterSqlite3 } = await import("better-sqlite3");
return { Driver: BetterSqlite3, name: "better-sqlite3" };
}
}
/* ── 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 { Driver, name } = await loadDriver();
const db = new Driver(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 = name;
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 parameterisable, 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;
}