mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 15:17:30 +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:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user