refactor(db): type the database settings and inject one engine

The settings for the database were one flat record whose url and pool size
were meaningful only for Postgres, so every reader had to re-check the URL.
They are now a discriminated union per engine (DbEngineSettings): the
Postgres arm carries its URL and a pool size already capped at the ceiling,
and the SQLite arm carries nothing else. The env schema uses the same ceiling
constant, so the boot check and the derivation cannot drift apart.

The engine was resolved from the environment by every caller that needed it
(the lifecycle, the unit of work, the backup adapters), each building its own
instance. The engine is now provided once per container by
DatabaseEngineModule and injected everywhere, so the state an engine keeps
(Postgres's reopen hook) is the same wherever it is used. resolveEngine stays
for the MikroORM CLI config and the DI factory, and nothing else calls it.

The engine's reopen no longer carries a `reopenSwapsConnection` flag. The
engine itself decides what a reopen needs: SQLite closes and reconnects the
ORM's connection before the schema bootstrap (its handle is swapped under
Kysely's cache), and Postgres only migrates, because a restore replaces the
contents of the database the pool already reaches. The Postgres pool is never
closed on a reopen, since ending it waits for connections lent out during the
restore.

The backup ports answer every method the same way. verify() now throws a
DomainError for a refused archive on both engines, and the restore path maps
it back to the same { success: false, error, status } result, so the HTTP
response of a refused restore (status and body) is unchanged. The restore
step that swaps the database and then always reopens it is shared in
nest/backup/database-swap.ts, with the error-description helper in
nest/common, instead of two copies that could drift.
This commit is contained in:
Isaias Tavares
2026-11-05 00:56:39 -03:00
parent 1c3dc93716
commit 98533f3dbe
66 changed files with 639 additions and 351 deletions
@@ -8,6 +8,7 @@
* The real open, migrate and reopen run in tests/integration/database-lifecycle.test.ts.
*/
import { PostgresEngine } from '../../../../src/db/engine/postgres/postgres-engine';
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
import { DatabaseLifecycle } from '../../../../src/nest/database/database-lifecycle.service';
import type { MikroORM } from '@mikro-orm/core';
@@ -16,6 +17,9 @@ import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/** The settings a Postgres process would read from TREK_DB_URL, given directly rather than through the environment. */
const POSTGRES = { engine: 'postgres' as const, url: 'postgres://trek:pw@db/trek', poolMax: 10 };
const { dbMock, ormMock, calls } = vi.hoisted(() => {
const calls: string[] = [];
return {
@@ -67,7 +71,7 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-001: open() opens the connection, binds the ORM to later swaps, then brings the schema to head', async () => {
const { orm } = ormStub();
await new DatabaseLifecycle(orm).open();
await new DatabaseLifecycle(orm, new SqliteEngine()).open();
expect(calls).toEqual(['getRawConnection', 'registerReinitializeHook', 'runSchemaBootstrap:{"snapshot":true}']);
expect(ormMock.runSchemaBootstrap).toHaveBeenCalledWith(orm, { snapshot: true });
@@ -75,7 +79,7 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-002: the hook open() registers rebuilds the ORM client and migrates the new file without a pre-migrate copy', async () => {
const { orm, connection } = ormStub();
await new DatabaseLifecycle(orm).open();
await new DatabaseLifecycle(orm, new SqliteEngine()).open();
const hook = dbMock.registerReinitializeHook.mock.calls[0][0];
calls.length = 0;
@@ -87,7 +91,7 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-007: listeners registered with onReopened run after the schema bootstrap of a reopen, in order', async () => {
const { orm } = ormStub();
const lifecycle = new DatabaseLifecycle(orm);
const lifecycle = new DatabaseLifecycle(orm, new SqliteEngine());
lifecycle.onReopened(async () => {
calls.push('listener:first');
});
@@ -111,7 +115,7 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-008: a listener that throws fails the reopen, so a listener must contain its own failures', async () => {
const { orm } = ormStub();
const lifecycle = new DatabaseLifecycle(orm);
const lifecycle = new DatabaseLifecycle(orm, new SqliteEngine());
lifecycle.onReopened(async () => {
throw new Error('listener broke');
});
@@ -122,7 +126,6 @@ describe('DatabaseLifecycle', () => {
});
it('DBLIFE-009: on Postgres a reopen keeps the pool and only migrates, so it never waits on a connection lent to a job', async () => {
vi.stubEnv('TREK_DB_URL', 'postgres://trek:pw@db/trek');
const bootstrap = vi
.spyOn(PostgresEngine.prototype, 'schemaBootstrap')
.mockImplementation(async (_orm, options) => {
@@ -130,7 +133,7 @@ describe('DatabaseLifecycle', () => {
});
try {
const { orm, connection } = ormStub();
const lifecycle = new DatabaseLifecycle(orm);
const lifecycle = new DatabaseLifecycle(orm, new PostgresEngine(POSTGRES));
lifecycle.onReopened(async () => {
calls.push('listener');
});
@@ -144,12 +147,11 @@ describe('DatabaseLifecycle', () => {
expect(calls).toEqual(['schemaBootstrap:{"snapshot":false}', 'listener']);
} finally {
bootstrap.mockRestore();
vi.unstubAllEnvs();
}
});
it('DBLIFE-003: close() and reopen() go through the connection module', async () => {
const lifecycle = new DatabaseLifecycle(ormStub().orm);
const lifecycle = new DatabaseLifecycle(ormStub().orm, new SqliteEngine());
lifecycle.close();
await lifecycle.reopen();
@@ -160,7 +162,9 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-004: a reopen that fails is not swallowed', async () => {
dbMock.reinitialize.mockRejectedValueOnce(new Error('database is locked'));
await expect(new DatabaseLifecycle(ormStub().orm).reopen()).rejects.toThrow('database is locked');
await expect(new DatabaseLifecycle(ormStub().orm, new SqliteEngine()).reopen()).rejects.toThrow(
'database is locked',
);
});
describe('file', () => {
@@ -173,7 +177,7 @@ describe('DatabaseLifecycle', () => {
});
it('DBLIFE-005: is the in-memory database under test', () => {
expect(new DatabaseLifecycle(ormStub().orm).file).toBe(':memory:');
expect(new DatabaseLifecycle(ormStub().orm, new SqliteEngine()).file).toBe(':memory:');
});
it('DBLIFE-006: is TREK_DB_FILE when it is set, the one path the connection, the backup and the restore share', () => {
@@ -182,7 +186,7 @@ describe('DatabaseLifecycle', () => {
vi.stubEnv('NODE_ENV', 'production');
vi.stubEnv('TREK_DB_FILE', file);
expect(new DatabaseLifecycle(ormStub().orm).file).toBe(file);
expect(new DatabaseLifecycle(ormStub().orm, new SqliteEngine()).file).toBe(file);
});
});
});