mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 08:00:06 +00:00
refactor(db): open the database through a DatabaseLifecycle provider
db/database.ts opened the connection as a side effect of being imported, so the moment anything reached it the database was open. index.ts had to defer loading the app until a first-boot restore was done, and nothing in the container decided when the connection opened or closed. The module now opens the connection on first use and opens nothing at import. A connection closed on purpose (a restore, the shutdown) stays closed until it is reopened, as before. The new DatabaseLifecycle provider owns the decisions: buildApp() opens through it, which also binds the ORM to later swaps (the hook attachOrm used to register) and runs the schema bootstrap in the same order as before, and the shutdown closes through it. Its file property is the one resolved database path. The module keeps every export, so the test suites that replace it with vi.mock keep working; buildDbMock gains the new openDb.
This commit is contained in:
+53
-40
@@ -6,49 +6,57 @@ import { readSchemaSnapshot } from './schema-snapshot';
|
||||
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
// In test mode each vitest worker gets an isolated in-memory DB so that
|
||||
// parallel forks can't race on the same file or share migration state.
|
||||
const isTest = readEnv().app.isTest;
|
||||
const dbPath = resolveDbPath();
|
||||
|
||||
let _db: Database.Database | null = null;
|
||||
/**
|
||||
* Set by `closeDb()`, cleared by `openDb()`. A handle that was never opened is
|
||||
* opened on first use; one that was closed on purpose (a restore swapping the
|
||||
* file, the shutdown) stays closed until somebody reopens it, so nothing can
|
||||
* quietly reconnect to a file that is being replaced.
|
||||
*/
|
||||
let closedOnPurpose = false;
|
||||
|
||||
/**
|
||||
* Opens the connection and applies the pragmas. It deliberately does NOT build
|
||||
* the schema: migrations and seeding are MikroORM's job now and run from
|
||||
* `db/orm.ts` during `buildApp()`, because the migrator is async and this
|
||||
* function is called at module load.
|
||||
* the schema: migrations and seeding are MikroORM's job and run from
|
||||
* `db/orm.ts` when `DatabaseLifecycle.open()` (`nest/database/`) is called by
|
||||
* `buildApp()`, because the migrator is async.
|
||||
*
|
||||
* The one exception is test mode, where there is no `buildApp()` to hook into
|
||||
* for the handful of suites that use this singleton directly. Those open a copy
|
||||
* of a schema snapshot the vitest global setup migrated once for the whole run.
|
||||
* Nothing calls this at import any more. The first reader opens it: in
|
||||
* production that is the ORM's first connect inside `NestFactory.create()`,
|
||||
* which is still after `index.ts` ran a first-boot restore. Opening an open
|
||||
* connection is a no-op.
|
||||
*
|
||||
* In test mode there is no `buildApp()` for the handful of suites that use this
|
||||
* singleton directly, so those open a copy of a schema snapshot the vitest
|
||||
* global setup migrated once for the whole run.
|
||||
*/
|
||||
function initDb(): void {
|
||||
if (_db) {
|
||||
try {
|
||||
_db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
|
||||
} catch (e) {}
|
||||
try {
|
||||
_db.close();
|
||||
} catch (e) {}
|
||||
_db = null;
|
||||
}
|
||||
|
||||
const snapshot = isTest ? readSchemaSnapshot() : null;
|
||||
_db = openDatabase(snapshot ?? dbPath);
|
||||
function openDb(): void {
|
||||
if (_db) return;
|
||||
// Resolved here rather than at import, so loading the module touches neither
|
||||
// the environment nor the data directory.
|
||||
const dbPath = resolveDbPath();
|
||||
const snapshot = readEnv().app.isTest ? readSchemaSnapshot() : null;
|
||||
const handle = openDatabase(snapshot ?? dbPath);
|
||||
// Ahead of the journal switch now: changing journal_mode needs an exclusive
|
||||
// lock, which a sibling process (reset-admin, the rotation script) may hold.
|
||||
_db.exec('PRAGMA busy_timeout = 5000');
|
||||
const durability = applyDurabilityPragmas(_db);
|
||||
_db.exec('PRAGMA foreign_keys = ON');
|
||||
// Reported so an operator can see whether their setting took — the test DB is
|
||||
handle.exec('PRAGMA busy_timeout = 5000');
|
||||
const durability = applyDurabilityPragmas(handle);
|
||||
handle.exec('PRAGMA foreign_keys = ON');
|
||||
_db = handle;
|
||||
closedOnPurpose = false;
|
||||
// Reported so an operator can see whether their setting took. The test DB is
|
||||
// :memory: and has no journal file, so there is nothing to report there.
|
||||
if (dbPath !== ':memory:') {
|
||||
console.log(`[DB] journal_mode=${durability.journalMode}, synchronous=${durability.synchronous}`);
|
||||
}
|
||||
}
|
||||
|
||||
initDb();
|
||||
/** The open handle, opening it on first use. Throws while it is closed on purpose. */
|
||||
function current(): Database.Database {
|
||||
if (!_db && !closedOnPurpose) openDb();
|
||||
if (!_db) throw new Error('Database connection is not available (restore in progress?)');
|
||||
return _db;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live better-sqlite3 handle, for the MikroORM dialect in `orm-driver.ts`.
|
||||
@@ -58,8 +66,7 @@ initDb();
|
||||
* The driver calls this on every connect so it always binds the current handle.
|
||||
*/
|
||||
function getRawConnection(): Database.Database {
|
||||
if (!_db) throw new Error('Database connection is not available (restore in progress?)');
|
||||
return _db;
|
||||
return current();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,12 +87,12 @@ function getRawConnection(): Database.Database {
|
||||
*/
|
||||
const db = new Proxy({} as Database.Database, {
|
||||
get(_, prop: string | symbol) {
|
||||
if (!_db) throw new Error('Database connection is not available (restore in progress?)');
|
||||
const val = (_db as unknown as Record<string | symbol, unknown>)[prop];
|
||||
return typeof val === 'function' ? val.bind(_db) : val;
|
||||
const handle = current();
|
||||
const val = (handle as unknown as Record<string | symbol, unknown>)[prop];
|
||||
return typeof val === 'function' ? val.bind(handle) : val;
|
||||
},
|
||||
set(_, prop: string | symbol, val: unknown) {
|
||||
(_db as unknown as Record<string | symbol, unknown>)[prop] = val;
|
||||
(current() as unknown as Record<string | symbol, unknown>)[prop] = val;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
@@ -119,8 +126,9 @@ async function runDemoSeed(): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets `db/orm.ts` rebuild the ORM's connection when this module swaps handles,
|
||||
* without this module importing the ORM (which imports this module back).
|
||||
* Lets `DatabaseLifecycle` (`nest/database/`) rebuild the ORM's connection when
|
||||
* this module swaps handles, without this module importing the ORM (which
|
||||
* imports this module back).
|
||||
*/
|
||||
let onReinitialize: (() => Promise<void>) | null = null;
|
||||
function registerReinitializeHook(hook: () => Promise<void>): void {
|
||||
@@ -136,6 +144,7 @@ function closeDb(): void {
|
||||
_db.close();
|
||||
} catch (e) {}
|
||||
_db = null;
|
||||
closedOnPurpose = true;
|
||||
console.log('[DB] Database connection closed');
|
||||
}
|
||||
}
|
||||
@@ -144,13 +153,17 @@ function closeDb(): void {
|
||||
* Reopens the connection after a restore has swapped the file underneath us.
|
||||
*
|
||||
* Async now, because bringing a restored backup up to date means running the
|
||||
* migrations, and the hook also has to rebuild the ORM's Kysely client — it
|
||||
* migrations, and the hook also has to rebuild the ORM's Kysely client: it
|
||||
* cached the handle this function is about to replace.
|
||||
*
|
||||
* Production code reaches this through `DatabaseLifecycle.reopen()`; the export
|
||||
* stays for the suites that drive the swap directly and for the mock factories
|
||||
* that stub it.
|
||||
*/
|
||||
async function reinitialize(): Promise<void> {
|
||||
console.log('[DB] Reinitializing database connection after restore...');
|
||||
if (_db) closeDb();
|
||||
initDb();
|
||||
openDb();
|
||||
if (onReinitialize) await onReinitialize();
|
||||
console.log('[DB] Database reinitialized successfully');
|
||||
}
|
||||
@@ -167,4 +180,4 @@ async function reinitialize(): Promise<void> {
|
||||
// exported — see its own docstring above for why (~190 test files' static
|
||||
// typecheck, not a production `src/` need).
|
||||
|
||||
export { db, closeDb, reinitialize, getRawConnection, registerReinitializeHook, runDemoSeed };
|
||||
export { db, openDb, closeDb, reinitialize, getRawConnection, registerReinitializeHook, runDemoSeed };
|
||||
|
||||
Reference in New Issue
Block a user