feat(db): choose the database engine from TREK_DB_URL

A port for the engine TREK runs on, without changing what it runs on.
src/db/engine/ names the engine (SqliteEngine, PostgresEngine) and builds
the MikroORM config from it; src/mikro-orm.config.ts exports that config for
the CLI and the Nest container alike. Without TREK_DB_URL the config is the
one it was: the shared SQLite driver on TREK_DB_FILE or data/travel.db.

- TREK_DB_URL takes a postgres:// or postgresql:// URL and is masked in the
  boot report; TREK_DB_POOL_MAX sizes the pool (1 to 100, default 10).
  TREK_DB_URL beside TREK_DB_FILE, TREK_DB_JOURNAL_MODE or
  TREK_DB_SYNCHRONOUS refuses the boot as an ambiguous configuration.
- MikroORM builds the pg pool from the URL's host, port, user, password and
  database and drops the rest of the query, so the engine reads sslmode and
  sslrootcert itself. require, verify-ca and verify-full all verify the
  server's certificate, as the pg driver reads them; a mode that would not
  verify, or a misspelt one, refuses.
- Postgres cannot run TREK yet, so a boot with TREK_DB_URL is refused with
  that reason, in the boot check and again where the config is built, before
  anything connects.
- @mikro-orm/postgresql moves to dependencies; pg is plain JavaScript.
- lint:engine-dispatch (CI) holds the engine checks outside src/db/dialect/
  and src/db/engine/ (isSqlite(, isPostgres(, an instanceof on a platform, a
  comparison on the engine's name) to a baseline that starts and stays empty.
This commit is contained in:
Isaias Tavares
2026-11-02 13:10:32 -03:00
parent 62912e5db1
commit 25f5e34558
21 changed files with 566 additions and 52 deletions
+7
View File
@@ -338,7 +338,14 @@ export function deriveBackup(raw: RawEnv) {
export function deriveDb(raw: RawEnv) {
const durability = resolveDurability(raw.TREK_DB_JOURNAL_MODE, raw.TREK_DB_SYNCHRONOUS);
const url = raw.TREK_DB_URL?.trim() || undefined;
return {
/** Which database this process runs on: Postgres when TREK_DB_URL names one, the SQLite file otherwise. */
engine: (url ? 'postgres' : 'sqlite') as 'sqlite' | 'postgres',
/** The Postgres connection URL; it carries the password, so never log it (db/engine/redact-url.ts). */
url,
/** The largest number of connections the Postgres pool opens. */
poolMax: Math.min(positiveIntOr(raw.TREK_DB_POOL_MAX, 10), 100),
trekDbFile: raw.TREK_DB_FILE,
/** Resolved journal_mode — WAL unless the operator asked for something else (network storage needs DELETE/TRUNCATE). */
journalMode: durability.journalMode,
+12
View File
@@ -51,6 +51,14 @@ const url = optionalWith((v) => {
return false;
}
}, 'must be a valid URL (with protocol)');
/** A Postgres connection URL: TREK_DB_URL names no other engine. */
const postgresUrl = optionalWith((v) => {
try {
return ['postgres:', 'postgresql:'].includes(new URL(v).protocol);
} catch {
return false;
}
}, 'must be a postgres:// or postgresql:// URL');
const duration = optionalWith((v) => parseDurationMs(v) != null, 'must be a duration like "1h", "7d" or "30d"');
const oneOf = (values: string[]) =>
optionalWith((v) => values.includes(v.toLowerCase()), `must be one of: ${values.join(', ')}`);
@@ -156,6 +164,10 @@ export const envSchema = z.object({
Path: anyString,
// Data / paths
// A Postgres database instead of the SQLite file. Its value is a secret (it
// carries the password), so it is masked in the boot report.
TREK_DB_URL: postgresUrl,
TREK_DB_POOL_MAX: integer(1, 100),
TREK_DB_FILE: anyString,
// The two SQLite pragmas are deliberately unvalidated: a typo here must fall
// back and warn rather than abort boot, because reset-admin.js — the way out
+29 -1
View File
@@ -33,6 +33,7 @@ export const SECRET_ENV_KEYS: ReadonlySet<string> = new Set([
'MAPBOX_ACCESS_TOKEN',
'CARTO_API_KEY',
'DEMO_ADMIN_PASS',
'TREK_DB_URL',
]);
/** How a variable's value appears in the boot report. */
@@ -95,7 +96,7 @@ export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
const key = String(issue.path[0]);
return ` - ${key}=${reportedValue(key, raw[key])}: ${issue.message}`;
});
lines.push(...managedPreconditions(raw));
lines.push(...databasePreconditions(raw), ...managedPreconditions(raw));
if (lines.length === 0) return;
console.error(`Invalid environment configuration:\n${lines.join('\n')}`);
throw new Error(
@@ -104,6 +105,33 @@ export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
);
}
/** Why a boot with TREK_DB_URL is refused until the Postgres engine can run TREK. */
export const POSTGRES_NOT_READY =
'Postgres support is not complete in this release; unset TREK_DB_URL to run on the SQLite file.';
/** The SQLite settings that mean nothing next to TREK_DB_URL. */
const SQLITE_ONLY_DB_KEYS = ['TREK_DB_FILE', 'TREK_DB_JOURNAL_MODE', 'TREK_DB_SYNCHRONOUS'] as const;
/**
* Cross-field rules for the database engine. TREK_DB_URL beside a SQLite
* setting names two databases, and either guess would leave the operator on
* the one they did not mean: it refuses instead (fail closed, see
* server/CLAUDE.md). The URL itself never reaches the report.
*/
function databasePreconditions(raw: RawEnv): string[] {
if (!raw.TREK_DB_URL?.trim()) return [];
const problems: string[] = [];
const sqliteKeys = SQLITE_ONLY_DB_KEYS.filter((key) => raw[key]?.trim());
if (sqliteKeys.length > 0) {
problems.push(
` - ambiguous database configuration: TREK_DB_URL is set together with ${sqliteKeys.join(', ')}, ` +
'which only apply to the SQLite file. Unset one side.',
);
}
problems.push(` - TREK_DB_URL: ${POSTGRES_NOT_READY}`);
return problems;
}
/**
* Cross-field rules that only apply to a centrally administered install.
*
+23
View File
@@ -0,0 +1,23 @@
import type { Options } from '@mikro-orm/core';
/** The databases TREK can be pointed at. MySQL/MariaDB are out of scope (server/CLAUDE.md). */
type EngineId = 'sqlite' | 'postgres';
/**
* One database engine: what the ORM needs to reach it and how to name it in a
* log line. Code that differs by engine dispatches through this, or through
* the helpers in `db/dialect/`, never through its own platform check
* (`lint:engine-dispatch`).
*
* Free of Nest like every other file under `db/`: `src/db` does not import
* `src/nest` (`lint:boundaries`).
*/
export interface DatabaseEngine {
readonly id: EngineId;
/** Whether this release can run TREK on the engine; `buildOrmConfig` refuses one that cannot. */
readonly ready: boolean;
/** For log lines and errors: the file path, or the URL without its password. */
describe(): string;
/** What MikroORM needs to reach the database: the driver and its target, the pool, driver options. */
ormOptions(): Partial<Options>;
}
+48
View File
@@ -0,0 +1,48 @@
import { readEnv } from '../../app-config';
import { POSTGRES_NOT_READY } from '../../app-config/env';
import { ALL_ENTITIES } from '../entities';
import type { DatabaseEngine } from './engine';
import { PostgresEngine } from './postgres/postgres-engine';
import { SqliteEngine } from './sqlite/sqlite-engine';
import { defineConfig, type Options } from '@mikro-orm/core';
import { Migrator } from '@mikro-orm/migrations';
import { SeedManager } from '@mikro-orm/seeder';
export type { DatabaseEngine } from './engine';
/**
* The engine this process runs on, from `TREK_DB_URL` (`readEnv().db`): the
* SQLite file unless the URL names a Postgres database. Read afresh on every
* call, like everything `readEnv()` answers, so nothing caches a choice a test
* or a restart changes.
*/
export function resolveEngine(db: ReturnType<typeof readEnv>['db'] = readEnv().db): DatabaseEngine {
if (db.engine === 'postgres' && db.url) return new PostgresEngine({ url: db.url, poolMax: db.poolMax });
return new SqliteEngine();
}
/**
* The MikroORM config for `engine`: what every engine shares (entities,
* migrations, seeders) and what the engine adds. `src/mikro-orm.config.ts`
* exports it for the CLI and the Nest container, so both reach the same
* database. An engine this release cannot run is refused here, before
* anything connects; the boot check refuses it earlier with the same words.
*/
export function buildOrmConfig(engine: DatabaseEngine): Options {
if (!engine.ready) throw new Error(`${POSTGRES_NOT_READY} (${engine.describe()})`);
return defineConfig({
entities: ALL_ENTITIES,
extensions: [Migrator, SeedManager],
migrations: {
path: 'dist/db/migrations',
pathTs: 'src/db/migrations',
snapshot: false,
},
seeder: {
path: 'dist/db/seeders',
pathTs: 'src/db/seeders',
defaultSeeder: 'DatabaseSeeder',
},
...engine.ormOptions(),
}) as Options;
}
@@ -0,0 +1,79 @@
import type { DatabaseEngine } from '../engine';
import { redactUrl } from '../redact-url';
import { PostgreSqlDriver } from '@mikro-orm/postgresql';
import { readFileSync } from 'node:fs';
/** What `TREK_DB_URL` and `TREK_DB_POOL_MAX` resolve to (`readEnv().db`). */
export interface PostgresSettings {
url: string;
poolMax: number;
}
/** The `ssl` option of a `pg` pool, as `sslOptionFor` builds it. */
export type PgSslOption = false | { rejectUnauthorized: true; ca?: string };
/** The sslmode values that verify the server, read the way the `pg` driver reads them. */
const VERIFYING_MODES = new Set(['require', 'verify-ca', 'verify-full']);
/**
* The `ssl` option for the pool, from the URL's `sslmode` and `sslrootcert`.
*
* MikroORM builds the pool from the URL's host, port, user, password and
* database alone and drops the rest of the query, so an `sslmode` in
* `TREK_DB_URL` would be ignored without this. `require`, `verify-ca` and
* `verify-full` all verify the server's certificate, as the `pg` driver itself
* treats them; `disable` turns SSL off, and no `sslmode` leaves the driver's
* default (no SSL). A mode that would connect without verifying (`prefer`,
* `allow`, `no-verify`) or that is misspelt refuses, rather than quietly
* connecting with less than was asked. `sslrootcert` names the CA file a host
* that signs its own certificates needs (Supabase's, say).
*/
export function sslOptionFor(url: string): PgSslOption | undefined {
const params = new URL(url).searchParams;
const mode = params.get('sslmode');
const rootCert = params.get('sslrootcert');
if (mode === null) {
if (rootCert !== null) throw new Error('TREK_DB_URL names an sslrootcert without sslmode=verify-full.');
return undefined;
}
if (mode === 'disable') return false;
if (!VERIFYING_MODES.has(mode)) {
throw new Error(
`TREK_DB_URL has sslmode "${mode}"; use disable, require, verify-ca or verify-full (all but disable verify the server).`,
);
}
if (rootCert === null) return { rejectUnauthorized: true };
try {
return { rejectUnauthorized: true, ca: readFileSync(rootCert, 'utf8') };
} catch (error) {
throw new Error(`TREK_DB_URL names sslrootcert ${rootCert}, which cannot be read.`, { cause: error });
}
}
/**
* The Postgres engine: MikroORM's own `pg` driver on `TREK_DB_URL`, with a
* pool of at most `TREK_DB_POOL_MAX` connections that keeps none open while
* idle. Not ready in this release: `buildOrmConfig` refuses it until the
* engine can bring a database to the schema.
*/
export class PostgresEngine implements DatabaseEngine {
readonly id = 'postgres';
readonly ready = false;
constructor(private readonly settings: PostgresSettings) {}
describe(): string {
return `Postgres ${redactUrl(this.settings.url)}`;
}
ormOptions() {
const ssl = sslOptionFor(this.settings.url);
return {
driver: PostgreSqlDriver,
clientUrl: this.settings.url,
pool: { min: 0, max: this.settings.poolMax },
driverOptions: ssl === undefined ? {} : { ssl },
};
}
}
+17
View File
@@ -0,0 +1,17 @@
/**
* A connection URL fit for a log line: the password masked and the query
* dropped, since libpq reads a password from the query too
* (`?password=...`). A value that does not parse is not echoed at all.
*/
export function redactUrl(url: string): string {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
return '<unparseable URL>';
}
if (parsed.password) parsed.password = '***';
parsed.search = '';
parsed.hash = '';
return parsed.toString();
}
@@ -0,0 +1,21 @@
import { resolveDbPath } from '../../db-path';
import { SharedSqliteDriver } from '../../orm-driver';
import type { DatabaseEngine } from '../engine';
/**
* The SQLite file engine, TREK's default: one better-sqlite3 handle that
* `db/database.ts` owns and the ORM's bound driver shares (`db/orm-driver.ts`),
* on `TREK_DB_FILE` or `data/travel.db` (`:memory:` under test).
*/
export class SqliteEngine implements DatabaseEngine {
readonly id = 'sqlite';
readonly ready = true;
describe(): string {
return `SQLite file ${resolveDbPath()}`;
}
ormOptions() {
return { driver: SharedSqliteDriver, dbName: resolveDbPath() };
}
}
+7 -29
View File
@@ -1,30 +1,8 @@
import { resolveDbPath } from './db/db-path';
import { ALL_ENTITIES } from './db/entities';
import { SharedSqliteDriver } from './db/orm-driver';
import { Migrator } from '@mikro-orm/migrations';
import { SeedManager } from '@mikro-orm/seeder';
import { defineConfig } from '@mikro-orm/sqlite';
import { buildOrmConfig, resolveEngine } from './db/engine';
export default defineConfig({
entities: ALL_ENTITIES,
extensions: [Migrator, SeedManager],
// Reuses the connection db/database.ts owns rather than opening a second one.
// See orm-driver.ts — with `:memory:` in tests, a second connection would be a
// second, empty database.
driver: SharedSqliteDriver,
migrations: {
path: 'dist/db/migrations',
pathTs: 'src/db/migrations',
snapshot: false,
},
seeder: {
path: 'dist/db/seeders',
pathTs: 'src/db/seeders',
defaultSeeder: 'DatabaseSeeder',
},
// Same resolution database.ts uses: `:memory:` under test, TREK_DB_FILE when
// set, else data/travel.db. The driver above ignores it for the connection
// itself, but the CLI and the migrator's logging still read it, and naming a
// different file here than the one actually open is a trap.
dbName: resolveDbPath(),
});
/**
* The one MikroORM config, for the CLI and the Nest container alike: the
* engine `TREK_DB_URL` names (the SQLite file by default) and what every
* engine shares (`db/engine/index.ts`).
*/
export default buildOrmConfig(resolveEngine());