/** * What shape is this database in? * * The app applies pending migrations at boot and never applies one twice. The gap * is the other direction: a build older than its database finds nothing to do and * serves words through a shape it does not know. Every migration so far only * adds a column or a table, so that works by luck. * * The module reads a database another process may own, so it writes nothing and * reports a failure instead of throwing. Plain JavaScript because `server.js` * loads it before the app's module graph. */ import { existsSync, readdirSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { DatabaseSync } from 'node:sqlite'; /** * Accepts `file:` and a bare path, as `src/lib/server/db/index.ts` does for the * app. */ export function resolveDatabasePath(raw) { if (!raw) return null; const withoutScheme = raw.startsWith('file:') ? raw.slice('file:'.length) : raw; return resolve(withoutScheme); } /** * The migrations this build ships, in the order drizzle applies them. A folder * counts only when it holds the `migration.sql` the migrator reads; an empty list * means the folder is missing, which the caller must read as "cannot tell". */ export function readLocalMigrations(folder) { try { return readdirSync(folder) .filter((name) => existsSync(join(folder, name, 'migration.sql'))) .sort(); } catch { return []; } } /** * `newerThanBuild` stays false when the migrations folder cannot be read: a * check that cannot run must never stop an instance. */ export function readDbState({ databasePath, migrationsFolder }) { const local = readLocalMigrations(migrationsFolder); // The shape lives in `db-state.d.mts`, the contract every importer is checked // against. const state = { databasePath: databasePath ?? null, created: false, applied: [], local, newerThanBuild: false, version: null, openedAt: null, error: null }; if (!databasePath || !existsSync(databasePath)) return state; state.created = true; let db; try { // Opened read-write on purpose: a read-only connection to a WAL database // needs the shared memory file beside it, and a restore removes that file. // Nothing here writes. db = new DatabaseSync(databasePath); } catch (error) { state.error = messageOf(error); return state; } try { const rows = db.prepare('select name from __drizzle_migrations order by id').all(); state.applied = rows.map((row) => row.name).filter((name) => typeof name === 'string'); } catch (error) { // The table is missing. Another migration tool wrote this database, or no // tool did. state.error = messageOf(error); } try { const row = db .prepare('select last_version, last_opened_at from instance_setting where id = 1') .get(); if (row) { state.version = typeof row.last_version === 'string' ? row.last_version : null; state.openedAt = typeof row.last_opened_at === 'number' ? new Date(row.last_opened_at).toISOString() : null; } } catch { // A database from before these columns existed. The migration level above is // the answer that matters; the version is the friendly half. } db.close(); const shipped = new Set(local); state.newerThanBuild = local.length > 0 && state.applied.some((name) => !shipped.has(name)); return state; } export function unexpectedMigrations(state) { const shipped = new Set(state.local); return state.applied.filter((name) => !shipped.has(name)); } /** * One block of text, not a log line per fact: this is the whole of what an * operator sees when a rollback goes wrong. */ export function formatRefusal(state, build) { if (!state.newerThanBuild) return null; const unknown = unexpectedMigrations(state); const rows = [ ['database', state.databasePath ?? '(unknown)'], ['this build', describe(build)], ['last opened by', state.version ?? '(not recorded)'], ['newer migrations', unknown.join(', ')] ]; return [ 'fablewright: this build is older than the database it was given.', '', ...rows.map(([label, value]) => ` ${label.padEnd(18)}${value}`), '', 'Restore the database backup taken before the upgrade, then start the version', 'that took it. To start anyway, set FABLEWRIGHT_ALLOW_NEWER_SCHEMA=1.' ].join('\n'); } /** One line for the boot log when the operator overrode the check. */ export function formatOverrideWarning(state, build) { return [ `fablewright: FABLEWRIGHT_ALLOW_NEWER_SCHEMA=1, so ${describe(build)} will use a database`, `last opened by ${state.version ?? '(an unrecorded build)'}. Words written now may be unreadable.` ].join(' '); } function describe(build) { // A build that cannot name its commit says so by omission, rather than print // "unknown" where an operator expects a revision. return build.commit && build.commit !== 'unknown' ? `${build.version} (${build.commit})` : build.version; } function messageOf(error) { return error instanceof Error ? error.message : String(error); }