From 1c3dc937168762883d0a6e04e183329fea66b463 Mon Sep 17 00:00:00 2001 From: Isaias Tavares Date: Thu, 5 Nov 2026 00:56:25 -0300 Subject: [PATCH] refactor(db): keep the SQLite-only helpers and the Postgres number parsers explicit createStandaloneOrm builds the SQLite schema snapshot, so it now refuses a config that names another driver instead of silently building a snapshot of the wrong engine. runSchemaBootstrap takes its snapshot flag as a required argument: the reopen after a restore is the only caller that skips the copy, and an omitted flag should not be able to pick a default for it. The Postgres driver's number parsers say which values they refuse: NaN and the infinities are reported as not finite instead of as beyond 2^53, which was the wrong reason. The driver's header comment is folded into the constant docs it described. --- .../src/db/engine/postgres/postgres-driver.ts | 37 ++++++++++++------- server/src/db/orm.ts | 16 +++----- server/src/db/standalone-orm.ts | 7 ++++ server/tests/build-schema-snapshot.ts | 2 +- server/tests/helpers/legacy-upgrade-suite.ts | 2 +- .../engine/postgres/postgres-driver.test.ts | 3 +- .../unit/db/restore-migrates-forward.test.ts | 4 +- 7 files changed, 42 insertions(+), 29 deletions(-) diff --git a/server/src/db/engine/postgres/postgres-driver.ts b/server/src/db/engine/postgres/postgres-driver.ts index 125ee367d..5dde04db2 100644 --- a/server/src/db/engine/postgres/postgres-driver.ts +++ b/server/src/db/engine/postgres/postgres-driver.ts @@ -1,8 +1,10 @@ import { type Configuration } from '@mikro-orm/core'; import { PostgreSqlConnection, PostgreSqlDriver } from '@mikro-orm/postgresql'; -/** The `pg` type id of `bigint` (`int8`): every integer column and every `count(*)` on Postgres. */ +/** `int8` (bigint), a `pg_type.oid`: every integer column and every `count(*)` on Postgres. */ const INT8_OID = 20; +/** `numeric`: what `sum()` of a bigint and `avg()` answer. */ +const NUMERIC_OID = 1700; /** * Reads a `bigint` as a JavaScript number, the way better-sqlite3 hands @@ -17,24 +19,29 @@ export function parseInt8(text: string): number { return value; } -/** The `pg` type id of `numeric`: what `sum()` of a bigint and `avg()` answer. */ -const NUMERIC_OID = 1700; - /** - * Reads a `numeric` as a number, as SQLite answers `sum()` and `avg()`. An - * integral result past 2^53 is refused like a bigint; a fraction is a double, - * the precision SQLite's REAL has. + * Reads a `numeric` as a number, as SQLite answers `sum()` and `avg()`. `NaN` + * and the infinities are refused, as is an integral result past 2^53, which is + * refused like a bigint; a fraction is a double, the precision SQLite's REAL has. */ export function parseNumeric(text: string): number { const value = Number(text); - if (!Number.isFinite(value) || (/^-?\d+$/.test(text) && !Number.isSafeInteger(value))) { + if (!Number.isFinite(value)) { + throw new Error(`A numeric of ${text} is not a finite number, which TREK does not read.`); + } + if (/^-?\d+$/.test(text) && !Number.isSafeInteger(value)) { throw new Error(`A numeric of ${text} is beyond what TREK reads exactly (2^53).`); } return value; } -/** The pool's own parsers (MikroORM keeps dates as text), plus `int8` and `numeric` as numbers. */ -class Int8NumberConnection extends PostgreSqlConnection { +/** + * MikroORM's `PostgreSqlConnection`, with the pool's own type parsers replaced + * for `int8` and `numeric`. MikroORM keeps dates as text, so only these two + * change. `mapOptions` builds the `pg` pool options, whose `types` is the + * `pg` TypeOverrides, the object that holds the parsers. + */ +class NumberTypesConnection extends PostgreSqlConnection { override mapOptions(overrides: Parameters[0]) { const options = super.mapOptions(overrides); const types = options.types as { setTypeParser(oid: number, parse: (text: string) => unknown): void }; @@ -45,14 +52,16 @@ class Int8NumberConnection extends PostgreSqlConnection { } /** - * MikroORM's Postgres driver on a connection that reads `bigint` as a number. - * The parsers belong to this pool only: nothing global in `pg` changes. + * MikroORM's Postgres driver on a connection that reads `bigint` and `numeric` + * as numbers. The parsers belong to this pool only: nothing global in `pg` + * changes. */ export class TrekPostgreSqlDriver extends PostgreSqlDriver { constructor(config: Configuration) { super(config); // PostgreSqlDriver's constructor hardcodes its connection class, as - // SqliteDriver's does (`db/orm-driver.ts`); replaced before anything connects. - (this as unknown as { connection: PostgreSqlConnection }).connection = new Int8NumberConnection(config); + // SqliteDriver's does (`db/orm-driver.ts`). It keeps the connection in a + // field, which is not public, so it is replaced here, before anything connects. + (this as unknown as { connection: PostgreSqlConnection }).connection = new NumberTypesConnection(config); } } diff --git a/server/src/db/orm.ts b/server/src/db/orm.ts index 19ef5b09d..efb0fa622 100644 --- a/server/src/db/orm.ts +++ b/server/src/db/orm.ts @@ -7,13 +7,9 @@ import type { AnyEntity, EntityClass, EntityManager, EntitySchema, IDatabaseDriv import type { Migrator } from '@mikro-orm/migrations'; /** - * Schema ownership at startup. - * - * This replaces `createTables()` → `runMigrations()` → `runSeeds()`, which used - * to run synchronously inside `database.ts::initDb()` at module load. The - * migrator is async, so the work moved to `buildApp()`, which is the first place - * in the boot with an await and still runs before anything reads the database - * (`bootstrap.ts` resolves SettingsService right after). + * Schema ownership at startup. The migrator is async, so the schema is brought + * to head from `DatabaseLifecycle.open()`, which `buildApp()` calls before + * anything reads the database. Nothing runs at module load. */ /** @@ -33,10 +29,10 @@ export type AnyOrm = MikroORM< * Migrate to head, then seed. Safe to call again, both halves are idempotent. * * `snapshot: false` skips the pre-migration copy (`pre-migrate-snapshot.ts`). - * Only the restore hook passes it: the file it migrates was just unpacked from - * a backup archive, which is still there to go back to. + * Only the reopen after a restore passes it: the file it migrates was just + * unpacked from a backup archive, which is still there to go back to. */ -export async function runSchemaBootstrap(orm: AnyOrm, { snapshot = true }: { snapshot?: boolean } = {}): Promise { +export async function runSchemaBootstrap(orm: AnyOrm, { snapshot }: { snapshot: boolean }): Promise { const migrator = orm.config.getExtension('@mikro-orm/migrator') as Migrator; const connection = orm.em.getConnection(); // A database the retired positional runner migrated has no migrator rows yet; diff --git a/server/src/db/standalone-orm.ts b/server/src/db/standalone-orm.ts index 05f3b438a..f300bfff2 100644 --- a/server/src/db/standalone-orm.ts +++ b/server/src/db/standalone-orm.ts @@ -1,13 +1,20 @@ import mikroOrmConfig from '../mikro-orm.config'; import type { AnyOrm } from './orm'; +import { SharedSqliteDriver } from './orm-driver'; import { MikroORM as SqliteMikroORM } from '@mikro-orm/sqlite'; /** * An ORM instance outside Nest, for the vitest global setup that builds the * schema snapshot. Production uses the container-owned one from * `MikroOrmModule.forRoot()` instead of creating a second. + * + * SQLite only: the snapshot is the SQLite schema and the init below is the + * SQLite driver's, so a config that names another engine is refused. */ export function createStandaloneOrm(): Promise { + if (mikroOrmConfig.driver !== SharedSqliteDriver) { + throw new Error('createStandaloneOrm builds the SQLite schema snapshot; unset TREK_DB_URL to run it.'); + } return SqliteMikroORM.init({ ...mikroOrmConfig, // Entity discovery is skipped deliberately. Migrations and seeders are raw diff --git a/server/tests/build-schema-snapshot.ts b/server/tests/build-schema-snapshot.ts index 226a7a50e..12bdc8f20 100644 --- a/server/tests/build-schema-snapshot.ts +++ b/server/tests/build-schema-snapshot.ts @@ -26,7 +26,7 @@ async function main(): Promise { // serialised straight after. const orm = await createStandaloneOrm(); try { - await runSchemaBootstrap(orm); + await runSchemaBootstrap(orm, { snapshot: true }); writeSchemaSnapshot(getRawConnection().serialize()); console.log(`[test-db] schema snapshot written to ${schemaSnapshotPath()}`); } finally { diff --git a/server/tests/helpers/legacy-upgrade-suite.ts b/server/tests/helpers/legacy-upgrade-suite.ts index f807ef0d4..367c9433d 100644 --- a/server/tests/helpers/legacy-upgrade-suite.ts +++ b/server/tests/helpers/legacy-upgrade-suite.ts @@ -152,7 +152,7 @@ export function describeLegacyUpgrade( it(`${c.id}-005: a second bootstrap (a restart, or a restore of this file) baselines nothing and applies nothing`, async () => { const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); try { - await runSchemaBootstrap(app.get(MikroORM)); + await runSchemaBootstrap(app.get(MikroORM), { snapshot: true }); const lines = logSpy.mock.calls.map((args) => args.map(String).join(' ')); expect( lines.filter((line) => line.startsWith('[DB] Legacy install') || line.startsWith('[DB] Applying')), diff --git a/server/tests/unit/db/engine/postgres/postgres-driver.test.ts b/server/tests/unit/db/engine/postgres/postgres-driver.test.ts index f957cf9eb..25c9cf469 100644 --- a/server/tests/unit/db/engine/postgres/postgres-driver.test.ts +++ b/server/tests/unit/db/engine/postgres/postgres-driver.test.ts @@ -23,7 +23,8 @@ describe('postgres driver', () => { expect(parseNumeric('2.5000000000000000')).toBe(2.5); expect(parseNumeric('-7')).toBe(-7); expect(() => parseNumeric('9007199254740993')).toThrow(/beyond what TREK reads exactly/); - expect(() => parseNumeric('NaN')).toThrow(/beyond what TREK reads exactly/); + expect(() => parseNumeric('NaN')).toThrow(/not a finite number/); + expect(() => parseNumeric('Infinity')).toThrow(/not a finite number/); }); it("PGDRIVER-002: the pool parses int8 as a number and keeps MikroORM's text dates", () => { diff --git a/server/tests/unit/db/restore-migrates-forward.test.ts b/server/tests/unit/db/restore-migrates-forward.test.ts index 214863577..aebbf7d19 100644 --- a/server/tests/unit/db/restore-migrates-forward.test.ts +++ b/server/tests/unit/db/restore-migrates-forward.test.ts @@ -71,10 +71,10 @@ describe('a restored database is migrated forward', () => { // What reinitialize() does after the file has been swapped in. const restored = await ormFor(dbFile); - await runSchemaBootstrap(restored); + await runSchemaBootstrap(restored, { snapshot: true }); // Twice: a restore can follow a boot that already bootstrapped, and every // seeder is written to tolerate that. - await runSchemaBootstrap(restored); + await runSchemaBootstrap(restored, { snapshot: true }); await restored.close(true); const after = new Database(dbFile);