mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30: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,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Addons } from '../../src/db/entities/Addons.entity';
|
||||
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
|
||||
import { PhotoProviderFields } from '../../src/db/entities/PhotoProviderFields.entity';
|
||||
@@ -42,6 +43,6 @@ export async function createTestAddonsService(db: Database.Database): Promise<Ad
|
||||
t.repo(PhotoProviderFields),
|
||||
t.repo(AppSettings),
|
||||
t.repo(Users),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AppSettings } from '../../src/db/entities/AppSettings.entity';
|
||||
import { AssignmentParticipants } from '../../src/db/entities/AssignmentParticipants.entity';
|
||||
import { Categories } from '../../src/db/entities/Categories.entity';
|
||||
@@ -143,7 +144,7 @@ export function createTestUnitOfWork(db: Database.Database): Promise<UnitOfWork>
|
||||
// which is exactly what no-misused-promises/checksConditionals rejects.
|
||||
const existing = perHandle.get(db);
|
||||
if (existing !== undefined) return existing;
|
||||
const pending = sharedTestOrm(db).then((t) => new UnitOfWork(t.em));
|
||||
const pending = sharedTestOrm(db).then((t) => new UnitOfWork(t.em, new SqliteEngine()));
|
||||
perHandle.set(db, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { getMcpSafeUrl } from '../../src/app-config';
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { db as testDb } from '../../src/db/database';
|
||||
import { SqliteEngine } from '../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
import { McpTokens } from '../../src/db/entities/McpTokens.entity';
|
||||
import { OauthClients } from '../../src/db/entities/OauthClients.entity';
|
||||
@@ -85,7 +86,7 @@ beforeAll(async () => {
|
||||
t.repo(OauthConsents),
|
||||
await createTestAddonsService(testDb),
|
||||
new AuditService(t.repo(AuditLog), t.repo(Users)),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
nestApp.get(CimdClientResolver),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { db as testDb } from '../../src/db/database';
|
||||
import { SqliteEngine } from '../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Addons } from '../../src/db/entities/Addons.entity';
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
import { OauthClients } from '../../src/db/entities/OauthClients.entity';
|
||||
@@ -96,7 +97,7 @@ beforeAll(async () => {
|
||||
t.repo(OauthConsents),
|
||||
await createTestAddonsService(testDb),
|
||||
new AuditService(t.repo(AuditLog), t.repo(Users)),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
nestApp.get(CimdClientResolver),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { db as testDb } from '../../src/db/database';
|
||||
import { SqliteEngine } from '../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Addons } from '../../src/db/entities/Addons.entity';
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
import { OauthClients } from '../../src/db/entities/OauthClients.entity';
|
||||
@@ -97,7 +98,7 @@ beforeAll(async () => {
|
||||
t.repo(OauthConsents),
|
||||
await createTestAddonsService(testDb),
|
||||
new AuditService(t.repo(AuditLog), t.repo(Users)),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
nestApp.get(CimdClientResolver),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
* asserts the plugin still comes up clean.
|
||||
*/
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Addons } from '../../../src/db/entities/Addons.entity';
|
||||
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
@@ -173,7 +174,7 @@ describe('plugin boot vs registry scan ordering', () => {
|
||||
(t as TestOrm).repo(NotificationChannelPreferences),
|
||||
// Plan 4 Task 4: `uow` is no longer `@Optional()` — ordered ahead
|
||||
// of `registry?`/`hostFactory?`, matching the real constructor.
|
||||
new UnitOfWork((t as TestOrm).em),
|
||||
new UnitOfWork((t as TestOrm).em, new SqliteEngine()),
|
||||
undefined,
|
||||
hostFactory,
|
||||
t?.orm,
|
||||
@@ -264,7 +265,7 @@ describe('plugin boot vs registry scan ordering', () => {
|
||||
t2.repo(PhotoProviderFields),
|
||||
t2.repo(AppSettings),
|
||||
t2.repo(Users),
|
||||
new UnitOfWork(t2.em),
|
||||
new UnitOfWork(t2.em, new SqliteEngine()),
|
||||
);
|
||||
const auditLogRepo2 = t2.repo(AuditLog);
|
||||
const usersRepo2 = t2.repo(Users);
|
||||
@@ -293,7 +294,7 @@ describe('plugin boot vs registry scan ordering', () => {
|
||||
t2.repo(PluginCapabilityAudit),
|
||||
t2.repo(Settings),
|
||||
t2.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t2.em),
|
||||
new UnitOfWork(t2.em, new SqliteEngine()),
|
||||
undefined,
|
||||
hostFactory2,
|
||||
t2.orm,
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* so every one of the 14 repositories this task injects reads/writes real columns,
|
||||
* not a hand-slimmed fixture table.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
@@ -76,7 +77,7 @@ async function buildRuntime(registrar?: CronRegistrarService): Promise<PluginRun
|
||||
const audit = new AuditService(t.repo(AuditLog), t.repo(Users));
|
||||
const addons = await createTestAddonsService(testDb);
|
||||
const userSettings = new PluginUserSettingsService(t.repo(PluginSettingsFields), t.repo(PluginUserConfig));
|
||||
const uow = new UnitOfWork(t.em);
|
||||
const uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
return new PluginRuntimeService(
|
||||
audit,
|
||||
addons,
|
||||
@@ -218,7 +219,7 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
fakeRegistry(['db:own']),
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -254,7 +255,7 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
fakeRegistry(['db:own', 'db:read:trips']),
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -303,7 +304,7 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
registry,
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -342,7 +343,7 @@ describe('Plan 3j Task 2 — R-install-gates named accept+refuse pairs (PR17/PR2
|
||||
t.repo(PluginCapabilityAudit),
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
registry,
|
||||
);
|
||||
await expect(rtR.retrust('pr28-refuse', '2.0.0', 'NEWKEY', { userId: 1 })).rejects.toThrow(/nothing to re-trust/);
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
* plugin-runtime.service.ts's own comment at the wrap site) already ran inside a
|
||||
* request context by the time this file's shared `runtime` finished booting.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
@@ -158,7 +159,7 @@ async function buildRuntime(registrar?: CronRegistrarService, orm?: TestOrm['orm
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
// Plan 4 Task 4: `uow` is no longer `@Optional()`.
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
undefined,
|
||||
undefined,
|
||||
orm,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* install a pinned version through the full verify -> extract -> validate ->
|
||||
* move -> register pipeline (with the network download mocked).
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
@@ -148,7 +149,7 @@ beforeEach(() => {
|
||||
t.repo(PluginActions),
|
||||
t.repo(PluginSettingsFields),
|
||||
t.repo(PluginErrorLog),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
|
||||
@@ -373,8 +373,8 @@ describe('deriveDb: the pre-migration snapshot', () => {
|
||||
|
||||
describe('deriveDb: the engine', () => {
|
||||
it('DB-ENGINE-001: SQLite unless TREK_DB_URL names a database', () => {
|
||||
expect(deriveDb({})).toMatchObject({ engine: 'sqlite', url: undefined });
|
||||
expect(deriveDb({ TREK_DB_URL: ' ' })).toMatchObject({ engine: 'sqlite', url: undefined });
|
||||
expect(deriveDb({})).toMatchObject({ engine: 'sqlite' });
|
||||
expect(deriveDb({ TREK_DB_URL: ' ' })).toMatchObject({ engine: 'sqlite' });
|
||||
expect(deriveDb({ TREK_DB_URL: ' postgres://u:p@db:5432/trek ' })).toMatchObject({
|
||||
engine: 'postgres',
|
||||
url: 'postgres://u:p@db:5432/trek',
|
||||
@@ -382,10 +382,20 @@ describe('deriveDb: the engine', () => {
|
||||
});
|
||||
|
||||
it('DB-ENGINE-002: a pool of ten connections unless told otherwise, from 1 to 100', () => {
|
||||
expect(deriveDb({}).poolMax).toBe(10);
|
||||
expect(deriveDb({ TREK_DB_POOL_MAX: '25' }).poolMax).toBe(25);
|
||||
expect(deriveDb({ TREK_DB_POOL_MAX: '0' }).poolMax).toBe(10);
|
||||
expect(deriveDb({ TREK_DB_POOL_MAX: '500' }).poolMax).toBe(100);
|
||||
const poolMaxOf = (raw: Record<string, string>) => {
|
||||
const db = deriveDb({ TREK_DB_URL: 'postgres://u:p@db:5432/trek', ...raw });
|
||||
return db.engine === 'postgres' ? db.poolMax : null;
|
||||
};
|
||||
expect(deriveDb({ TREK_DB_URL: 'postgres://u:p@db:5432/trek' })).toMatchObject({ engine: 'postgres' });
|
||||
expect(poolMaxOf({})).toBe(10);
|
||||
expect(poolMaxOf({ TREK_DB_POOL_MAX: '25' })).toBe(25);
|
||||
expect(poolMaxOf({ TREK_DB_POOL_MAX: '0' })).toBe(10);
|
||||
expect(poolMaxOf({ TREK_DB_POOL_MAX: '500' })).toBe(100);
|
||||
});
|
||||
|
||||
it('DB-ENGINE-003: no pool size on SQLite, which has no pool', () => {
|
||||
expect(deriveDb({ TREK_DB_POOL_MAX: '25' })).toMatchObject({ engine: 'sqlite' });
|
||||
expect(deriveDb({})).not.toHaveProperty('poolMax');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* the legacy router, because rpc-host.test.ts asserts them and shipped plugins read
|
||||
* them, so these tests pin the exact strings rather than just the refusal.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
@@ -205,7 +206,7 @@ describe('PluginGuards — canEditAs/canCreateAs against a real UsersRepository
|
||||
beforeEach(async () => {
|
||||
testDb = createSnapshotTestDb();
|
||||
orm = await createTestOrm(testDb);
|
||||
const permissions = new PermissionsService(orm.repo(AppSettings), new UnitOfWork(orm.em));
|
||||
const permissions = new PermissionsService(orm.repo(AppSettings), new UnitOfWork(orm.em, new SqliteEngine()));
|
||||
const db = {
|
||||
findAccessible: vi.fn(async (tripId: number) => (tripId === 1 ? { id: 1, user_id: ownerId } : undefined)),
|
||||
} as unknown as TripsRepository;
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
* filter itself (the disabled row is excluded) alongside the boolean coercion
|
||||
* of the enabled row that remains.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Addons } from '../../../src/db/entities/Addons.entity';
|
||||
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
|
||||
import { PhotoProviderFields } from '../../../src/db/entities/PhotoProviderFields.entity';
|
||||
@@ -195,7 +196,7 @@ beforeEach(() => {
|
||||
photoProviderFieldsRepo,
|
||||
appSettingsRepo,
|
||||
usersRepo,
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* The restore step the two backup ports share (`database-swap.ts`): the swap,
|
||||
* then a reopen that always runs, and how the two failures surface.
|
||||
*/
|
||||
import { keepRestoreCopy, replaceThenReopen } from '../../../../src/nest/backup/database-swap';
|
||||
import { DatabaseConnectionLostError } from '../../../../src/nest/database/database-backup.interface';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const ok = async () => undefined;
|
||||
const fails = (error: unknown) => async () => {
|
||||
throw error;
|
||||
};
|
||||
|
||||
describe('replaceThenReopen', () => {
|
||||
it('SWAP-001: a swap that lands and a reopen that works resolves with no reopen error', async () => {
|
||||
const swap = vi.fn(ok);
|
||||
const reopen = vi.fn(ok);
|
||||
|
||||
await expect(replaceThenReopen(swap, reopen)).resolves.toEqual({ reopenError: null });
|
||||
expect(swap).toHaveBeenCalledTimes(1);
|
||||
expect(reopen).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('SWAP-002: a swap that lands and a reopen that fails resolves with the reopen error, so the caller says restart', async () => {
|
||||
const lost = new Error('reconnect failed');
|
||||
|
||||
await expect(replaceThenReopen(ok, fails(lost))).resolves.toEqual({ reopenError: lost });
|
||||
});
|
||||
|
||||
it('SWAP-003: a swap that fails still reopens, and its own error is rethrown', async () => {
|
||||
const reopen = vi.fn(ok);
|
||||
const swapError = new Error('rename failed');
|
||||
|
||||
await expect(replaceThenReopen(fails(swapError), reopen)).rejects.toBe(swapError);
|
||||
expect(reopen).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('SWAP-004: a swap and a reopen that both fail go up together, as DatabaseConnectionLostError', async () => {
|
||||
const swapError = new Error('rename failed');
|
||||
const reopenError = new Error('reconnect failed');
|
||||
|
||||
const thrown = await replaceThenReopen(fails(swapError), fails(reopenError)).catch((err: unknown) => err);
|
||||
|
||||
expect(thrown).toBeInstanceOf(DatabaseConnectionLostError);
|
||||
expect((thrown as DatabaseConnectionLostError).swapError).toBe(swapError);
|
||||
expect((thrown as DatabaseConnectionLostError).cause).toBe(reopenError);
|
||||
});
|
||||
|
||||
it('SWAP-005: a step that throws undefined still counts as failed', async () => {
|
||||
// A reopen that throws undefined is a failure: with a swap that also failed, the two go up as the lost connection.
|
||||
await expect(replaceThenReopen(fails(new Error('rename failed')), fails(undefined))).rejects.toBeInstanceOf(
|
||||
DatabaseConnectionLostError,
|
||||
);
|
||||
// A swap that throws undefined rethrows undefined, the same value the step threw.
|
||||
await expect(replaceThenReopen(fails(undefined), ok)).rejects.toBeUndefined();
|
||||
});
|
||||
|
||||
it('SWAP-006: a synchronous swap that throws is caught like an async one', async () => {
|
||||
const swapError = new Error('copy failed');
|
||||
const reopen = vi.fn(ok);
|
||||
|
||||
await expect(
|
||||
replaceThenReopen(() => {
|
||||
throw swapError;
|
||||
}, reopen),
|
||||
).rejects.toBe(swapError);
|
||||
expect(reopen).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('keepRestoreCopy', () => {
|
||||
it('SWAP-007: resolves with the target once the copy is written', async () => {
|
||||
await expect(keepRestoreCopy('/data/pre-restore-1.db', ok)).resolves.toBe('/data/pre-restore-1.db');
|
||||
});
|
||||
|
||||
it('SWAP-008: a copy that cannot be written resolves with null, so the restore goes on', async () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
try {
|
||||
await expect(keepRestoreCopy('/data/pre-restore-2.db', fails(new Error('disk full')))).resolves.toBeNull();
|
||||
} finally {
|
||||
warn.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* DatabaseEngineModule: one engine per container, shared by every injector.
|
||||
*/
|
||||
import {
|
||||
DatabaseEngineModule,
|
||||
DATABASE_ENGINE,
|
||||
DATABASE_SETTINGS,
|
||||
} from '../../../../src/nest/database/database-engine.module';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('DatabaseEngineModule', () => {
|
||||
it('ENGINE-DI-001: provides one engine instance, so state an engine keeps is the same wherever it is injected', async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [DatabaseEngineModule] }).compile();
|
||||
|
||||
const engine = moduleRef.get(DATABASE_ENGINE);
|
||||
expect(moduleRef.get(DATABASE_ENGINE)).toBe(engine);
|
||||
expect(engine.id).toBe('sqlite');
|
||||
});
|
||||
|
||||
it('ENGINE-DI-002: the settings are read from the environment once and the engine is resolved from them', async () => {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [DatabaseEngineModule] }).compile();
|
||||
|
||||
const settings = moduleRef.get(DATABASE_SETTINGS);
|
||||
expect(settings.engine).toBe('sqlite');
|
||||
expect(moduleRef.get(DATABASE_SETTINGS)).toBe(settings);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { Users } from '../../../../src/db/entities/Users.entity';
|
||||
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
@@ -29,7 +30,7 @@ let uow: UnitOfWork;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
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 { 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';
|
||||
@@ -25,7 +26,7 @@ let days: DaysRepository;
|
||||
*/
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
uow = new UnitOfWork(t.em);
|
||||
uow = new UnitOfWork(t.em, new SqliteEngine());
|
||||
days = t.repo(Days);
|
||||
});
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
import { ADDON_IDS } from '../../../src/addons';
|
||||
import { getMcpSafeUrl } from '../../../src/app-config';
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { OauthClients } from '../../../src/db/entities/OauthClients.entity';
|
||||
import { OauthConsents } from '../../../src/db/entities/OauthConsents.entity';
|
||||
@@ -132,7 +133,7 @@ beforeAll(async () => {
|
||||
consentsRepo,
|
||||
addonsStub,
|
||||
new AuditService(auditLogRepo, usersRepo),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
cimdStub,
|
||||
);
|
||||
});
|
||||
@@ -1446,7 +1447,7 @@ describe('module-scoped OAuth state', () => {
|
||||
consentsRepo,
|
||||
addonsStub,
|
||||
new AuditService(auditLogRepo, usersRepo),
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
cimdStub,
|
||||
);
|
||||
expect((await secondInstance.consumeAuthCode(code))?.userId).toBe(42);
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
* tests/helpers/fake-pg-tools.ts) and a stand-in DatabaseLifecycle. The tools'
|
||||
* own arguments are pinned in tests/unit/db/engine/postgres/pg-tools.test.ts.
|
||||
*/
|
||||
import { deriveDb } from '../../../src/app-config/derive';
|
||||
import { resolveEngine } from '../../../src/db/engine';
|
||||
import { knownMigrationNames } from '../../../src/db/known-migrations';
|
||||
import type { DataPathsService } from '../../../src/nest/app-config/data-paths.service';
|
||||
import { PostgresDatabaseBackup } from '../../../src/nest/backup/postgres-database-backup';
|
||||
@@ -31,6 +33,17 @@ let extract: string;
|
||||
let reopen: ReturnType<typeof vi.fn>;
|
||||
let backup: PostgresDatabaseBackup;
|
||||
|
||||
/** The adapter over the settings a process reads from these variables, with stand-ins for the lifecycle and the data directory. */
|
||||
function postgresBackup(env: Record<string, string>): PostgresDatabaseBackup {
|
||||
const db = deriveDb(env);
|
||||
return new PostgresDatabaseBackup(
|
||||
{ reopen } as unknown as DatabaseLifecycle,
|
||||
{ dataDir: root } as unknown as DataPathsService,
|
||||
resolveEngine(db),
|
||||
db,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(path.join(tmpdir(), 'trek-pg-backup-'));
|
||||
bin = path.join(root, 'bin');
|
||||
@@ -38,13 +51,8 @@ beforeEach(() => {
|
||||
mkdirSync(bin);
|
||||
mkdirSync(extract);
|
||||
installFakeTool(bin, 'psql', { snippets: [answersSchema()] });
|
||||
vi.stubEnv('TREK_DB_URL', 'postgresql://trek:pw@db/trek');
|
||||
vi.stubEnv('TREK_DB_PG_BIN_DIR', bin);
|
||||
reopen = vi.fn(async () => undefined);
|
||||
backup = new PostgresDatabaseBackup(
|
||||
{ reopen } as unknown as DatabaseLifecycle,
|
||||
{ dataDir: root } as unknown as DataPathsService,
|
||||
);
|
||||
backup = postgresBackup({ TREK_DB_URL: 'postgresql://trek:pw@db/trek', TREK_DB_PG_BIN_DIR: bin });
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
@@ -78,7 +86,7 @@ describe('PostgresDatabaseBackup', () => {
|
||||
it('PGBACKUP-002: verify accepts a TREK dump this build knows', async () => {
|
||||
writeFileSync(path.join(extract, 'travel.pgdump'), 'dump');
|
||||
installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3))] });
|
||||
await expect(backup.verify(extract)).resolves.toBeNull();
|
||||
await expect(backup.verify(extract)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('PGBACKUP-002a: verify refuses an archive without a TREK dump in it', async () => {
|
||||
@@ -159,7 +167,6 @@ describe('PostgresDatabaseBackup', () => {
|
||||
|
||||
it('PGBACKUP-006: names the database without its password, and refuses to run without TREK_DB_URL', async () => {
|
||||
expect(backup.location()).toBe('Postgres postgresql://trek:***@db/trek');
|
||||
vi.stubEnv('TREK_DB_URL', '');
|
||||
await expect(backup.snapshot(path.join(root, 'c.pgdump'))).rejects.toThrow(/without TREK_DB_URL/);
|
||||
await expect(postgresBackup({}).snapshot(path.join(root, 'c.pgdump'))).rejects.toThrow(/without TREK_DB_URL/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
*/
|
||||
import { SqliteMaintenance } from '../../../src/db/engine/sqlite/sqlite-maintenance';
|
||||
import { SqliteDatabaseBackup } from '../../../src/nest/backup/sqlite-database-backup';
|
||||
import { DomainError } from '../../../src/nest/common/domain-error';
|
||||
import { DatabaseConnectionLostError } from '../../../src/nest/database/database-backup.interface';
|
||||
import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
|
||||
import { withRequestContext } from '../../../src/nest/database/request-context';
|
||||
@@ -146,11 +147,16 @@ describe('SqliteDatabaseBackup', () => {
|
||||
expect(fs.existsSync(target)).toBe(false);
|
||||
});
|
||||
|
||||
it('SQLBK-007: verify refuses an unpacked archive without a database', async () => {
|
||||
await expect(portWith(maintenanceStub()).verify(dir)).resolves.toEqual({
|
||||
error: 'Invalid backup: travel.db not found',
|
||||
status: 400,
|
||||
});
|
||||
it('SQLBK-007: verify refuses an unpacked archive without a database, as a DomainError the restore route answers', async () => {
|
||||
const refusal = await portWith(maintenanceStub())
|
||||
.verify(dir)
|
||||
.then(
|
||||
() => null,
|
||||
(err: unknown) => err,
|
||||
);
|
||||
expect(refusal).toBeInstanceOf(DomainError);
|
||||
expect((refusal as DomainError).publicMessage).toBe('Invalid backup: travel.db not found');
|
||||
expect((refusal as DomainError).getStatus()).toBe(400);
|
||||
});
|
||||
|
||||
it('SQLBK-008: keeps a copy of the database a restore replaces next to it, and says where', async () => {
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* bundle), via a real MikroORM over the full migrated schema (`createSnapshotTestDb`
|
||||
* + `createTestOrm`) rather than a hand-rolled `:memory:` table set.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
import { PluginErrorLog } from '../../../src/db/entities/PluginErrorLog.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
@@ -47,7 +48,7 @@ beforeAll(async () => {
|
||||
actions: t.repo(PluginActions),
|
||||
settingsFields: t.repo(PluginSettingsFields),
|
||||
errorLog: t.repo(PluginErrorLog),
|
||||
uow: new UnitOfWork(t.em),
|
||||
uow: new UnitOfWork(t.em, new SqliteEngine()),
|
||||
};
|
||||
});
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* https/SSRF guard on the endpoints, the code + refresh token exchanges (mocked fetch),
|
||||
* tokens encrypted at rest, and a stored refresh token that the plugin never sees.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { PluginOauthState } from '../../../src/db/entities/PluginOauthState.entity';
|
||||
import { PluginOauthTokens } from '../../../src/db/entities/PluginOauthTokens.entity';
|
||||
import { PluginSettingsFields } from '../../../src/db/entities/PluginSettingsFields.entity';
|
||||
@@ -90,7 +91,7 @@ async function makeOauthService(): Promise<PluginOAuthService> {
|
||||
orm.repo(PluginOauthTokens),
|
||||
orm.repo(PluginOauthState),
|
||||
orm.repo(PluginSettingsFields),
|
||||
new UnitOfWork(orm.em),
|
||||
new UnitOfWork(orm.em, new SqliteEngine()),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
* defensible: dropping the `logError` call, or falling through to `activate`
|
||||
* anyway, would ship green with no test failing. This file pins it directly.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
@@ -99,7 +100,7 @@ async function buildRuntime(withOrm: boolean): Promise<PluginRuntimeService> {
|
||||
t.repo(NotificationChannelPreferences),
|
||||
// Plan 4 Task 4: `uow` is no longer `@Optional()` — ordered ahead of
|
||||
// `registry?`/`hostFactory?`, matching the real constructor's own order.
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
undefined,
|
||||
undefined,
|
||||
withOrm ? t.orm : undefined,
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
* shared helpers use to let ordinary unit tests call a repository with no
|
||||
* request wrapper at all: that default would hide this exact bug.
|
||||
*/
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
|
||||
import { Trips } from '../../../src/db/entities/Trips.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
@@ -70,7 +71,7 @@ let userId: number;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb, { allowGlobalContext: false });
|
||||
permissions = new PermissionsService(t.repo(AppSettings), new UnitOfWork(t.em));
|
||||
permissions = new PermissionsService(t.repo(AppSettings), new UnitOfWork(t.em, new SqliteEngine()));
|
||||
// Plan 3j Task 1: PluginGuards' own role lookup (canCreateAs, PG4) now goes
|
||||
// through UsersRepository.getRole — a REAL repository bound to `t.em`
|
||||
// (allowGlobalContext: false, same as `permissions`' AppSettingsRepository
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* which for a notification channel meant being dispatched to everyone with no credentials.
|
||||
*/
|
||||
import { db as testDb } from '../../../src/db/database';
|
||||
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
|
||||
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
|
||||
import { NotificationChannelPreferences } from '../../../src/db/entities/NotificationChannelPreferences.entity';
|
||||
import { PluginActions } from '../../../src/db/entities/PluginActions.entity';
|
||||
@@ -204,7 +205,7 @@ describe('a plugin channel label is bounded by the host', () => {
|
||||
t.repo(Settings),
|
||||
t.repo(NotificationChannelPreferences),
|
||||
// Plan 4 Task 4: `uow` is no longer `@Optional()`.
|
||||
new UnitOfWork(t.em),
|
||||
new UnitOfWork(t.em, new SqliteEngine()),
|
||||
);
|
||||
// Stand the plugin up as a granted, active notificationChannel provider.
|
||||
(rt as unknown as { supervisor: { running: Map<string, unknown> } }).supervisor.running.set('loud', {
|
||||
|
||||
Reference in New Issue
Block a user