mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
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:
@@ -1,4 +1,5 @@
|
||||
import { openDatabase } from '../../../src/db/connection';
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { Trips } from '../../../src/db/entities/Trips.entity';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
@@ -147,7 +148,19 @@ async function deleteTripAndWatchTempFiles(db: Database.Database): Promise<{
|
||||
|
||||
const none = undefined as never;
|
||||
try {
|
||||
const trips = new TripsService(none, none, none, none, none, none, none, none, new UnitOfWork(t.em), t.em, none);
|
||||
const trips = new TripsService(
|
||||
none,
|
||||
none,
|
||||
none,
|
||||
none,
|
||||
none,
|
||||
none,
|
||||
none,
|
||||
none,
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
t.em,
|
||||
none,
|
||||
);
|
||||
await trips.remove(trip.id, user.id, 'user');
|
||||
return {
|
||||
tempFiles: [...seen],
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { deriveDb } from '../../../../src/app-config/derive';
|
||||
import { buildOrmConfig, resolveEngine } from '../../../../src/db/engine';
|
||||
import { TrekPostgreSqlDriver } from '../../../../src/db/engine/postgres/postgres-driver';
|
||||
import { sslOptionFor } from '../../../../src/db/engine/postgres/postgres-engine';
|
||||
import { sslOptionFor } from '../../../../src/db/engine/postgres/ssl';
|
||||
import { redactUrl } from '../../../../src/db/engine/redact-url';
|
||||
import type { AnyOrm } from '../../../../src/db/orm';
|
||||
import { SharedSqliteDriver } from '../../../../src/db/orm-driver';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
@@ -112,7 +113,8 @@ describe('buildOrmConfig', () => {
|
||||
const engine = resolveEngine(deriveDb({ TREK_DB_URL: PG_URL }));
|
||||
await expect(engine.reopen()).rejects.toThrow(/reopened before it was opened/);
|
||||
const onReopened = vi.fn(async () => undefined);
|
||||
expect(() => engine.open(onReopened)).not.toThrow();
|
||||
const orm = {} as unknown as AnyOrm;
|
||||
expect(() => engine.open(orm, onReopened)).not.toThrow();
|
||||
expect(() => engine.close()).not.toThrow();
|
||||
await engine.reopen();
|
||||
expect(onReopened).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -44,7 +44,7 @@ const migrator = () => orm.config.getExtension('@mikro-orm/migrator') as Migrato
|
||||
function envWith(db: Partial<AppEnv['db']>, isTest = false): () => AppEnv {
|
||||
return () => {
|
||||
const env = readEnv();
|
||||
return { ...env, app: { ...env.app, isTest }, db: { ...env.db, ...db } };
|
||||
return { ...env, app: { ...env.app, isTest }, db: { ...env.db, ...db } as AppEnv['db'] };
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
* username)` — unlike `AssignmentsService.getParticipants` (AS15) — see the
|
||||
* repository's own docstring.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AssignmentParticipants } from '../../../../src/db/entities/AssignmentParticipants.entity';
|
||||
import { Users } from '../../../../src/db/entities/Users.entity';
|
||||
import type { AssignmentParticipantsRepository } from '../../../../src/db/repositories/AssignmentParticipants.repository';
|
||||
@@ -27,7 +28,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
participants = t.repo(AssignmentParticipants);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* assignment-with-place projection contract (built here, Task 3 consumes it
|
||||
* unchanged for AS1/AS3).
|
||||
*/
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { DayAccommodations } from '../../../../src/db/entities/DayAccommodations.entity';
|
||||
import { DayAssignments } from '../../../../src/db/entities/DayAssignments.entity';
|
||||
import { Places } from '../../../../src/db/entities/Places.entity';
|
||||
@@ -35,7 +36,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
assignments = t.repo(DayAssignments);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { InviteTokens } from '../../../../src/db/entities/InviteTokens.entity';
|
||||
import type { InviteTokensRepository } from '../../../../src/db/repositories/InviteTokens.repository';
|
||||
import { withRequestContext } from '../../../../src/nest/database/request-context';
|
||||
@@ -227,7 +228,7 @@ describe('InviteTokensRepository', () => {
|
||||
it('INVREPO-017: incrementUsedCount inside uow.transactional is not discarded by a stale entity read earlier under a different projection', async () => {
|
||||
const { user: admin } = createUser(testDb, { username: 'invrepo-017-admin' });
|
||||
const invite = createInviteToken(testDb, { token: 'invrepo-017', max_uses: 5, created_by: admin.id });
|
||||
const uow = new UnitOfWork(t.em);
|
||||
const uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
|
||||
await withRequestContext(t.orm, async () => {
|
||||
// Projection A — wide, full row, carries used_count.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { McpTokens } from '../../../../src/db/entities/McpTokens.entity';
|
||||
import type { McpTokensRepository } from '../../../../src/db/repositories/McpTokens.repository';
|
||||
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
|
||||
@@ -449,7 +450,7 @@ describe('McpTokensRepository', () => {
|
||||
// read, nativeUpdate, flush, still correct — is still worth pinning.
|
||||
const { user } = createUser(testDb);
|
||||
const created = createMcpToken(testDb, user.id, { name: 'stays-original' });
|
||||
const uow = new UnitOfWork(t.em);
|
||||
const uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
|
||||
await uow.transactional(async () => {
|
||||
const basic = await tokens.findBasic(created.id);
|
||||
@@ -516,7 +517,7 @@ describe('McpTokensRepository', () => {
|
||||
it('MCPTOKREPO-023: projection A then projection B then a nativeUpdate on an A-only column, inside uow.transactional — the nativeUpdate survives the closing flush', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const created = createMcpToken(testDb, user.id, { name: 'stays-original', scope_mode: 'all' });
|
||||
const uow = new UnitOfWork(t.em);
|
||||
const uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
|
||||
await uow.transactional(async () => {
|
||||
// Projection A: selects `scope_mode` among its columns.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { OauthClients } from '../../../../src/db/entities/OauthClients.entity';
|
||||
import { OauthTokens } from '../../../../src/db/entities/OauthTokens.entity';
|
||||
import type { OauthClientsRepository } from '../../../../src/db/repositories/OauthClients.repository';
|
||||
@@ -20,7 +21,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
clients = t.repo(OauthClients);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { OauthClients } from '../../../../src/db/entities/OauthClients.entity';
|
||||
import { OauthConsents } from '../../../../src/db/entities/OauthConsents.entity';
|
||||
import type { OauthConsentsRepository } from '../../../../src/db/repositories/OauthConsents.repository';
|
||||
@@ -19,7 +20,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
consents = t.repo(OauthConsents);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { OauthClients } from '../../../../src/db/entities/OauthClients.entity';
|
||||
import { OauthConsents } from '../../../../src/db/entities/OauthConsents.entity';
|
||||
import { OauthTokens } from '../../../../src/db/entities/OauthTokens.entity';
|
||||
@@ -21,7 +22,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
tokens = t.repo(OauthTokens);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { PasswordResetTokens } from '../../../../src/db/entities/PasswordResetTokens.entity';
|
||||
import type { PasswordResetTokensRepository } from '../../../../src/db/repositories/PasswordResetTokens.repository';
|
||||
import { dbNow } from '../../../../src/db/types';
|
||||
@@ -209,7 +210,7 @@ describe('PasswordResetTokensRepository', () => {
|
||||
it('PWDRESETREPO-011: findByTokenHash then markConsumed inside uow.transactional survives the closing flush (cannot fail by construction — see PWDRESETREPO-012 for the mutation-proved guard)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const id = await seedToken(user.id, hash('survives'));
|
||||
const uow = new UnitOfWork(t.em);
|
||||
const uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
|
||||
await uow.transactional(async () => {
|
||||
const found = await tokens.findByTokenHash(hash('survives'));
|
||||
@@ -223,7 +224,7 @@ describe('PasswordResetTokensRepository', () => {
|
||||
it('PWDRESETREPO-012: findByTokenHash is the FIRST, wider read (it carries consumed_at); a narrower managed read follows; markConsumed still lands', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const id = await seedToken(user.id, hash('dshape'));
|
||||
const uow = new UnitOfWork(t.em);
|
||||
const uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
|
||||
await uow.transactional(async () => {
|
||||
await tokens.findByTokenHash(hash('dshape')); // projection A — WIDE (carries consumed_at)
|
||||
@@ -241,7 +242,7 @@ describe('PasswordResetTokensRepository', () => {
|
||||
it('PWDRESETREPO-013: same D-shape guard for consumeAllLiveForUser', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const id = await seedToken(user.id, hash('dshape-consume-all'));
|
||||
const uow = new UnitOfWork(t.em);
|
||||
const uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
|
||||
await uow.transactional(async () => {
|
||||
await tokens.findByTokenHash(hash('dshape-consume-all')); // projection A — WIDE (carries consumed_at)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Tags } from '../../../../src/db/entities/Tags.entity';
|
||||
import type { TagsRepository } from '../../../../src/db/repositories/Tags.repository';
|
||||
import { withRequestContext } from '../../../../src/nest/database/request-context';
|
||||
@@ -19,7 +20,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
tags = t.repo(Tags);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* days hold (MDT-02), the trip copy read and write
|
||||
* (TO6/TO8), and the create/edit writes (TO7/TO9).
|
||||
*/
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { DayAssignments } from '../../../../src/db/entities/DayAssignments.entity';
|
||||
import { Places } from '../../../../src/db/entities/Places.entity';
|
||||
import { TourPackingLinks } from '../../../../src/db/entities/TourPackingLinks.entity';
|
||||
@@ -332,7 +333,9 @@ describe('ToursRepository stages on days (MDT-02)', () => {
|
||||
createTour(testDb, other.id);
|
||||
const otherStage = createDayAssignment(testDb, days[2].id, other.id, { tour_stage_key: 'stage-two' });
|
||||
|
||||
const gone = await new UnitOfWork(t.em).transactional(() => repo.deleteTourStagesNotIn(place.id, ['stage-one']));
|
||||
const gone = await new UnitOfWork(t.em, new SqliteEngine()).transactional(() =>
|
||||
repo.deleteTourStagesNotIn(place.id, ['stage-one']),
|
||||
);
|
||||
expect(gone).toEqual([{ id: second.id, day_id: days[1].id }]);
|
||||
const left = (await findRows(t, DayAssignments, {}, { id: 'asc' })).map((row) => row.id);
|
||||
expect(left).toEqual([first.id, whole.id, otherStage.id]);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Trips } from '../../../../src/db/entities/Trips.entity';
|
||||
import { Users } from '../../../../src/db/entities/Users.entity';
|
||||
import type { TripsRepository } from '../../../../src/db/repositories/Trips.repository';
|
||||
@@ -20,7 +21,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
trips = t.repo(Trips);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { WebauthnCredentials } from '../../../../src/db/entities/WebauthnCredentials.entity';
|
||||
import type { WebauthnCredentialsRepository } from '../../../../src/db/repositories/WebauthnCredentials.repository';
|
||||
import { withRequestContext } from '../../../../src/nest/database/request-context';
|
||||
@@ -317,7 +318,7 @@ describe('WebauthnCredentialsRepository', () => {
|
||||
it('WEBAUTHN-CRED-REPO-017: a nativeUpdate inside uow.transactional is not discarded by a stale entity read earlier under a different projection', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const cred = await insertCredential(user.id, { counter: 1 });
|
||||
const uow = new UnitOfWork(t.em);
|
||||
const uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
|
||||
await withRequestContext(t.orm, async () => {
|
||||
// Projection A — wide, full row, carries `counter` (PK9's shape: findByCredentialId).
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
* no `disableIdentityMap`) makes IMWB-001 fail with the stale write-back this
|
||||
* test is built to catch.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Users } from '../../../../src/db/entities/Users.entity';
|
||||
import type { UsersRepository } from '../../../../src/db/repositories/Users.repository';
|
||||
import { withRequestContext } from '../../../../src/nest/database/request-context';
|
||||
@@ -50,7 +51,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
users = t.repo(Users);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
* backwards until this task; `OAUTHTOKREPO-029` (`OauthTokens.repository
|
||||
* .test.ts`) already had it right and is the shape to copy.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Users } from '../../../../src/db/entities/Users.entity';
|
||||
import { WebauthnChallenges } from '../../../../src/db/entities/WebauthnChallenges.entity';
|
||||
import type { UsersRepository } from '../../../../src/db/repositories/Users.repository';
|
||||
@@ -66,7 +67,7 @@ beforeAll(async () => {
|
||||
t = await createTestOrm(testDb, { allowGlobalContext: false });
|
||||
users = t.repo(Users);
|
||||
challenges = t.repo(WebauthnChallenges);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
// `t.clear()` is deliberately NOT called here (unlike most repository test
|
||||
// files): `EntityManager.clear()` itself calls the VALIDATING `getContext()`
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
* docstring: NESTED propagation) rather than the independent, connection-mutex-
|
||||
* queued transaction two unrelated concurrent requests actually are.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Trips } from '../../../src/db/entities/Trips.entity';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
import { withRequestContext } from '../../../src/nest/database/request-context';
|
||||
@@ -57,7 +58,7 @@ let uow: UnitOfWork;
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
trips = t.repo(Trips);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
|
||||
Reference in New Issue
Block a user