Files
TREK/server/tests/postgres/databases.ts
T
Isaias Tavares 526437926a test(db): run the suites that boot the app on Postgres in their own lane
npm run test:pg --workspace=server (vitest.pg.config.ts) runs every suite
that boots the app through buildApp() on the real database module against
Postgres, each test file on its own copy of one template database the
engine's bootstrap migrates once per run. TREK_TEST_DB_URL names the server;
without it the lane fails instead of passing on nothing. The CI job
'Server: Postgres Tests' runs it on a postgres:17 service and is part of
ci-ok.

tests/postgres/ holds what only Postgres needs proving:
- PARITY-PG: MikroORM's comparator finds nothing between the bootstrapped
  database and the entities. What it reports that changes nothing (key
  columns it would make nullable, defaults and checks Postgres spells its
  own way, the hand-ported triggers) is proven so: the spelling statements
  run in a rolled-back transaction and every default and check must read
  the same after, and every ported trigger must exist.
- the write lock: concurrent read-then-insert units of work never see the
  same count, and counts are numbers; a search ignores case.

tours-hike and tours-plan-types stay on SQLite only: they move a faked
setTimeout on until a tool call ends, which a database over the network
does not finish within.
2026-11-04 22:45:32 -03:00

38 lines
1.3 KiB
TypeScript

import { MikroORM } from '@mikro-orm/postgresql';
/**
* The databases the Postgres lane creates on the server TREK_TEST_DB_URL names:
* one migrated template per run, and one copy of it per test file.
*/
export const TEMPLATE_DATABASE = 'trek_test_template';
export const WORKER_DATABASE_PREFIX = 'trek_test_w';
/** `adminUrl` pointed at `database`, everything else (credentials, host, sslmode) kept. */
export function databaseUrl(adminUrl: string, database: string): string {
const url = new URL(adminUrl);
url.pathname = `/${database}`;
return url.toString();
}
type Run = <T = unknown>(sql: string, params?: unknown[]) => Promise<T[]>;
/**
* Runs `fn` on a connection to the admin database, outside any transaction
* (CREATE and DROP DATABASE refuse to run in one), through the same Postgres
* driver the app uses.
*/
export async function withAdmin<T>(adminUrl: string, fn: (run: Run) => Promise<T>): Promise<T> {
const orm = await MikroORM.init({
clientUrl: adminUrl,
entities: [],
discovery: { warnWhenNoEntities: false },
pool: { min: 0, max: 1 },
});
try {
const connection = orm.em.getConnection();
return await fn((sql, params = []) => connection.execute(sql, params, 'all'));
} finally {
await orm.close(true);
}
}