mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
feat(db): back up, restore and copy a Postgres database before migrating it
On Postgres the backup port dumps with pg_dump and restores by turning the dump into a script with pg_restore and having psql clear the current schema and run it in one transaction. A dump only recreates what it holds, so a plain pg_restore --clean would leave a later migration's tables behind and break the migrations the reopen runs; a restore that fails leaves the database as it was. A restore refuses a pg_restore or psql older than 17.6/16.10/15.14/14.19, whose script would lack the \restrict line that keeps a psql meta-command smuggled into an uploaded dump from running (CVE-2025-8714). A restore refuses a SQLite archive, a dump without TREK's migration history or one a newer TREK wrote before anything is replaced, and keeps a dump of the database it replaces. RESTORE_FROM_BACKUP loads the archive's dump the same way into a database that holds no table yet, and is ignored with a warning once it holds one. Before pending migrations the boot now takes a pg_dump copy to data/pre-migrate-<last migration>-<time>.pgdump under the same TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP) policy as the SQLite file, instead of refusing; a copy that cannot be written refuses the boot. The tools run by absolute path (TREK_DB_PG_BIN_DIR, or the usual directories), never through PATH, with the password in PGPASSWORD; an sslmode that asks for SSL verifies the certificate as the app pool does. Dumps are written beside their target and renamed into place, readable by their owner only, and a tool's stderr reaches errors without the lines that quote SQL or rows. The image installs postgresql-client-17 from Debian 13.
This commit is contained in:
@@ -0,0 +1,309 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/** The Postgres client tools a backup runs. */
|
||||
type PgTool = 'pg_dump' | 'pg_restore' | 'psql';
|
||||
|
||||
/**
|
||||
* Where the client tools are looked for when `TREK_DB_PG_BIN_DIR` is unset:
|
||||
* Debian's versioned directories newest first (the Docker image installs 17),
|
||||
* then the usual prefixes. Never PATH: a binary is run by its absolute path.
|
||||
*/
|
||||
const DEFAULT_BIN_DIRS = [
|
||||
'/usr/lib/postgresql/17/bin',
|
||||
'/usr/lib/postgresql/16/bin',
|
||||
'/usr/lib/postgresql/15/bin',
|
||||
'/usr/lib/postgresql/14/bin',
|
||||
'/usr/local/bin',
|
||||
'/usr/bin',
|
||||
];
|
||||
|
||||
/** A dump or a restore of a large database takes minutes, not hours. */
|
||||
const TOOL_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
const TOOL_MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
|
||||
/** An unreachable host fails the tool in seconds instead of holding a boot or a restore. */
|
||||
const CONNECT_TIMEOUT_SECONDS = '10';
|
||||
/**
|
||||
* A restore waiting on a lock another session holds gives up, and rolls back,
|
||||
* instead of hanging; the NOTICEs every CASCADE prints stay out of its stderr.
|
||||
*/
|
||||
const RESTORE_SESSION_OPTIONS = '-c lock_timeout=60s -c client_min_messages=warning';
|
||||
/** How much of a tool's stderr an error keeps. */
|
||||
const STDERR_LIMIT = 2000;
|
||||
/** stderr lines that quote SQL or row data: they stay out of errors and logs. */
|
||||
const DATA_LINE = /^\s*(Command was:|CONTEXT:|DETAIL:|LINE \d+:|QUERY:)/;
|
||||
|
||||
/**
|
||||
* Drops every table, view, sequence, routine, collation and standalone type in
|
||||
* the current schema, except an extension's, before a dump is loaded: a dump only recreates what it
|
||||
* holds, so whatever a later migration added would otherwise survive the
|
||||
* restore and break the migrations the reopen runs. It runs in the same
|
||||
* transaction as the load, so a restore that fails leaves the database as it
|
||||
* was.
|
||||
*/
|
||||
const CLEAR_SCHEMA_SQL = `DO $clear$
|
||||
DECLARE r record;
|
||||
BEGIN
|
||||
FOR r IN SELECT c.oid::regclass AS name, c.relkind FROM pg_class c
|
||||
WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype IN ('e', 'a', 'i'))
|
||||
LOOP
|
||||
EXECUTE format('DROP %s IF EXISTS %s CASCADE',
|
||||
CASE r.relkind WHEN 'v' THEN 'VIEW' WHEN 'm' THEN 'MATERIALIZED VIEW' WHEN 'S' THEN 'SEQUENCE'
|
||||
WHEN 'f' THEN 'FOREIGN TABLE' ELSE 'TABLE' END, r.name);
|
||||
END LOOP;
|
||||
FOR r IN SELECT p.oid::regprocedure AS sig FROM pg_proc p
|
||||
WHERE p.pronamespace = current_schema()::regnamespace
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')
|
||||
LOOP
|
||||
EXECUTE format('DROP ROUTINE IF EXISTS %s CASCADE', r.sig);
|
||||
END LOOP;
|
||||
FOR r IN SELECT format('%I.%I', n.nspname, c.collname) AS name FROM pg_collation c
|
||||
JOIN pg_namespace n ON n.oid = c.collnamespace
|
||||
WHERE n.nspname = current_schema()
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype = 'e')
|
||||
LOOP
|
||||
EXECUTE format('DROP COLLATION IF EXISTS %s CASCADE', r.name);
|
||||
END LOOP;
|
||||
FOR r IN SELECT t.oid::regtype AS name FROM pg_type t
|
||||
WHERE t.typnamespace = current_schema()::regnamespace AND t.typtype IN ('e', 'd', 'r')
|
||||
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = t.oid AND d.deptype IN ('e', 'i'))
|
||||
LOOP
|
||||
EXECUTE format('DROP TYPE IF EXISTS %s CASCADE', r.name);
|
||||
END LOOP;
|
||||
END
|
||||
$clear$;
|
||||
`;
|
||||
|
||||
/** The absolute path of `tool`, or null when it is not installed where TREK looks. */
|
||||
export function resolvePgTool(tool: PgTool, binDir: string | undefined): string | null {
|
||||
const dirs = binDir ? [binDir] : DEFAULT_BIN_DIRS;
|
||||
const executable = (candidate: string): boolean => {
|
||||
try {
|
||||
fs.accessSync(candidate, fs.constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false; // missing or not executable: the next directory may have it
|
||||
}
|
||||
};
|
||||
return dirs.map((dir) => path.join(dir, tool)).find(executable) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The libpq environment for `url`: the tools read the password from
|
||||
* PGPASSWORD, so it never appears in an argument list another process can
|
||||
* read. An sslmode that asks for SSL verifies the server's certificate, as the
|
||||
* app's own pool does (`postgres-engine.ts`): against the URL's sslrootcert,
|
||||
* else the system's trusted CAs.
|
||||
*/
|
||||
export function pgConnectionEnv(url: string): Record<string, string> {
|
||||
const parsed = new URL(url);
|
||||
const env: Record<string, string> = {
|
||||
PGHOST: parsed.hostname.replace(/^\[(.*)\]$/, '$1'),
|
||||
PGPORT: parsed.port || '5432',
|
||||
PGDATABASE: decodeURIComponent(parsed.pathname.replace(/^\//, '')),
|
||||
PGCONNECT_TIMEOUT: CONNECT_TIMEOUT_SECONDS,
|
||||
};
|
||||
if (parsed.username) env.PGUSER = decodeURIComponent(parsed.username);
|
||||
if (parsed.password) env.PGPASSWORD = decodeURIComponent(parsed.password);
|
||||
const sslmode = parsed.searchParams.get('sslmode');
|
||||
if (sslmode === 'disable') env.PGSSLMODE = 'disable';
|
||||
else if (sslmode) {
|
||||
env.PGSSLMODE = 'verify-full';
|
||||
env.PGSSLROOTCERT = parsed.searchParams.get('sslrootcert') ?? 'system';
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
/** A client tool, refused with a clear message when it is not installed. */
|
||||
export class PgToolMissingError extends Error {
|
||||
constructor(tool: PgTool) {
|
||||
super(
|
||||
`${tool} was not found, so a Postgres database cannot be backed up or restored. ` +
|
||||
'Install the PostgreSQL client tools (the Docker image has them) or point TREK_DB_PG_BIN_DIR at them.',
|
||||
);
|
||||
this.name = 'PgToolMissingError';
|
||||
}
|
||||
}
|
||||
|
||||
/** The tool's own message, without the lines that quote SQL or rows, and bounded. */
|
||||
function summarizeStderr(stderr: string | undefined): string {
|
||||
const kept = (stderr ?? '')
|
||||
.split('\n')
|
||||
.filter((line) => line.trim() !== '' && !DATA_LINE.test(line))
|
||||
.join('\n');
|
||||
return kept.length > STDERR_LIMIT ? `${kept.slice(0, STDERR_LIMIT)}…` : kept;
|
||||
}
|
||||
|
||||
async function run(
|
||||
tool: PgTool,
|
||||
binDir: string | undefined,
|
||||
args: string[],
|
||||
env: Record<string, string>,
|
||||
): Promise<string> {
|
||||
const binary = resolvePgTool(tool, binDir);
|
||||
if (!binary) throw new PgToolMissingError(tool);
|
||||
try {
|
||||
const { stdout } = await execFileAsync(binary, args, {
|
||||
env,
|
||||
timeout: TOOL_TIMEOUT_MS,
|
||||
maxBuffer: TOOL_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
return stdout;
|
||||
} catch (err) {
|
||||
// stderr is the tool's own message; the password is in env, never in it.
|
||||
const message = summarizeStderr((err as { stderr?: string }).stderr);
|
||||
throw new Error(`${tool} failed${message ? `: ${message}` : ''}`, { cause: err });
|
||||
}
|
||||
}
|
||||
|
||||
/** An empty file only its owner can read: the tool writing into it keeps the mode. */
|
||||
function createPrivateFile(file: string): void {
|
||||
fs.writeFileSync(file, '', { mode: 0o600 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a custom-format dump of the database at `url` to `target`, readable
|
||||
* by its owner only. It is written beside the target and renamed into place,
|
||||
* so a dump that fails or is killed never leaves a file that passes for a copy.
|
||||
*/
|
||||
export async function pgDump(url: string, target: string, binDir: string | undefined): Promise<void> {
|
||||
const partial = `${target}.partial`;
|
||||
try {
|
||||
createPrivateFile(partial);
|
||||
await run(
|
||||
'pg_dump',
|
||||
binDir,
|
||||
['--format=custom', '--no-owner', '--no-privileges', `--file=${partial}`],
|
||||
pgConnectionEnv(url),
|
||||
);
|
||||
fs.renameSync(partial, target);
|
||||
} catch (err) {
|
||||
fs.rmSync(partial, { force: true });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The first minor of each major whose pg_restore and psql carry the fix for
|
||||
* CVE-2025-8714; every major after 17 has it from its first release.
|
||||
*/
|
||||
const RESTRICT_SINCE: Readonly<Record<number, number>> = { 14: 19, 15: 14, 16: 10, 17: 6 };
|
||||
const LAST_MAJOR_WITHOUT_IT = 17;
|
||||
const OLDEST_MAJOR = 14;
|
||||
|
||||
/** Whether `version` (`pg_restore (PostgreSQL) 17.11 (Debian …)`) carries the fix. */
|
||||
export function hasRestrictFix(version: string): boolean {
|
||||
const match = /\(PostgreSQL\) (\d+)\.(\d+)/.exec(version);
|
||||
if (!match) return false;
|
||||
const major = Number(match[1]);
|
||||
const minor = Number(match[2]);
|
||||
if (major > LAST_MAJOR_WITHOUT_IT) return true;
|
||||
return major >= OLDEST_MAJOR && minor >= RESTRICT_SINCE[major];
|
||||
}
|
||||
|
||||
/**
|
||||
* A script from a dump an admin uploaded is run by psql, which would also run
|
||||
* a psql meta-command (`\!` runs a shell command) smuggled into an object
|
||||
* name. A fixed pg_restore opens the script with `\restrict <random key>`, and
|
||||
* a fixed psql then refuses every meta-command until the matching
|
||||
* `\unrestrict` (CVE-2025-8714). The tools' own versions are checked, not the
|
||||
* script, whose text the dump controls.
|
||||
*/
|
||||
async function refuseToolsWithoutRestrict(binDir: string | undefined): Promise<void> {
|
||||
const tools = ['pg_restore', 'psql'] as const;
|
||||
const versions = await Promise.all(tools.map((tool) => run(tool, binDir, ['--version'], {})));
|
||||
const stale = tools.findIndex((_, i) => !hasRestrictFix(versions[i]));
|
||||
if (stale >= 0) {
|
||||
throw new Error(
|
||||
`${tools[stale]} is too old to restore safely (${versions[stale].trim()}): it must be at least 17.6, 16.10, ` +
|
||||
'15.14 or 14.19 (the Docker image has 17). Upgrade the PostgreSQL client tools or point TREK_DB_PG_BIN_DIR at newer ones.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the database at `url` with the dump at `source`: pg_restore turns
|
||||
* the dump into a script beside it, then psql clears the current schema and
|
||||
* runs the script in one transaction, so a restore that fails leaves the
|
||||
* database as it was.
|
||||
*/
|
||||
export async function pgRestore(url: string, source: string, binDir: string | undefined): Promise<void> {
|
||||
await refuseToolsWithoutRestrict(binDir);
|
||||
const workDir = fs.mkdtempSync(path.join(path.dirname(source), '.pg-restore-'));
|
||||
try {
|
||||
const clear = path.join(workDir, 'clear-schema.sql');
|
||||
const script = path.join(workDir, 'restore.sql');
|
||||
fs.writeFileSync(clear, CLEAR_SCHEMA_SQL, { mode: 0o600 });
|
||||
createPrivateFile(script);
|
||||
await run('pg_restore', binDir, ['--no-owner', '--no-privileges', `--file=${script}`, '--', source], {});
|
||||
await run(
|
||||
'psql',
|
||||
binDir,
|
||||
[
|
||||
'--no-psqlrc',
|
||||
'--quiet',
|
||||
'--single-transaction',
|
||||
'--set=ON_ERROR_STOP=1',
|
||||
'--output=/dev/null',
|
||||
`--file=${clear}`,
|
||||
`--file=${script}`,
|
||||
],
|
||||
{ ...pgConnectionEnv(url), PGOPTIONS: RESTORE_SESSION_OPTIONS },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(workDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** The tables in the current schema of the database at `url`, read before TREK opens it. */
|
||||
export async function pgTableNames(url: string, binDir: string | undefined): Promise<string[]> {
|
||||
const out = await run(
|
||||
'psql',
|
||||
binDir,
|
||||
[
|
||||
'--no-psqlrc',
|
||||
'--no-align',
|
||||
'--tuples-only',
|
||||
'--command=select table_name from information_schema.tables where table_schema = current_schema()',
|
||||
],
|
||||
pgConnectionEnv(url),
|
||||
);
|
||||
return out.split('\n').filter((line) => line !== '');
|
||||
}
|
||||
|
||||
/**
|
||||
* The migrations a dump records as executed, read from the dump itself (its
|
||||
* `mikro_orm_migrations` rows as COPY text), so a restore can refuse a newer
|
||||
* TREK's backup before anything is replaced. Throws on a file that is not a
|
||||
* dump; an empty list means the dump holds no TREK history.
|
||||
*/
|
||||
export async function pgDumpMigrations(source: string, binDir: string | undefined): Promise<string[]> {
|
||||
const script = await run(
|
||||
'pg_restore',
|
||||
binDir,
|
||||
['--data-only', '--table=mikro_orm_migrations', '--file=-', '--', source],
|
||||
{},
|
||||
);
|
||||
const lines = script.split('\n');
|
||||
const copy = lines.findIndex((line) => /^COPY \S*mikro_orm_migrations \(/.test(line));
|
||||
if (copy < 0) return [];
|
||||
const columns =
|
||||
/\(([^)]*)\)/
|
||||
.exec(lines[copy])?.[1]
|
||||
.split(',')
|
||||
.map((column) => column.trim()) ?? [];
|
||||
const nameAt = columns.indexOf('name');
|
||||
if (nameAt < 0) return [];
|
||||
const names: string[] = [];
|
||||
for (const line of lines.slice(copy + 1)) {
|
||||
if (line === '\\.' || line === '') break;
|
||||
const name = line.split('\t')[nameAt];
|
||||
if (name) names.push(name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { NO_SAFETY_NET } from '../../legacy-baseline';
|
||||
import { finishSchemaBootstrap, type AnyOrm } from '../../orm';
|
||||
import type { DatabaseEngine } from '../engine';
|
||||
import { redactUrl } from '../redact-url';
|
||||
@@ -69,19 +70,28 @@ export class PostgresEngine implements DatabaseEngine {
|
||||
|
||||
constructor(
|
||||
private readonly settings: PostgresSettings,
|
||||
private readonly bootstrapDeps: () => PostgresBootstrapDeps = defaultPostgresBootstrapDeps,
|
||||
private readonly bootstrapDeps: (url: string) => PostgresBootstrapDeps = defaultPostgresBootstrapDeps,
|
||||
) {}
|
||||
|
||||
open(): void {
|
||||
// Nothing of its own to open: the ORM connects the pool.
|
||||
private onReopened: (() => Promise<void>) | null = null;
|
||||
|
||||
/** Nothing of its own to open (the ORM connects the pool); keeps what a reopen runs. */
|
||||
open(onReopened: () => Promise<void>): void {
|
||||
this.onReopened = onReopened;
|
||||
}
|
||||
|
||||
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.'));
|
||||
/**
|
||||
* After `pg_restore` replaced the database's contents: the ORM reconnects
|
||||
* and the restored database is migrated forward (`onReopened`, which
|
||||
* `DatabaseLifecycle` hands to `open`).
|
||||
*/
|
||||
async reopen(): Promise<void> {
|
||||
if (!this.onReopened) throw new Error('The Postgres engine was reopened before it was opened.');
|
||||
await this.onReopened();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,8 +105,10 @@ export class PostgresEngine implements DatabaseEngine {
|
||||
.execute('select pg_advisory_xact_lock(?)', [TREK_WRITE_LOCK], 'run', em.getTransactionContext());
|
||||
}
|
||||
|
||||
async schemaBootstrap(orm: AnyOrm): Promise<void> {
|
||||
await bootstrapPostgresSchema(orm, this.bootstrapDeps());
|
||||
/** `snapshot: false` (a restore, whose archive is the copy) migrates without a pg_dump first. */
|
||||
async schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void> {
|
||||
const deps = this.bootstrapDeps(this.settings.url);
|
||||
await bootstrapPostgresSchema(orm, options.snapshot ? deps : { ...deps, safetyNet: NO_SAFETY_NET });
|
||||
await finishSchemaBootstrap(orm);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
import { readEnv, type AppEnv } from '../../../app-config';
|
||||
import { resolveDataPaths } from '../../../app-config/data-paths';
|
||||
import { knownMigrationNames } from '../../known-migrations';
|
||||
import { migrationLabel, REFUSAL, refuseNewerDatabase, type MigrationSafetyNet } from '../../legacy-baseline';
|
||||
import type { AnyOrm } from '../../orm';
|
||||
import { listSnapshots, PREFIX, pruneSnapshots, stamp } from '../../pre-migrate-snapshot';
|
||||
import { readPostgresBaseline, type PostgresBaseline } from './baseline';
|
||||
import { pgDump } from './pg-tools';
|
||||
import type { Connection } from '@mikro-orm/core';
|
||||
import type { Migrator } from '@mikro-orm/migrations';
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const logger = new Logger('DB');
|
||||
|
||||
/** A Postgres copy is a pg_dump custom-format archive. */
|
||||
const DUMP_EXTENSION = '.pgdump';
|
||||
|
||||
/** What a Postgres bootstrap reads, passed in so a test can supply its own. */
|
||||
export interface PostgresBootstrapDeps {
|
||||
baseline: () => PostgresBaseline;
|
||||
@@ -67,7 +76,8 @@ export async function bootstrapPostgresSchema(orm: AnyOrm, deps: PostgresBootstr
|
||||
await Promise.all(baseline.migrations.map((name) => storage.logMigration({ name }, trx)));
|
||||
});
|
||||
} else {
|
||||
refuseNewerDatabase(executed, deps.known);
|
||||
const thisRelease = migrationLabel([...deps.known].sort().at(-1) ?? '');
|
||||
refuseNewerDatabase(executed, deps.known, await deps.safetyNet.restoreHint(thisRelease));
|
||||
}
|
||||
|
||||
const pending = await migrator.getPending();
|
||||
@@ -78,32 +88,73 @@ export async function bootstrapPostgresSchema(orm: AnyOrm, deps: PostgresBootstr
|
||||
await migrator.up();
|
||||
}
|
||||
|
||||
/** Dumps a killed boot left half-written: never a copy, only disk taken. */
|
||||
function removeOrphanedPartials(dir: string): void {
|
||||
for (const file of fs.readdirSync(dir)) {
|
||||
if (file.startsWith(PREFIX) && file.endsWith(`${DUMP_EXTENSION}.partial`)) {
|
||||
fs.rmSync(path.join(dir, file), { force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The Postgres safety net before pending migrations, as the SQLite file's
|
||||
* (`db/pre-migrate-snapshot.ts`): a `pg_dump` of the database to
|
||||
* `<data>/pre-migrate-<schema>-<time>.pgdump`, the newest
|
||||
* `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` kept. A copy that cannot be written
|
||||
* (pg_dump missing, the data dir full) refuses the boot before anything is
|
||||
* migrated, unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. Off under
|
||||
* NODE_ENV=test unless a suite asks for it.
|
||||
*/
|
||||
export function postgresSafetyNet(env: () => AppEnv = readEnv): MigrationSafetyNet {
|
||||
export function postgresSafetyNet(
|
||||
url: string,
|
||||
env: () => AppEnv = readEnv,
|
||||
now: () => Date = () => new Date(),
|
||||
dataDir: () => string = () => resolveDataPaths(env()).dataDir,
|
||||
): MigrationSafetyNet {
|
||||
return {
|
||||
async beforeMigrate() {
|
||||
async beforeMigrate(from) {
|
||||
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.',
|
||||
);
|
||||
const target = path.join(dataDir(), `${PREFIX}${from ?? 'unversioned'}-${stamp(now())}${DUMP_EXTENSION}`);
|
||||
try {
|
||||
fs.mkdirSync(dataDir(), { recursive: true });
|
||||
removeOrphanedPartials(dataDir());
|
||||
await pgDump(url, target, db.pgBinDir);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`${REFUSAL} could not write a copy of the database to ${target} before migrating it ` +
|
||||
`(${err instanceof Error ? err.message : String(err)}). Nothing was migrated. Fix that, ` +
|
||||
'or set TREK_DB_PRE_MIGRATE_SNAPSHOT=false to migrate without a copy.',
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
logger.log(`Copy of the database before migrating: ${target}`);
|
||||
pruneSnapshots(dataDir(), db.preMigrateSnapshotKeep, DUMP_EXTENSION);
|
||||
},
|
||||
|
||||
async restoreHint(thisRelease) {
|
||||
const snapshots = listSnapshots(dataDir(), DUMP_EXTENSION);
|
||||
const match = snapshots.find((snapshot) => path.basename(snapshot).startsWith(`${PREFIX}${thisRelease}-`));
|
||||
if (match) {
|
||||
return (
|
||||
`The copy taken right before the newer TREK migrated it is ${match}: stop TREK, empty the database ` +
|
||||
'(drop and recreate it), and restore it with pg_restore --no-owner --no-privileges --single-transaction.'
|
||||
);
|
||||
}
|
||||
if (snapshots.length > 0) {
|
||||
return `Copies taken before earlier migrations are in ${dataDir()} (${PREFIX}*${DUMP_EXTENSION}), none of them from this release.`;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
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() };
|
||||
export function defaultPostgresBootstrapDeps(url: string): PostgresBootstrapDeps {
|
||||
return { baseline: readPostgresBaseline, known: knownMigrationNames(), safetyNet: postgresSafetyNet(url) };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user