mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +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:
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { DatabaseLifecycle } from './database-lifecycle.service';
|
||||
|
||||
/**
|
||||
* Provides `DatabaseLifecycle`. Not global: the backup port and the app root
|
||||
* import it by name, so a partial test harness that never touches the
|
||||
* connection lifecycle does not have to supply the `MikroORM` it injects.
|
||||
*/
|
||||
@Module({ providers: [DatabaseLifecycle], exports: [DatabaseLifecycle] })
|
||||
export class DatabaseLifecycleModule {}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { closeDb, getRawConnection, registerReinitializeHook, reinitialize } from '../../db/database';
|
||||
import { resolveDbPath } from '../../db/db-path';
|
||||
import { runSchemaBootstrap } from '../../db/orm';
|
||||
|
||||
/**
|
||||
* The one owner of the core database connection's lifecycle: open, close and
|
||||
* reopen, plus the schema bootstrap that has to follow an open.
|
||||
*
|
||||
* The handle itself still lives in `db/database.ts`, because the ORM's bound
|
||||
* driver (`db/orm-driver.ts`) reads it on every connect and the test suites
|
||||
* replace that module wholesale with `vi.mock`. What moved here is the
|
||||
* decision about WHEN it opens and closes: `buildApp()` opens through this and
|
||||
* the shutdown closes through this. Nothing opens the database at import any
|
||||
* more; the first connect does, and this provider makes it explicit. The
|
||||
* restore and the demo reset still call the module's `closeDb()`/`reinitialize()`
|
||||
* themselves until they move onto `close()`/`reopen()`.
|
||||
*/
|
||||
@Injectable()
|
||||
export class DatabaseLifecycle {
|
||||
constructor(private readonly orm: MikroORM) {}
|
||||
|
||||
/**
|
||||
* The database file this process runs on, resolved the one way every caller
|
||||
* shares (`db/db-path.ts`): `TREK_DB_FILE` when set, `data/travel.db`
|
||||
* otherwise, `:memory:` under test.
|
||||
*/
|
||||
get file(): string {
|
||||
return resolveDbPath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the connection, binds the ORM to its later swaps and brings the schema
|
||||
* to head (legacy baseline, migrations, the deferred index, seeders, demo
|
||||
* seed, in that order: see `db/orm.ts`). Called once by `buildApp()`, before
|
||||
* anything reads the database.
|
||||
*/
|
||||
async open(): Promise<void> {
|
||||
// Normally a no-op: the ORM's first connect inside NestFactory.create()
|
||||
// already opened it. Said here so the boot does not depend on that.
|
||||
getRawConnection();
|
||||
registerReinitializeHook(() => this.rebindOrm());
|
||||
await runSchemaBootstrap(this.orm);
|
||||
}
|
||||
|
||||
/** Checkpoints and closes the connection. A closed connection stays closed until `reopen()`. */
|
||||
close(): void {
|
||||
closeDb();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reopens the connection after its file was replaced, rebuilds the ORM's
|
||||
* cached client around the new handle and migrates the new file forward (a
|
||||
* restored backup may predate this release).
|
||||
*/
|
||||
async reopen(): Promise<void> {
|
||||
await reinitialize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Kysely caches whatever handle it was given, so without this the ORM would
|
||||
* keep talking to the closed one. Closing and reconnecting sends the driver
|
||||
* back through `createKyselyDialect()`, which picks up the new handle.
|
||||
*/
|
||||
private async rebindOrm(): Promise<void> {
|
||||
const connection = this.orm.em.getConnection();
|
||||
// The handle is owned and closed by `db/database.ts`; the bound driver's
|
||||
// `destroy()` is a no-op (see `orm-driver.ts`), so this close never reaches it.
|
||||
await connection.close(true);
|
||||
await connection.connect();
|
||||
// No pre-migrate snapshot: the file was just unpacked from an archive that
|
||||
// is still there to go back to.
|
||||
await runSchemaBootstrap(this.orm, { snapshot: false });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user