mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
feat(db): create and migrate the schema on a Postgres database
With TREK_DB_URL set, TREK now boots on Postgres; without it nothing changes. - The database engine contract gains open, close, reopen and the schema bootstrap; DatabaseLifecycle delegates to the engine resolveEngine() picks. - An empty Postgres database gets server/assets/postgres/baseline.sql (generated from the entities by gen:pg-baseline, with the reference rows the migrations up to its cut insert: tour types, provider catalogues, addons, app settings) and every migration up to its cut recorded as executed, in one transaction. A database holding tables without TREK's history is refused before anything is written; a migrated one runs the newer-database refusal and its pending migrations, which refuse without a copy unless TREK_DB_PRE_MIGRATE_SNAPSHOT=false. - INTEGER columns are bigint on Postgres (SQLite's INTEGER is 64-bit: an epoch-millisecond column overflowed int4), and the engine's driver reads bigint and numeric back as numbers, refusing values past 2^53. - The two SQLite triggers are ported to PL/pgSQL; check:pg-baseline fails while a SQLite trigger has no port, and while the baseline drifts from the entities before a later migration freezes it. - Backups and restores on Postgres refuse until they can dump and load one. - Migration helpers read the catalog per engine (dialect/catalog.ts), and the email case index no longer needs group_concat. - CI runs check:pg-baseline and boots the image on postgres:17 twice.
This commit is contained in:
@@ -105,10 +105,6 @@ 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;
|
||||
|
||||
@@ -120,16 +116,12 @@ const SQLITE_ONLY_DB_KEYS = ['TREK_DB_FILE', 'TREK_DB_JOURNAL_MODE', 'TREK_DB_SY
|
||||
*/
|
||||
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;
|
||||
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.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { isPostgres, isSqlite, unsupported } from './platform';
|
||||
import type { Platform } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* The schema catalog, for the migrations' helpers (`db/migration-utils.ts`):
|
||||
* which tables and columns exist, each spelled the way its engine keeps them.
|
||||
* Both statements take the table name as their one bound parameter and answer
|
||||
* one row per hit with the name in `name`. Postgres reads the current schema
|
||||
* only, the one TREK's own tables live in.
|
||||
*/
|
||||
|
||||
/** Lists the columns of the table bound as `?`, one `name` per row; none for a missing table. */
|
||||
export function columnNamesSql(platform: Platform): string {
|
||||
if (isSqlite(platform)) return 'select name from pragma_table_info(?)';
|
||||
if (isPostgres(platform)) {
|
||||
return 'select column_name as name from information_schema.columns where table_schema = current_schema() and table_name = ?';
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** One row when the table bound as `?` exists, none otherwise. */
|
||||
export function tableExistsSql(platform: Platform): string {
|
||||
if (isSqlite(platform)) return "select name from sqlite_master where type = 'table' and name = ?";
|
||||
if (isPostgres(platform)) {
|
||||
return 'select table_name as name from information_schema.tables where table_schema = current_schema() and table_name = ?';
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
@@ -18,13 +18,18 @@ export async function ensureEmailCaseIndex(connection: Connection): Promise<void
|
||||
const pending: unknown[] = await connection.execute(`SELECT value FROM app_settings WHERE key = ?`, [PENDING_KEY]);
|
||||
if (pending.length === 0) return;
|
||||
|
||||
const duplicates: Array<{ ids: string }> = await connection.execute(
|
||||
`SELECT group_concat(id, ', ') AS ids FROM (SELECT id, email FROM users ORDER BY id) GROUP BY lower(email) HAVING COUNT(*) > 1`,
|
||||
// Grouped here rather than with group_concat, which Postgres spells string_agg.
|
||||
const rows: Array<{ id: number; email_key: string }> = await connection.execute(
|
||||
`SELECT id, lower(email) AS email_key FROM users WHERE lower(email) IN ` +
|
||||
`(SELECT lower(email) FROM users GROUP BY lower(email) HAVING COUNT(*) > 1) ORDER BY id`,
|
||||
);
|
||||
if (duplicates.length > 0) {
|
||||
const duplicates = new Map<string, number[]>();
|
||||
for (const row of rows) duplicates.set(row.email_key, [...(duplicates.get(row.email_key) ?? []), row.id]);
|
||||
if (duplicates.size > 0) {
|
||||
const ids = [...duplicates.values()].map((group) => group.join(', '));
|
||||
console.warn(
|
||||
`[DB] ${duplicates.length} email address(es) still belong to more than one account when case is ignored ` +
|
||||
`(user ids ${duplicates.map((row) => row.ids).join('; ')}), so users.email has no case-insensitive unique ` +
|
||||
`[DB] ${duplicates.size} email address(es) still belong to more than one account when case is ignored ` +
|
||||
`(user ids ${ids.join('; ')}), so users.email has no case-insensitive unique ` +
|
||||
'index yet. Give each of those accounts its own address under Admin > Users; the next start creates it.',
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -1,23 +1,40 @@
|
||||
import type { AnyOrm } from '../orm';
|
||||
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`).
|
||||
* One database engine: what the ORM needs to reach it, how the connection
|
||||
* opens, closes and comes back after a restore, and how a database is brought
|
||||
* to the current schema. 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`).
|
||||
* `src/nest` (`lint:boundaries`). `DatabaseLifecycle` is the provider that
|
||||
* calls it.
|
||||
*/
|
||||
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>;
|
||||
/**
|
||||
* Called once at boot, before the schema bootstrap. `onReopened` is what
|
||||
* has to follow a later reopen (rebinding the ORM, migrating the restored
|
||||
* database forward).
|
||||
*/
|
||||
open(onReopened: () => Promise<void>): void;
|
||||
/** Closes what the engine itself holds; the ORM's own pool is closed with the Nest container. */
|
||||
close(): void;
|
||||
/** Comes back after the database was replaced by a restore, then runs `onReopened`. */
|
||||
reopen(): Promise<void>;
|
||||
/**
|
||||
* Brings the database to the current schema, then seeds it. `snapshot:
|
||||
* false` skips the copy taken before pending migrations (a restore, whose
|
||||
* archive is the copy).
|
||||
*/
|
||||
schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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';
|
||||
@@ -25,11 +24,9 @@ export function resolveEngine(db: ReturnType<typeof readEnv>['db'] = readEnv().d
|
||||
* 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.
|
||||
* database.
|
||||
*/
|
||||
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],
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { splitStatements } from './schema-adjust';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* Where the Postgres baseline lives: `server/assets/postgres/`, which the
|
||||
* Docker image copies beside `dist/` (the same place the airports and atlas
|
||||
* data are read from), reached the same way from `src/` and from `dist/`.
|
||||
*/
|
||||
const BASELINE_DIR = path.join(__dirname, '..', '..', '..', '..', 'assets', 'postgres');
|
||||
const SQL_FILE = 'baseline.sql';
|
||||
const MANIFEST_FILE = 'baseline.json';
|
||||
|
||||
/** The manifest beside the SQL: the last migration the baseline stands for, and every migration it replaces. */
|
||||
interface BaselineManifest {
|
||||
through: string;
|
||||
migrations: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The schema a fresh Postgres database starts from.
|
||||
*
|
||||
* The 331 migrations up to `through` are written in SQLite and frozen, so a
|
||||
* Postgres database does not replay them: it runs these statements, generated
|
||||
* from the entities (`npm run gen:pg-baseline`), and records every migration
|
||||
* in `migrations` as executed in the same transaction. Migrations after
|
||||
* `through` run on both engines through the migrator.
|
||||
*/
|
||||
export interface PostgresBaseline extends BaselineManifest {
|
||||
statements: string[];
|
||||
}
|
||||
|
||||
/** The two files a baseline is written as, ready to compare or write. */
|
||||
export function renderBaseline(baseline: PostgresBaseline): { sql: string; manifest: string } {
|
||||
return {
|
||||
sql:
|
||||
'-- The schema a fresh Postgres database starts from. Generated by `npm run gen:pg-baseline`; do not edit.\n' +
|
||||
baseline.statements.map((statement) => `${statement};\n`).join(''),
|
||||
manifest: `${JSON.stringify({ through: baseline.through, migrations: baseline.migrations }, null, 2)}\n`,
|
||||
};
|
||||
}
|
||||
|
||||
function parseManifest(text: string, file: string): BaselineManifest {
|
||||
const data: unknown = JSON.parse(text);
|
||||
const manifest = data as Partial<BaselineManifest>;
|
||||
const valid =
|
||||
typeof manifest.through === 'string' &&
|
||||
Array.isArray(manifest.migrations) &&
|
||||
manifest.migrations.length > 0 &&
|
||||
manifest.migrations.every((name) => typeof name === 'string') &&
|
||||
manifest.migrations.includes(manifest.through);
|
||||
if (!valid) throw new Error(`${file} must name "through" and list it among "migrations"`);
|
||||
return { through: manifest.through as string, migrations: manifest.migrations as string[] };
|
||||
}
|
||||
|
||||
/** Reads the committed baseline; a missing or malformed one throws, so a boot cannot start from half a schema. */
|
||||
export function readPostgresBaseline(dir = BASELINE_DIR): PostgresBaseline {
|
||||
const manifestFile = path.join(dir, MANIFEST_FILE);
|
||||
const manifest = parseManifest(fs.readFileSync(manifestFile, 'utf8'), manifestFile);
|
||||
const statements = splitStatements(fs.readFileSync(path.join(dir, SQL_FILE), 'utf8').replace(/^--[^\n]*\n/gm, ''));
|
||||
if (statements.length === 0) throw new Error(`${path.join(dir, SQL_FILE)} holds no statements`);
|
||||
// The boot sends the baseline as one statement without parameters, where a `?` would be read as a binding.
|
||||
if (statements.some((statement) => statement.includes('?'))) {
|
||||
throw new Error(`${path.join(dir, SQL_FILE)} holds a "?", which the boot would read as a parameter`);
|
||||
}
|
||||
return { ...manifest, statements };
|
||||
}
|
||||
|
||||
/** Writes the two files (the generator's `--write`). */
|
||||
export function writePostgresBaseline(baseline: PostgresBaseline, dir = BASELINE_DIR): void {
|
||||
const { sql, manifest } = renderBaseline(baseline);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, SQL_FILE), sql);
|
||||
fs.writeFileSync(path.join(dir, MANIFEST_FILE), manifest);
|
||||
}
|
||||
|
||||
/** Whether the committed files are what `baseline` renders to (the generator's `--check`). */
|
||||
export function baselineMatches(baseline: PostgresBaseline, dir = BASELINE_DIR): boolean {
|
||||
const { sql, manifest } = renderBaseline(baseline);
|
||||
const read = (file: string) =>
|
||||
fs.existsSync(path.join(dir, file)) ? fs.readFileSync(path.join(dir, file), 'utf8') : null;
|
||||
return read(SQL_FILE) === sql && read(MANIFEST_FILE) === manifest;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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. */
|
||||
const INT8_OID = 20;
|
||||
|
||||
/**
|
||||
* Reads a `bigint` as a JavaScript number, the way better-sqlite3 hands
|
||||
* SQLite's 64-bit INTEGER to the services. `pg` returns it as a string to
|
||||
* keep precision past 2^53; no TREK value comes near that (ids, counts,
|
||||
* epoch milliseconds, cents), so one that does is refused rather than
|
||||
* rounded.
|
||||
*/
|
||||
export function parseInt8(text: string): number {
|
||||
const value = Number(text);
|
||||
if (!Number.isSafeInteger(value)) throw new Error(`A bigint of ${text} is beyond what TREK reads exactly (2^53).`);
|
||||
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.
|
||||
*/
|
||||
export function parseNumeric(text: string): number {
|
||||
const value = Number(text);
|
||||
if (!Number.isFinite(value) || (/^-?\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 {
|
||||
override mapOptions(overrides: Parameters<PostgreSqlConnection['mapOptions']>[0]) {
|
||||
const options = super.mapOptions(overrides);
|
||||
const types = options.types as { setTypeParser(oid: number, parse: (text: string) => unknown): void };
|
||||
types.setTypeParser(INT8_OID, parseInt8);
|
||||
types.setTypeParser(NUMERIC_OID, parseNumeric);
|
||||
return options;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { finishSchemaBootstrap, type AnyOrm } from '../../orm';
|
||||
import type { DatabaseEngine } from '../engine';
|
||||
import { redactUrl } from '../redact-url';
|
||||
import { PostgreSqlDriver } from '@mikro-orm/postgresql';
|
||||
import { TrekPostgreSqlDriver } from './postgres-driver';
|
||||
import { bootstrapPostgresSchema, defaultPostgresBootstrapDeps, type PostgresBootstrapDeps } from './schema-bootstrap';
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
@@ -54,14 +56,34 @@ export function sslOptionFor(url: string): PgSslOption | undefined {
|
||||
/**
|
||||
* 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.
|
||||
* idle. The pool belongs to the ORM, which the Nest container closes; the
|
||||
* schema comes from the baseline plus the migrations after it
|
||||
* (`schema-bootstrap.ts`).
|
||||
*/
|
||||
export class PostgresEngine implements DatabaseEngine {
|
||||
readonly id = 'postgres';
|
||||
readonly ready = false;
|
||||
|
||||
constructor(private readonly settings: PostgresSettings) {}
|
||||
constructor(
|
||||
private readonly settings: PostgresSettings,
|
||||
private readonly bootstrapDeps: () => PostgresBootstrapDeps = defaultPostgresBootstrapDeps,
|
||||
) {}
|
||||
|
||||
open(): void {
|
||||
// Nothing of its own to open: the ORM connects the pool.
|
||||
}
|
||||
|
||||
close(): void {
|
||||
// Nothing of its own to close: the pool goes with the ORM.
|
||||
}
|
||||
|
||||
reopen(): Promise<void> {
|
||||
return Promise.reject(new Error('Restoring a backup into a Postgres database is not available in this release.'));
|
||||
}
|
||||
|
||||
async schemaBootstrap(orm: AnyOrm): Promise<void> {
|
||||
await bootstrapPostgresSchema(orm, this.bootstrapDeps());
|
||||
await finishSchemaBootstrap(orm);
|
||||
}
|
||||
|
||||
describe(): string {
|
||||
return `Postgres ${redactUrl(this.settings.url)}`;
|
||||
@@ -70,7 +92,7 @@ export class PostgresEngine implements DatabaseEngine {
|
||||
ormOptions() {
|
||||
const ssl = sslOptionFor(this.settings.url);
|
||||
return {
|
||||
driver: PostgreSqlDriver,
|
||||
driver: TrekPostgreSqlDriver,
|
||||
clientUrl: this.settings.url,
|
||||
pool: { min: 0, max: this.settings.poolMax },
|
||||
driverOptions: ssl === undefined ? {} : { ssl },
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* How the entities' schema is written in Postgres: the one definition the
|
||||
* Postgres baseline (`scripts/generate-pg-baseline.ts`), the schema parity
|
||||
* check and the probe (`scripts/pg-probe.ts`) share.
|
||||
*
|
||||
* The entities are generated from the migrated SQLite schema and a parity
|
||||
* test pins them to it (`npm run check:entities`), so they are the one
|
||||
* description of the tables both engines can read. MikroORM's schema
|
||||
* generator turns them into Postgres DDL after the adjustments below, which
|
||||
* keep the storage model the services and the dialect helpers are written
|
||||
* for (server/CLAUDE.md, "Storage model"):
|
||||
*
|
||||
* - timestamps stay TEXT;
|
||||
* - an INTEGER column is `bigint`: SQLite's INTEGER holds 64 bits, so a
|
||||
* column written with epoch milliseconds or a byte count past 2 GB would
|
||||
* overflow Postgres's 32-bit `integer` (the engine's driver reads
|
||||
* `bigint` back as a number, `postgres-driver.ts`);
|
||||
* - a SQLite-only default (`datetime('now')`, `strftime('%s','now')`,
|
||||
* `CURRENT_TIMESTAMP` in a TEXT column) gets its Postgres equivalent, and
|
||||
* a column declared `COLLATE NOCASE` uses the `nocase` collation
|
||||
* `collateNoCase()` names on Postgres.
|
||||
*
|
||||
* The baseline keeps the foreign keys; the probe leaves them out, so a
|
||||
* statement it sends is never refused only because the sample row it writes
|
||||
* points at nothing.
|
||||
*/
|
||||
import { pgTimestampText, PG_UTC_NOW } from '../../dialect/platform';
|
||||
|
||||
/** SQLite's timestamp text on Postgres, for a column default. */
|
||||
export const PG_NOW_TEXT_DEFAULT = pgTimestampText(PG_UTC_NOW);
|
||||
|
||||
/** The case-insensitive collation `collateNoCase()` names on Postgres. */
|
||||
export const NOCASE_COLLATION_SQL =
|
||||
"CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false)";
|
||||
|
||||
/** The Postgres spelling of a column default the entities carry in SQLite's. */
|
||||
export function portableDefault(raw: string): string {
|
||||
const text = raw
|
||||
.trim()
|
||||
.replace(/^\((.*)\)$/s, '$1')
|
||||
.trim();
|
||||
if (/^current_timestamp$/i.test(text) || /^datetime\(\s*'now'\s*\)$/i.test(text)) return PG_NOW_TEXT_DEFAULT;
|
||||
if (/^strftime\(\s*'%s'\s*,\s*'now'\s*\)$/i.test(text))
|
||||
return 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)';
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* The SQLite schema's triggers, as Postgres writes them: a trigger function
|
||||
* and the trigger that runs it, under the SQLite trigger's name. The entities
|
||||
* describe tables only, so the baseline adds these after the tables, and
|
||||
* `check:pg-baseline` fails while a trigger in the migrated SQLite schema has
|
||||
* no entry here.
|
||||
*/
|
||||
export const POSTGRES_TRIGGERS: Readonly<Record<string, readonly string[]>> = {
|
||||
// A deleted stay releases the day stops it claimed (no foreign key holds the link).
|
||||
trg_release_stop_on_stay_delete: [
|
||||
`CREATE FUNCTION trg_release_stop_on_stay_delete() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
UPDATE day_assignments SET accommodation_id = NULL WHERE accommodation_id = OLD.id;
|
||||
RETURN OLD;
|
||||
END
|
||||
$$`,
|
||||
'CREATE TRIGGER trg_release_stop_on_stay_delete AFTER DELETE ON day_accommodations ' +
|
||||
'FOR EACH ROW EXECUTE FUNCTION trg_release_stop_on_stay_delete()',
|
||||
],
|
||||
// A place that moved or was renamed drops the region it was resolved to (#2527).
|
||||
trg_place_regions_follow_place: [
|
||||
`CREATE FUNCTION trg_place_regions_follow_place() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
DELETE FROM place_regions WHERE place_id = NEW.id;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$`,
|
||||
'CREATE TRIGGER trg_place_regions_follow_place AFTER UPDATE OF lat, lng, address ON places FOR EACH ROW ' +
|
||||
'WHEN (OLD.lat IS DISTINCT FROM NEW.lat OR OLD.lng IS DISTINCT FROM NEW.lng OR OLD.address IS DISTINCT FROM NEW.address) ' +
|
||||
'EXECUTE FUNCTION trg_place_regions_follow_place()',
|
||||
],
|
||||
};
|
||||
|
||||
/**
|
||||
* Splits generated DDL into single statements on `;` outside quotes and
|
||||
* `$$` bodies, so one statement Postgres refuses does not take the rest of the
|
||||
* schema with it.
|
||||
*/
|
||||
export function splitStatements(sql: string): string[] {
|
||||
const statements: string[] = [];
|
||||
let current = '';
|
||||
let quote: '"' | "'" | '$$' | null = null;
|
||||
for (let i = 0; i < sql.length; i++) {
|
||||
const char = sql[i];
|
||||
const dollar = sql.startsWith('$$', i);
|
||||
if (quote === '$$') {
|
||||
if (dollar) {
|
||||
quote = null;
|
||||
current += '$';
|
||||
i++;
|
||||
}
|
||||
current += char;
|
||||
} else if (quote) {
|
||||
if (char === quote) quote = null;
|
||||
current += char;
|
||||
} else if (dollar) {
|
||||
quote = '$$';
|
||||
current += '$$';
|
||||
i++;
|
||||
} else if (char === "'" || char === '"') {
|
||||
quote = char;
|
||||
current += char;
|
||||
} else if (char === ';') {
|
||||
if (current.trim()) statements.push(current.trim());
|
||||
current = '';
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
if (current.trim()) statements.push(current.trim());
|
||||
return statements.filter((statement) => !/^set\s/i.test(statement));
|
||||
}
|
||||
|
||||
/** A column type SQLite stores as its 64-bit INTEGER. */
|
||||
const INTEGER_TYPE = /^(integer|int)$/i;
|
||||
|
||||
/** The subset of MikroORM's property metadata the schema adjustments touch. */
|
||||
export interface ColumnMeta {
|
||||
name: string;
|
||||
defaultRaw?: string;
|
||||
collation?: string;
|
||||
columnTypes?: string[];
|
||||
customType?: { constructor: { name: string } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the adjustments above to one entity's properties in place:
|
||||
* timestamp columns become `text`, integer columns `bigint`, SQLite-only defaults and the NOCASE
|
||||
* collation their Postgres spelling. Returns the names of the properties
|
||||
* it changed, for the log.
|
||||
*/
|
||||
export function adjustColumns(properties: readonly ColumnMeta[]): string[] {
|
||||
const changed: string[] = [];
|
||||
for (const property of properties) {
|
||||
let touched = false;
|
||||
if (property.customType?.constructor.name === 'DbTimestampType' && property.columnTypes) {
|
||||
property.columnTypes = property.columnTypes.map(() => 'text');
|
||||
touched = true;
|
||||
} else if (property.columnTypes?.some((type) => INTEGER_TYPE.test(type))) {
|
||||
property.columnTypes = property.columnTypes.map((type) => (INTEGER_TYPE.test(type) ? 'bigint' : type));
|
||||
touched = true;
|
||||
}
|
||||
if (typeof property.defaultRaw === 'string') {
|
||||
const next = portableDefault(property.defaultRaw);
|
||||
if (next !== property.defaultRaw) {
|
||||
property.defaultRaw = next;
|
||||
touched = true;
|
||||
}
|
||||
}
|
||||
if (property.collation?.toUpperCase() === 'NOCASE') {
|
||||
property.collation = 'nocase';
|
||||
touched = true;
|
||||
}
|
||||
if (touched) changed.push(property.name);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { readEnv, type AppEnv } from '../../../app-config';
|
||||
import { knownMigrationNames } from '../../known-migrations';
|
||||
import { migrationLabel, REFUSAL, refuseNewerDatabase, type MigrationSafetyNet } from '../../legacy-baseline';
|
||||
import type { AnyOrm } from '../../orm';
|
||||
import { readPostgresBaseline, type PostgresBaseline } from './baseline';
|
||||
import type { Connection } from '@mikro-orm/core';
|
||||
import type { Migrator } from '@mikro-orm/migrations';
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
const logger = new Logger('DB');
|
||||
|
||||
/** What a Postgres bootstrap reads, passed in so a test can supply its own. */
|
||||
export interface PostgresBootstrapDeps {
|
||||
baseline: () => PostgresBaseline;
|
||||
known: Set<string>;
|
||||
safetyNet: MigrationSafetyNet;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tables in the current schema. A database with no TREK migration history
|
||||
* must hold none: TREK creates its schema in an empty database and never
|
||||
* adopts tables something else made. Read before anything is written, so a
|
||||
* refused database is left exactly as it was.
|
||||
*/
|
||||
async function currentTables(connection: Connection): Promise<string[]> {
|
||||
const rows: Array<{ table_name: string }> = await connection.execute(
|
||||
'select table_name from information_schema.tables where table_schema = current_schema() order by table_name',
|
||||
);
|
||||
return rows.map((row) => row.table_name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a Postgres database to the current schema.
|
||||
*
|
||||
* - No migration recorded and no table: the baseline runs and every migration
|
||||
* it stands for is recorded as executed, in one transaction (DDL is
|
||||
* transactional on Postgres, so the database ends with all of it or none).
|
||||
* - No migration recorded but tables present: refused, naming a few of them.
|
||||
* - Migrations recorded: refused when one is unknown to this build (a newer
|
||||
* TREK migrated it), else the pending migrations run, after the safety net.
|
||||
* A database the baseline just created runs the migrations after the
|
||||
* baseline's cut without it: there is nothing yet to lose.
|
||||
*/
|
||||
export async function bootstrapPostgresSchema(orm: AnyOrm, deps: PostgresBootstrapDeps): Promise<void> {
|
||||
const migrator = orm.config.getExtension('@mikro-orm/migrator') as Migrator;
|
||||
const connection = orm.em.getConnection();
|
||||
const storage = migrator.getStorage();
|
||||
const historyTable = orm.config.get('migrations').tableName ?? 'mikro_orm_migrations';
|
||||
const tables = await currentTables(connection);
|
||||
const executed = tables.includes(historyTable) ? (await migrator.getExecuted()).map((row) => row.name) : [];
|
||||
const created = executed.length === 0;
|
||||
|
||||
if (created) {
|
||||
const foreign = tables.filter((table) => table !== historyTable);
|
||||
if (foreign.length > 0) {
|
||||
throw new Error(
|
||||
`${REFUSAL} the database holds ${foreign.length} table(s) (${foreign.slice(0, 5).join(', ')}) but no TREK ` +
|
||||
'migration history. Point TREK_DB_URL at an empty database.',
|
||||
);
|
||||
}
|
||||
await storage.ensureTable();
|
||||
const baseline = deps.baseline();
|
||||
logger.log(`Creating the schema in an empty Postgres database (through ${migrationLabel(baseline.through)})`);
|
||||
await connection.transactional(async (trx) => {
|
||||
// One round trip: without parameters pg sends it as a simple query, which may hold many statements.
|
||||
await connection.execute(baseline.statements.join(';\n'), [], 'run', trx);
|
||||
await Promise.all(baseline.migrations.map((name) => storage.logMigration({ name }, trx)));
|
||||
});
|
||||
} else {
|
||||
refuseNewerDatabase(executed, deps.known);
|
||||
}
|
||||
|
||||
const pending = await migrator.getPending();
|
||||
if (pending.length === 0) return;
|
||||
// A database created just now holds nothing a migration could lose.
|
||||
if (!created) await deps.safetyNet.beforeMigrate(migrationLabel([...executed].sort().at(-1) as string));
|
||||
logger.log(`Applying ${pending.length} pending migration(s)`);
|
||||
await migrator.up();
|
||||
}
|
||||
|
||||
/**
|
||||
* The Postgres safety net before pending migrations. This release cannot copy
|
||||
* a Postgres database (the SQLite engine's `VACUUM INTO` has no Postgres
|
||||
* equivalent short of `pg_dump`), so it refuses unless the operator turned
|
||||
* the copy off: fail closed, rather than migrate with nothing to go back to.
|
||||
* Off under NODE_ENV=test unless a suite asks for it, as on SQLite.
|
||||
*/
|
||||
export function postgresSafetyNet(env: () => AppEnv = readEnv): MigrationSafetyNet {
|
||||
return {
|
||||
async beforeMigrate() {
|
||||
const { db, app } = env();
|
||||
if (db.preMigrateSnapshot === undefined && app.isTest) return;
|
||||
if (db.preMigrateSnapshot === false) {
|
||||
logger.warn('TREK_DB_PRE_MIGRATE_SNAPSHOT is off: migrating the Postgres database without a copy');
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
`${REFUSAL} migrations are pending and TREK cannot copy a Postgres database before migrating it in this ` +
|
||||
'release. Back it up with pg_dump, then start once with TREK_DB_PRE_MIGRATE_SNAPSHOT=false.',
|
||||
);
|
||||
},
|
||||
restoreHint: async () => null,
|
||||
};
|
||||
}
|
||||
|
||||
/** What a production boot passes: the committed baseline, the migrations on disk, the safety net above. */
|
||||
export function defaultPostgresBootstrapDeps(): PostgresBootstrapDeps {
|
||||
return { baseline: readPostgresBaseline, known: knownMigrationNames(), safetyNet: postgresSafetyNet() };
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
import { closeDb, getRawConnection, registerReinitializeHook, reinitialize } from '../../database';
|
||||
import { resolveDbPath } from '../../db-path';
|
||||
import { runSchemaBootstrap, type AnyOrm } from '../../orm';
|
||||
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).
|
||||
* on `TREK_DB_FILE` or `data/travel.db` (`:memory:` under test). A restore
|
||||
* swaps the file and reopens the handle; the schema comes from the migration
|
||||
* chain (`db/orm.ts`).
|
||||
*/
|
||||
export class SqliteEngine implements DatabaseEngine {
|
||||
readonly id = 'sqlite';
|
||||
readonly ready = true;
|
||||
|
||||
describe(): string {
|
||||
return `SQLite file ${resolveDbPath()}`;
|
||||
@@ -18,4 +21,23 @@ export class SqliteEngine implements DatabaseEngine {
|
||||
ormOptions() {
|
||||
return { driver: SharedSqliteDriver, dbName: resolveDbPath() };
|
||||
}
|
||||
|
||||
open(onReopened: () => Promise<void>): void {
|
||||
// Normally a no-op: the ORM's first connect inside NestFactory.create()
|
||||
// already opened it. Said here so the boot does not depend on that.
|
||||
getRawConnection();
|
||||
registerReinitializeHook(onReopened);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
closeDb();
|
||||
}
|
||||
|
||||
reopen(): Promise<void> {
|
||||
return reinitialize();
|
||||
}
|
||||
|
||||
schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void> {
|
||||
return runSchemaBootstrap(orm, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { columnNamesSql, tableExistsSql } from './dialect/catalog';
|
||||
import { TableNotFoundException } from '@mikro-orm/core';
|
||||
import type { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
@@ -8,7 +10,7 @@ import type { Migration } from '@mikro-orm/migrations';
|
||||
* a migration class.
|
||||
*/
|
||||
|
||||
/** A single `pragma_table_info` row — only the column name is ever read. */
|
||||
/** A catalog row (`dialect/catalog.ts`): only the name is ever read. */
|
||||
interface ColumnRow {
|
||||
name: string;
|
||||
}
|
||||
@@ -30,21 +32,18 @@ export async function addColumnIfMissing(
|
||||
column: string,
|
||||
definition: string,
|
||||
): Promise<void> {
|
||||
const existing = (await migration.execute('select name from pragma_table_info(?) where name = ?', [
|
||||
table,
|
||||
column,
|
||||
])) as ColumnRow[];
|
||||
if (existing.length > 0) return;
|
||||
await migration.execute(`alter table \`${table}\` add column ${definition}`);
|
||||
if ((await columnNames(migration, table)).has(column)) return;
|
||||
const platform = migration.getEntityManager().getPlatform();
|
||||
await migration.execute(`alter table ${platform.quoteIdentifier(table)} add column ${definition}`);
|
||||
}
|
||||
|
||||
/** True when `table` exists in the current database. */
|
||||
export async function tableExists(migration: Migration, table: string): Promise<boolean> {
|
||||
const rows = await migration.execute(`select name from sqlite_master where type = 'table' and name = ?`, [table]);
|
||||
const rows = await migration.execute(tableExistsSql(migration.getEntityManager().getPlatform()), [table]);
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
/** The `CREATE TABLE` DDL SQLite stored for `table`, or null when it does not exist. */
|
||||
/** The `CREATE TABLE` DDL SQLite stored for `table`, or null when it does not exist. SQLite only: Postgres keeps no such text. */
|
||||
export async function tableSql(migration: Migration, table: string): Promise<string | null> {
|
||||
const rows = (await migration.execute(`select sql from sqlite_master where name = ?`, [table])) as {
|
||||
sql: string | null;
|
||||
@@ -68,7 +67,8 @@ export async function execBestEffort(migration: Migration, sql: string, params?:
|
||||
|
||||
/** The column names of `table`, or an empty set when the table does not exist. */
|
||||
export async function columnNames(migration: Migration, table: string): Promise<Set<string>> {
|
||||
const rows = (await migration.execute('select name from pragma_table_info(?)', [table])) as ColumnRow[];
|
||||
const sql = columnNamesSql(migration.getEntityManager().getPlatform());
|
||||
const rows = (await migration.execute(sql, [table])) as ColumnRow[];
|
||||
return new Set(rows.map((r) => r.name));
|
||||
}
|
||||
|
||||
@@ -80,7 +80,9 @@ export async function execUnlessTableMissing(migration: Migration, sql: string,
|
||||
try {
|
||||
await migration.execute(sql, params);
|
||||
} catch (err: unknown) {
|
||||
if (!(err instanceof Error) || !err.message.includes('no such table')) throw err;
|
||||
const missing =
|
||||
err instanceof TableNotFoundException || (err instanceof Error && err.message.includes('no such table'));
|
||||
if (!missing) throw err;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-25
@@ -1,4 +1,3 @@
|
||||
import mikroOrmConfig from '../mikro-orm.config';
|
||||
import { withRequestContext } from '../nest/database/request-context';
|
||||
import { runDemoSeed } from './database';
|
||||
import { ensureEmailCaseIndex } from './email-case-index';
|
||||
@@ -6,7 +5,6 @@ import { migrateToHead, NO_SAFETY_NET } from './legacy-baseline';
|
||||
import { preMigrateSnapshot } from './pre-migrate-snapshot';
|
||||
import type { AnyEntity, EntityClass, EntityManager, EntitySchema, IDatabaseDriver, MikroORM } from '@mikro-orm/core';
|
||||
import type { Migrator } from '@mikro-orm/migrations';
|
||||
import { MikroORM as SqliteMikroORM } from '@mikro-orm/sqlite';
|
||||
|
||||
/**
|
||||
* Schema ownership at startup.
|
||||
@@ -52,8 +50,16 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot = true }: { sna
|
||||
undefined,
|
||||
snapshot ? preMigrateSnapshot(connection) : NO_SAFETY_NET,
|
||||
);
|
||||
await finishSchemaBootstrap(orm);
|
||||
}
|
||||
|
||||
/**
|
||||
* What every engine does once its schema is at head: the deferred index, the
|
||||
* seeders, the demo seed. Idempotent, like the migration step before it.
|
||||
*/
|
||||
export async function finishSchemaBootstrap(orm: AnyOrm): Promise<void> {
|
||||
// The one index a migration may have had to defer (see email-case-index.ts).
|
||||
await ensureEmailCaseIndex(connection);
|
||||
await ensureEmailCaseIndex(orm.em.getConnection());
|
||||
|
||||
const defaultSeeder = orm.config.get('seeder').defaultSeeder;
|
||||
if (defaultSeeder) await orm.seeder.seedString(defaultSeeder);
|
||||
@@ -77,25 +83,3 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot = true }: { sna
|
||||
// fully-synchronous version had by construction.
|
||||
await withRequestContext(orm, () => runDemoSeed());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function createStandaloneOrm(): Promise<AnyOrm> {
|
||||
return SqliteMikroORM.init({
|
||||
...mikroOrmConfig,
|
||||
// Entity discovery is skipped deliberately. Migrations and seeders are raw
|
||||
// SQL and need no metadata, and the global setup that calls this runs as ESM
|
||||
// in vitest's main process, where discovering `*.entity.ts` fails on Node's
|
||||
// extensionless import resolution.
|
||||
entities: [],
|
||||
entitiesTs: [],
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
// The migrator's per-migration progress log is production boot output; the
|
||||
// global setup already reports the snapshot in one line of its own, and a
|
||||
// failing migration still throws.
|
||||
migrations: { ...mikroOrmConfig.migrations, silent: true },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import mikroOrmConfig from '../mikro-orm.config';
|
||||
import type { AnyOrm } from './orm';
|
||||
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.
|
||||
*/
|
||||
export function createStandaloneOrm(): Promise<AnyOrm> {
|
||||
return SqliteMikroORM.init({
|
||||
...mikroOrmConfig,
|
||||
// Entity discovery is skipped deliberately. Migrations and seeders are raw
|
||||
// SQL and need no metadata, and the global setup that calls this runs as ESM
|
||||
// in vitest's main process, where discovering `*.entity.ts` fails on Node's
|
||||
// extensionless import resolution.
|
||||
entities: [],
|
||||
entitiesTs: [],
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
// The migrator's per-migration progress log is production boot output; the
|
||||
// global setup already reports the snapshot in one line of its own, and a
|
||||
// failing migration still throws.
|
||||
migrations: { ...mikroOrmConfig.migrations, silent: true },
|
||||
});
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import { DATABASE_BACKUP } from '../database/database-backup.interface';
|
||||
import { resolveEngine } from '../../db/engine';
|
||||
import { DATABASE_BACKUP, type DatabaseBackupStrategy } from '../database/database-backup.interface';
|
||||
import { DatabaseLifecycleModule } from '../database/database-lifecycle.module';
|
||||
import { MaintenanceModule } from '../database/maintenance.module';
|
||||
import { PostgresDatabaseBackup } from './postgres-database-backup';
|
||||
import { SqliteDatabaseBackup } from './sqlite-database-backup';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Binds the database backup port (`DATABASE_BACKUP`) to the engine in use.
|
||||
* Binds the database backup port (`DATABASE_BACKUP`) to the engine in use
|
||||
* (`TREK_DB_URL`, read at boot through `resolveEngine()`).
|
||||
*
|
||||
* Global because its consumers sit in two domains: the backup domain itself
|
||||
* and the admin domain (the demo reset job and the baseline route). Admin
|
||||
@@ -20,7 +23,16 @@ import { Global, Module } from '@nestjs/common';
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [DatabaseLifecycleModule, MaintenanceModule],
|
||||
providers: [SqliteDatabaseBackup, { provide: DATABASE_BACKUP, useExisting: SqliteDatabaseBackup }],
|
||||
providers: [
|
||||
SqliteDatabaseBackup,
|
||||
PostgresDatabaseBackup,
|
||||
{
|
||||
provide: DATABASE_BACKUP,
|
||||
useFactory: (sqlite: SqliteDatabaseBackup, postgres: PostgresDatabaseBackup): DatabaseBackupStrategy =>
|
||||
({ sqlite, postgres })[resolveEngine().id],
|
||||
inject: [SqliteDatabaseBackup, PostgresDatabaseBackup],
|
||||
},
|
||||
],
|
||||
exports: [DATABASE_BACKUP],
|
||||
})
|
||||
export class DatabaseBackupModule {}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { resolveEngine } from '../../db/engine';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import type { DatabaseBackupStrategy } from '../database/database-backup.interface';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
/** Why a backup or a restore of a Postgres database is refused in this release. */
|
||||
export const POSTGRES_BACKUP_UNAVAILABLE =
|
||||
'Backups of a Postgres database are not available in this release: back it up with pg_dump.';
|
||||
|
||||
/**
|
||||
* The backup port on a Postgres database, before TREK can dump and load one.
|
||||
* Fails closed: a backup reports that it wrote nothing (rather than writing an
|
||||
* archive with the uploads and no database), a restore is refused before
|
||||
* anything is replaced, and the demo reset never gets a baseline to swap in.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PostgresDatabaseBackup implements DatabaseBackupStrategy {
|
||||
readonly archiveEntry = 'database.dump';
|
||||
|
||||
location(): string {
|
||||
return resolveEngine().describe();
|
||||
}
|
||||
|
||||
canSnapshot(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
async checkpoint(): Promise<void> {
|
||||
// Postgres keeps nothing beside its store that a copy would need flushed.
|
||||
}
|
||||
|
||||
snapshot(): Promise<void> {
|
||||
return Promise.reject(new Error(POSTGRES_BACKUP_UNAVAILABLE));
|
||||
}
|
||||
|
||||
/** Refuses before anything is replaced; the restore removes what it unpacked and answers 400. */
|
||||
verify(): never {
|
||||
throw new DomainError(400, POSTGRES_BACKUP_UNAVAILABLE);
|
||||
}
|
||||
|
||||
async keepCopyBeforeRestore(): Promise<string | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
replace(): Promise<{ reopenError: unknown }> {
|
||||
return Promise.reject(new Error(POSTGRES_BACKUP_UNAVAILABLE));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { closeDb, getRawConnection, registerReinitializeHook, reinitialize } from '../../db/database';
|
||||
import { resolveDbPath } from '../../db/db-path';
|
||||
import { runSchemaBootstrap } from '../../db/orm';
|
||||
import { resolveEngine } from '../../db/engine';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@@ -16,13 +15,14 @@ import { Injectable } from '@nestjs/common';
|
||||
* port), and the shutdown closes through this. Nothing opens the database at
|
||||
* import any more; the first connect does, and this provider makes it explicit.
|
||||
*
|
||||
* Only the SQLite file engine exists today. The engine specific parts (the file
|
||||
* path, the swap) are confined to `file` and to the backup port's SQLite
|
||||
* implementation, so another engine changes this provider and that one class.
|
||||
* What differs by engine (a file to open or not, how a database reaches the
|
||||
* schema) is the engine's (`db/engine/`), chosen from `TREK_DB_URL`: this
|
||||
* provider decides when, the engine decides how.
|
||||
*/
|
||||
@Injectable()
|
||||
export class DatabaseLifecycle {
|
||||
private readonly reopenListeners: Array<() => Promise<void>> = [];
|
||||
private readonly engine = resolveEngine();
|
||||
|
||||
constructor(private readonly orm: MikroORM) {}
|
||||
|
||||
@@ -37,21 +37,19 @@ export class DatabaseLifecycle {
|
||||
|
||||
/**
|
||||
* Opens the connection, binds the ORM to its later swaps and brings the schema
|
||||
* to head (legacy baseline, migrations, the deferred index, seeders, demo
|
||||
* seed, in that order: see `db/orm.ts`). Called once by `buildApp()`, before
|
||||
* anything reads the database.
|
||||
* to head (on SQLite: legacy baseline, migrations, the deferred index,
|
||||
* seeders, demo seed, in that order, see `db/orm.ts`; on Postgres: the
|
||||
* baseline or the migrations after it, then the same seeding). Called once
|
||||
* by `buildApp()`, before anything reads the database.
|
||||
*/
|
||||
async open(): Promise<void> {
|
||||
// Normally a no-op: the ORM's first connect inside NestFactory.create()
|
||||
// already opened it. Said here so the boot does not depend on that.
|
||||
getRawConnection();
|
||||
registerReinitializeHook(() => this.rebindOrm());
|
||||
await runSchemaBootstrap(this.orm);
|
||||
this.engine.open(() => this.rebindOrm());
|
||||
await this.engine.schemaBootstrap(this.orm, { snapshot: true });
|
||||
}
|
||||
|
||||
/** Checkpoints and closes the connection. A closed connection stays closed until `reopen()`. */
|
||||
close(): void {
|
||||
closeDb();
|
||||
this.engine.close();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,7 +58,7 @@ export class DatabaseLifecycle {
|
||||
* restored backup may predate this release).
|
||||
*/
|
||||
async reopen(): Promise<void> {
|
||||
await reinitialize();
|
||||
await this.engine.reopen();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,7 +88,7 @@ export class DatabaseLifecycle {
|
||||
await connection.connect();
|
||||
// No pre-migrate snapshot: the file was just unpacked from an archive that
|
||||
// is still there to go back to.
|
||||
await runSchemaBootstrap(this.orm, { snapshot: false });
|
||||
await this.engine.schemaBootstrap(this.orm, { snapshot: false });
|
||||
for (const listener of this.reopenListeners) await listener();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user