mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-20 11:06:06 +00:00
98533f3dbe
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.
104 lines
4.3 KiB
TypeScript
104 lines
4.3 KiB
TypeScript
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
|
import { Days } from '../../../../src/db/entities/Days.entity';
|
|
import type { DaysRepository } from '../../../../src/db/repositories/Days.repository';
|
|
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
|
|
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
|
import { createTrip, createUser } from '../../../helpers/factories';
|
|
import { countRows } from '../../../helpers/factories/rows';
|
|
import { resetTestDb } from '../../../helpers/test-db';
|
|
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
|
|
|
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
|
|
|
const testDb = createSnapshotTestDb();
|
|
let t: TestOrm;
|
|
let uow: UnitOfWork;
|
|
let days: DaysRepository;
|
|
|
|
/**
|
|
* `t.em` is the ORM's context-resolving global EntityManager and `t.repo()`
|
|
* builds on it, which is what makes this suite meaningful: the repository resolves the
|
|
* transactional fork out of MikroORM's TransactionContext, exactly as a
|
|
* Nest-injected repository does. A manually forked EntityManager would not
|
|
* (`fork()` defaults to `useContext: false`) — it would write outside the open
|
|
* transaction, on a second connection the transaction is holding, and deadlock
|
|
* on Kysely's connection mutex. See the docstring on `createTestOrm`.
|
|
*/
|
|
beforeAll(async () => {
|
|
t = await createTestOrm(testDb);
|
|
uow = new UnitOfWork(t.em, new SqliteEngine());
|
|
days = t.repo(Days);
|
|
});
|
|
beforeEach(() => {
|
|
resetTestDb(testDb);
|
|
t.clear();
|
|
});
|
|
afterAll(async () => {
|
|
await t.close();
|
|
testDb.close();
|
|
});
|
|
|
|
const countDays = (tripId: number): Promise<number> => countRows(t, Days, { trip: tripId });
|
|
|
|
describe('UnitOfWork.transactional', () => {
|
|
it('UOW-001: a throw rolls every statement back', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
await expect(
|
|
uow.transactional(async () => {
|
|
await days.createDay({ trip_id: trip.id, day_number: 1, date: null, notes: null });
|
|
throw new Error('boom');
|
|
}),
|
|
).rejects.toThrow('boom');
|
|
expect(await countDays(trip.id)).toBe(0);
|
|
});
|
|
|
|
it('UOW-002: an inner transaction is a savepoint — its failure leaves the outer writes intact', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
await uow.transactional(async () => {
|
|
await days.createDay({ trip_id: trip.id, day_number: 1, date: null, notes: null });
|
|
await uow
|
|
.transactional(async () => {
|
|
await days.createDay({ trip_id: trip.id, day_number: 2, date: null, notes: null });
|
|
throw new Error('inner');
|
|
})
|
|
.catch(() => undefined);
|
|
});
|
|
expect(await countDays(trip.id)).toBe(1);
|
|
});
|
|
|
|
it('UOW-003: concurrent transactions serialise on the one connection instead of throwing', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const order: string[] = [];
|
|
const tx = (label: string, dayNumber: number) =>
|
|
uow.transactional(async () => {
|
|
order.push(`${label}:in`);
|
|
await days.createDay({ trip_id: trip.id, day_number: dayNumber, date: null, notes: null });
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
order.push(`${label}:out`);
|
|
});
|
|
await Promise.all([tx('a', 1), tx('b', 2)]);
|
|
expect(await countDays(trip.id)).toBe(2);
|
|
// The second never enters before the first leaves.
|
|
expect(order.indexOf('b:in')).toBeGreaterThan(order.indexOf('a:out'));
|
|
});
|
|
|
|
it('UOW-004: a read outside the transaction waits for it and then sees the commit', async () => {
|
|
const { user } = createUser(testDb);
|
|
const trip = createTrip(testDb, user.id);
|
|
const tx = uow.transactional(async () => {
|
|
await days.createDay({ trip_id: trip.id, day_number: 1, date: null, notes: null });
|
|
await new Promise((r) => setTimeout(r, 20));
|
|
});
|
|
// A separate fork = a separate acquirer of the connection. It waits on the
|
|
// ConnectionMutex instead of deadlocking because nothing inside the
|
|
// transaction waits on it: the writer's own timer resolves regardless.
|
|
const reader = t.orm.em.fork().getRepository(Days);
|
|
const seen = await reader.listByTrip(trip.id);
|
|
await tx;
|
|
expect(seen).toHaveLength(1);
|
|
});
|
|
});
|