fix(backup): restore Postgres backups into PostgreSQL 14, 15 and 16

pg_restore 17 and later write SET transaction_timeout at the top of every script, which older servers refuse under ON_ERROR_STOP. The restore now leaves settings the target server does not know out of the script while it streams.
This commit is contained in:
Maurice
2026-11-23 14:56:55 +01:00
parent 626e19c534
commit bb2b4a1f5a
6 changed files with 192 additions and 8 deletions
+5 -4
View File
@@ -1,7 +1,7 @@
import { execFile, spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { Transform } from 'node:stream';
import { PassThrough, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { promisify } from 'node:util';
@@ -239,8 +239,8 @@ type Ending = { code: number | null; signal: NodeJS.Signals | null } | { error:
/**
* Runs `tool` and streams its stdout into `target` (which must exist; its mode
* is kept), stopping the tool with {@link PgOutputLimitError} once more than
* `maxBytes` have come out. The caller removes `target` on failure. A failure
* of the tool itself throws as `run` does.
* `maxBytes` have come out, through `filter` when one is given. The caller
* removes `target` on failure. A failure of the tool itself throws as `run` does.
*/
export async function runToFile(
tool: PgTool,
@@ -249,6 +249,7 @@ export async function runToFile(
env: Record<string, string>,
target: string,
maxBytes: number,
filter: Transform = new PassThrough(),
): Promise<void> {
const binary = locate(tool, binDir);
await refuseSystemRootCertOnOldClient(tool, binary, env);
@@ -271,7 +272,7 @@ export async function runToFile(
},
});
try {
await pipeline(child.stdout, limit, fs.createWriteStream(target, { flags: 'w' }));
await pipeline(child.stdout, limit, filter, fs.createWriteStream(target, { flags: 'w' }));
} catch (err) {
child.kill('SIGKILL');
await ended;
+13 -4
View File
@@ -3,6 +3,7 @@ import { CLEAR_SCHEMA_SQL, pluginSchemasSql } from './clear-schema';
import { pgConnectionEnv, PgOutputLimitError, refuseClientOlderThanServer, run, runToFile } from './pg-process';
import { isPluginSchemaName, PLUGIN_SCHEMA_PREFIX } from './plugin-schema';
import { refuseToolsWithoutRestrict } from './restore-safety';
import { withoutUnknownSettings } from './script-settings';
import { PRIVILEGED_ROLE_DESCRIPTION, PRIVILEGED_ROLE_SQL, serverMajor } from './server-checks';
import fs from 'node:fs';
@@ -144,18 +145,23 @@ async function scriptHoldsTrekSchema(script: string, schema: PgSchema): Promise<
}
}
/** pg_restore's script for the dump at `source`, written to `script` and held to `maxBytes`. */
/**
* pg_restore's script for the dump at `source`, written to `script` and held
* to `maxBytes`, without the settings a server of major `serverMajor` does
* not know.
*/
async function writeRestoreScript(
source: string,
script: string,
schemas: readonly string[],
binDir: string | undefined,
maxBytes: number,
limits: { maxBytes: number; serverMajor: number },
): Promise<void> {
const { maxBytes, serverMajor } = limits;
const only = schemas.map((name) => `--schema=${name}`);
const args = ['--no-owner', '--no-privileges', ...only, '--file=-', '--', source];
try {
await runToFile('pg_restore', binDir, args, {}, script, maxBytes);
await runToFile('pg_restore', binDir, args, {}, script, maxBytes, withoutUnknownSettings(serverMajor));
} catch (err) {
if (!(err instanceof PgOutputLimitError)) throw err;
throw new Error(
@@ -202,7 +208,10 @@ export async function pgRestore(
const pluginSchemas = await dumpPluginSchemas(source, path.join(workDir, 'toc.txt'), binDir);
fs.writeFileSync(clear, CLEAR_SCHEMA_SQL + pluginSchemasSql(pluginSchemas), { mode: 0o600 });
createPrivateFile(script);
await writeRestoreScript(source, script, [schema.name, ...pluginSchemas], binDir, maxScriptBytes);
await writeRestoreScript(source, script, [schema.name, ...pluginSchemas], binDir, {
maxBytes: maxScriptBytes,
serverMajor: major,
});
if (!(await scriptHoldsTrekSchema(script, schema))) {
throw new Error(`The backup holds no TREK tables in the schema "${schema.name}"; nothing was replaced.`);
}
@@ -0,0 +1,65 @@
import { Transform } from 'node:stream';
/**
* The settings a newer pg_restore writes at the start of every script, with
* the first server major that knows each. pg_restore 17 and later set
* `transaction_timeout` whatever server the script is for.
*/
const SETTING_SINCE: Readonly<Record<string, number>> = { transaction_timeout: 17 };
/** A line of the settings block before the script's first object: blank, a comment, a psql command or a setting. */
const PREAMBLE_LINE = /^(?:$|--|\\|SET |SELECT pg_catalog\.set_config\()/;
const SET_LINE = /^SET (\w+) = /;
/**
* Leaves out the `SET` lines of a restore script's settings block that a
* server of major `serverMajor` does not know, so psql under ON_ERROR_STOP does
* not refuse the whole script on its first lines. Only the lines before the
* first object are looked at; from there on every chunk passes as it comes,
* so a script's COPY data is never split into lines.
*/
export function withoutUnknownSettings(serverMajor: number): Transform {
const unknown = new Set(
Object.entries(SETTING_SINCE)
.filter(([, since]) => serverMajor < since)
.map(([name]) => name),
);
let inPreamble = unknown.size > 0;
let pending = Buffer.alloc(0);
const dropped = (line: string): boolean => unknown.has(SET_LINE.exec(line)?.[1] ?? '');
return new Transform({
transform(chunk: Buffer, _encoding, callback) {
if (!inPreamble) {
callback(null, chunk);
return;
}
pending = Buffer.concat([pending, chunk]);
const kept: Buffer[] = [];
let start = 0;
for (let end = pending.indexOf(0x0a, start); end >= 0; end = pending.indexOf(0x0a, start)) {
const line = pending.toString('utf8', start, end).replace(/\r$/, '');
if (!PREAMBLE_LINE.test(line)) {
inPreamble = false;
break;
}
if (!dropped(line)) kept.push(pending.subarray(start, end + 1));
start = end + 1;
}
const rest = pending.subarray(start);
if (inPreamble) {
pending = Buffer.from(rest);
} else {
kept.push(rest);
pending = Buffer.alloc(0);
}
callback(null, Buffer.concat(kept));
},
flush(callback) {
const last = pending.toString('utf8');
callback(null, inPreamble && dropped(last) ? Buffer.alloc(0) : pending);
},
});
}
@@ -378,6 +378,32 @@ describe('pg-tools', () => {
expect(readdirSync(out)).toEqual([]);
});
it.each([
{ id: 'PGTOOLS-021a', versionNum: '160004', kept: false },
{ id: 'PGTOOLS-021b', versionNum: '170002', kept: true },
])(
'$id: the script psql runs sets transaction_timeout only on a server that knows it',
async ({ versionNum, kept }) => {
const scriptCopy = path.join(bin, 'restore.sql');
installFakeTool(bin, 'pg_restore', {
snippets: [
writesFile(
'\\restrict k1\nSET lock_timeout = 0;\nSET transaction_timeout = 0;\n' +
'CREATE TABLE public.mikro_orm_migrations (\n);\n',
),
],
});
installFakeTool(bin, 'psql', {
snippets: [answersSchema('public', 'public', { versionNum }), copiesFileEndingWith('restore.sql', scriptCopy)],
});
await pgRestore(URL_WITH_SECRET, path.join(out, 'in.pgdump'), bin, LIMIT);
const script = readFileSync(scriptCopy, 'utf8');
expect(script).toContain('\nCREATE TABLE public.mikro_orm_migrations (\n');
expect(script).toContain('SET lock_timeout = 0;\n');
expect(script.includes('SET transaction_timeout = 0;')).toBe(kept);
},
);
it("PGTOOLS-020: a plugin's own table named mikro_orm_migrations never passes for TREK's history", async () => {
const forged =
'COPY trek_plugin_notes.mikro_orm_migrations (id, name) FROM stdin;\n1\tMigration29990101000000_forged\n\\.\n';
@@ -0,0 +1,81 @@
/**
* The settings a newer pg_restore writes at the start of a restore script
* (src/db/engine/postgres/script-settings.ts): a server that does not know one
* refuses the whole script under ON_ERROR_STOP, so the restore leaves it out
* for that server and nowhere else.
*/
import { withoutUnknownSettings } from '../../../../../src/db/engine/postgres/script-settings';
import { Readable } from 'node:stream';
import { describe, expect, it } from 'vitest';
/** The settings block pg_restore 18 writes, followed by the script's first objects and some COPY data. */
const SCRIPT = [
'--',
'-- PostgreSQL database dump',
'--',
'',
'\\restrict k1',
'',
'-- Dumped from database version 16.4',
'-- Dumped by pg_dump version 18.1',
'',
'SET statement_timeout = 0;',
'SET lock_timeout = 0;',
'SET idle_in_transaction_session_timeout = 0;',
'SET transaction_timeout = 0;',
"SET client_encoding = 'UTF8';",
'SET standard_conforming_strings = on;',
"SELECT pg_catalog.set_config('search_path', '', false);",
'SET row_security = off;',
'',
'CREATE TABLE public.mikro_orm_migrations (',
' id integer NOT NULL',
');',
'COPY public.notes (body) FROM stdin;',
'SET transaction_timeout = 0;',
'Grüße aus Köln',
'\\.',
'',
].join('\n');
/** What the filter makes of `text` for a server of major `major`, fed in chunks of `size` bytes. */
async function filtered(text: string, major: number, size: number): Promise<string> {
const bytes = Buffer.from(text, 'utf8');
const chunks: Buffer[] = [];
for (let at = 0; at < bytes.length; at += size) chunks.push(bytes.subarray(at, at + size));
const out: Buffer[] = [];
for await (const chunk of Readable.from(chunks).pipe(withoutUnknownSettings(major))) out.push(chunk as Buffer);
return Buffer.concat(out).toString('utf8');
}
describe('script-settings', () => {
it.each([14, 15, 16])(
'SCRIPTSET-001: a PostgreSQL %i server gets the script without SET transaction_timeout, and nothing else changes',
async (major) => {
const expected = SCRIPT.replace('SET transaction_timeout = 0;\n', '');
for (const size of [1, 3, 7, 64, 1 << 20]) {
expect(await filtered(SCRIPT, major, size), `chunks of ${size}`).toBe(expected);
}
},
);
it.each([17, 18])('SCRIPTSET-002: a PostgreSQL %i server gets the script as pg_restore wrote it', async (major) => {
expect(await filtered(SCRIPT, major, 5)).toBe(SCRIPT);
});
it('SCRIPTSET-003: only the settings block is read, so a COPY row that looks like the setting stays', async () => {
const out = await filtered(SCRIPT, 16, 1 << 20);
expect(out.match(/^SET transaction_timeout = 0;$/gm)).toHaveLength(1);
expect(out.indexOf('SET transaction_timeout')).toBeGreaterThan(out.indexOf('COPY public.notes'));
});
it('SCRIPTSET-004: a script that ends inside its settings block keeps its last line unless it is the setting', async () => {
expect(await filtered('SET lock_timeout = 0;\nSET transaction_timeout = 0;', 16, 4)).toBe(
'SET lock_timeout = 0;\n',
);
expect(await filtered('SET lock_timeout = 0;\nSET row_security = off;', 16, 4)).toBe(
'SET lock_timeout = 0;\nSET row_security = off;',
);
});
});
+2
View File
@@ -111,6 +111,8 @@ The copy cannot be loaded over the migrated schema: it recreates TREK's tables,
pg_restore --no-owner --no-privileges --schema=public --file=restore.sql data/pre-migrate-<schema>-<time>.pgdump
```
`pg_restore` 17 and later write `SET transaction_timeout = 0;` near the top of the script, a setting PostgreSQL 14, 15 and 16 do not know. On such a server, delete that line from `restore.sql` before step 4; TREK's own restore leaves it out the same way.
3. Save this block as `clear-schema.sql`. It drops every table, view, sequence, function, collation and type in the current schema, which is what TREK's restore runs before it loads a backup:
```sql