feat(db): run TREK on PostgreSQL

TREK runs on PostgreSQL when TREK_DB_URL is set, and on SQLite as before
otherwise: an engine port under src/db/engine, the dialect helpers under
src/db/dialect, a Postgres baseline for the migrations up to the cut,
pg_dump/pg_restore backups, a probe of every repository method against a
real server and a Postgres test lane in CI.
This commit is contained in:
Isaias Tavares
2026-11-05 01:15:21 -03:00
committed by Maurice
parent 17b47b38b9
commit 2e3762afe1
176 changed files with 6728 additions and 777 deletions
@@ -1,8 +1,8 @@
import { closeDb, getRawConnection, registerReinitializeHook, reinitialize } from '../../db/database';
import { resolveDbPath } from '../../db/db-path';
import { runSchemaBootstrap } from '../../db/orm';
import type { DatabaseEngine } from '../../db/engine';
import { DATABASE_ENGINE } from './database-engine.module';
import { MikroORM } from '@mikro-orm/core';
import { Injectable } from '@nestjs/common';
import { Inject, Injectable } from '@nestjs/common';
/**
* The one owner of the core database connection's lifecycle: open, close and
@@ -13,18 +13,21 @@ import { Injectable } from '@nestjs/common';
* replace that module wholesale with `vi.mock`. What moved here is every
* decision about WHEN it opens and closes: `buildApp()` opens through this,
* a restore and the demo reset close and reopen through this (via the backup
* port), and the shutdown closes through this. Nothing opens the database at
* import any more; the first connect does, and this provider makes it explicit.
* port), and the shutdown closes through this. The ORM's first connect is what
* actually opens the file; this provider makes that step explicit.
*
* Only the SQLite file engine exists today. The engine specific parts (the file
* path, the swap) are confined to `file` and to the backup port's SQLite
* implementation, so another engine changes this provider and that one class.
* What differs by engine (a file to open or not, how a reopen reaches the ORM)
* is the engine's (`db/engine/`), the one `DATABASE_ENGINE` provides: this
* provider decides when, the engine decides how.
*/
@Injectable()
export class DatabaseLifecycle {
private readonly reopenListeners: Array<() => Promise<void>> = [];
constructor(private readonly orm: MikroORM) {}
constructor(
private readonly orm: MikroORM,
@Inject(DATABASE_ENGINE) private readonly engine: DatabaseEngine,
) {}
/**
* The database file this process runs on, resolved the one way every caller
@@ -36,31 +39,29 @@ export class DatabaseLifecycle {
}
/**
* 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.
* Opens the connection, points the engine's reopen at the ORM and brings the
* schema to head (on SQLite: legacy baseline, migrations, the deferred index,
* seeders, demo seed, in that order, see `db/orm.ts`; on Postgres: the
* baseline or the migrations after it, then the same seeding). 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);
this.engine.open(this.orm, () => this.afterReopen());
await this.engine.schemaBootstrap(this.orm, { snapshot: true });
}
/** Checkpoints and closes the connection. A closed connection stays closed until `reopen()`. */
close(): void {
closeDb();
this.engine.close();
}
/**
* 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).
* Reopens the connection after the database was replaced. The engine points
* the ORM at the new database first; then `afterReopen` migrates it forward
* and runs the listeners.
*/
async reopen(): Promise<void> {
await reinitialize();
await this.engine.reopen();
}
/**
@@ -78,19 +79,12 @@ export class DatabaseLifecycle {
}
/**
* 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.
* What follows a reopen once the engine has pointed the ORM at the reopened
* database. No pre-migrate snapshot: the file was just unpacked from an
* archive that is still there to go back to.
*/
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 });
private async afterReopen(): Promise<void> {
await this.engine.schemaBootstrap(this.orm, { snapshot: false });
for (const listener of this.reopenListeners) await listener();
}
}