feat(db): run TREK on PostgreSQL

TREK runs on PostgreSQL when TREK_DB_URL is set, and on SQLite as before
otherwise: an engine port under src/db/engine, the dialect helpers under
src/db/dialect, a Postgres baseline for the migrations up to the cut,
pg_dump/pg_restore backups, a probe of every repository method against a
real server and a Postgres test lane in CI.
This commit is contained in:
Isaias Tavares
2026-11-05 01:15:21 -03:00
committed by Maurice
parent 17b47b38b9
commit 2e3762afe1
176 changed files with 6728 additions and 777 deletions
+14
View File
@@ -0,0 +1,14 @@
/** The databases TREK can run on. MySQL and MariaDB are out of scope (server/CLAUDE.md). */
export type EngineId = 'sqlite' | 'postgres';
/**
* Which database this process runs on, as `deriveDb` reads it from
* `TREK_DB_URL`. The Postgres arm carries what its pool needs, so nothing
* downstream has to check the URL again.
*/
export type DbEngineSettings = { engine: 'sqlite' } | { engine: 'postgres'; url: string; poolMax: number };
/** The most connections the Postgres pool opens (`TREK_DB_POOL_MAX` is refused above it). */
export const DB_POOL_MAX_CEILING = 100;
/** The pool size when `TREK_DB_POOL_MAX` is unset. */
export const DB_POOL_MAX_DEFAULT = 10;
+17
View File
@@ -14,6 +14,7 @@
* call, which is what keeps the runtime env-mutation semantics the test suite
* depends on. Zod validation runs once at boot (env.schema.ts), never here.
*/
import { DB_POOL_MAX_CEILING, DB_POOL_MAX_DEFAULT, type DbEngineSettings } from './db-settings';
import { imageVersion } from './image-version';
import {
csvList,
@@ -348,9 +349,25 @@ export function deriveBackup(raw: RawEnv) {
};
}
/** The database settings `readEnv().db` answers with. */
export type DbSettings = ReturnType<typeof deriveDb>;
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;
const engine: DbEngineSettings = url
? {
engine: 'postgres',
// The connection URL carries the password, so it is never logged (db/engine/redact-url.ts).
url,
poolMax: Math.min(positiveIntOr(raw.TREK_DB_POOL_MAX, DB_POOL_MAX_DEFAULT), DB_POOL_MAX_CEILING),
}
: { engine: 'sqlite' };
return {
/** Which database this process runs on: Postgres when TREK_DB_URL names one, the SQLite file otherwise. */
...engine,
/** Where pg_dump and pg_restore are; unset, the usual install directories are tried (never PATH). */
pgBinDir: raw.TREK_DB_PG_BIN_DIR?.trim() || undefined,
trekDbFile: raw.TREK_DB_FILE,
/** Resolved journal_mode — WAL unless the operator asked for something else (network storage needs DELETE/TRUNCATE). */
journalMode: durability.journalMode,
+14
View File
@@ -9,6 +9,7 @@
* listed here pass through untouched (Zod strips unknown keys, it does not
* reject them).
*/
import { DB_POOL_MAX_CEILING } from './db-settings';
import {
isP256PrivateKey,
isServiceKeyShape,
@@ -51,6 +52,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(', ')}`);
@@ -170,6 +179,11 @@ 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, DB_POOL_MAX_CEILING),
TREK_DB_PG_BIN_DIR: anyString,
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
+21 -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',
'MAIL_INGEST_IMAP_PASS',
'MAIL_INGEST_WEBHOOK_SECRET',
]);
@@ -97,7 +98,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(
@@ -106,6 +107,25 @@ export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
);
}
/** 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 sqliteKeys = SQLITE_ONLY_DB_KEYS.filter((key) => raw[key]?.trim());
if (sqliteKeys.length === 0) return [];
return [
` - ambiguous database configuration: TREK_DB_URL is set together with ${sqliteKeys.join(', ')}, ` +
'which only apply to the SQLite file. Unset one side.',
];
}
/**
* Cross-field rules that only apply to a centrally administered install.
*
+1
View File
@@ -2,6 +2,7 @@ export { readEnv, validateEnvAtBoot } from './env';
export { getAppUrl, getMcpSafeUrl } from './app-url';
export { runningVersion } from './running-version';
export type { AppEnv, RawEnv } from './env';
export type { DbSettings } from './derive';
export {
deriveAll,
deriveApp,