@pgxsinkit/pgwasm-pg-dump 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wasm.d.ts","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAUA,wBAAgB,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,CAuBnE"}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@pgxsinkit/pgwasm-pg-dump",
3
+ "version": "0.5.0",
4
+ "license": "PostgreSQL",
5
+ "files": [
6
+ "artefacts",
7
+ "dist",
8
+ "src",
9
+ "README.md",
10
+ "LICENSE",
11
+ "NOTICE"
12
+ ],
13
+ "type": "module",
14
+ "main": "./dist/index.js",
15
+ "browser": {
16
+ "crypto": false,
17
+ "fs": false,
18
+ "module": false,
19
+ "node:crypto": false,
20
+ "node:fs": false,
21
+ "node:module": false,
22
+ "node:path": false,
23
+ "node:url": false,
24
+ "path": false,
25
+ "url": false,
26
+ "ws": false
27
+ },
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "scripts": {
39
+ "build": "bun --cwd ../.. run build:public-packages"
40
+ },
41
+ "peerDependencies": {
42
+ "@pgxsinkit/pgwasm": "0.5.0"
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/pgxsinkit/pgxsinkit.git"
47
+ }
48
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `pg_dump`'s artefacts, pinned by release and checksum (ADR-0062 decision 9, ADR-0064).
3
+ *
4
+ * Written by `bun run pgwasm:pin <tag>`, from the same pgxsinkit/pgwasm-postgres release as the C build's
5
+ * (pg_dump refuses a server newer than itself, so it always ships with its server); never edit it by hand.
6
+ * They are not in git: `scripts/pgwasm-artefacts.ts` (the root `postinstall`) downloads each asset into
7
+ * `packages/pgwasm-pg-dump/artefacts/` and checks it against its bytes and sha256 below. The published
8
+ * package carries the files.
9
+ */
10
+
11
+ /** The release the files are assets of. */
12
+ export const ARTEFACT_RELEASE = {
13
+ repository: "pgxsinkit/pgwasm-postgres",
14
+ tag: "18.6.2",
15
+ name: "pgwasm-postgres 18.6.2",
16
+ commit: "bf7938ad6acd51e1f68a9cb14fee9fea879a3b48",
17
+ upstream: { tag: "REL_18_6", commit: "724edf9bde9d356724ad384a2e196edc3c9f80f7" },
18
+ dataFormat: 1,
19
+ builderImage:
20
+ "ghcr.io/pgxsinkit/pgwasm-builder@sha256:0c4d5255c5f1824216d1eb347cc231a6f881574c3d5b8172796a8cbe5f9f63c8",
21
+ manifestSha256: "571b72a31003f89510f1bcbb37b5f70c142a5271cfdf24b7229423f9975d621d",
22
+ } as const;
23
+
24
+ /** Every pinned file, by its name in `artefacts/` (the release asset of the same name). */
25
+ export const ARTEFACT_FILES = {
26
+ "pg_dump.js": { bytes: 112499, sha256: "e53c8f6e0388e793ffc8c7ec629c1a6c05ff49904c023a8ff1d1ef36cd3a2619" },
27
+ "pg_dump.wasm": { bytes: 655066, sha256: "40e669ee2a218a73f9ca0138e56ce3180fcb0398134d98f53fae253c03174ce8" },
28
+ } as const;
29
+
30
+ export type ArtefactName = keyof typeof ARTEFACT_FILES;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * pg_dump's artefacts, referenced relative to this module so bundlers copy and fingerprint them.
3
+ *
4
+ * This is the ONLY module that names `../artefacts/`: Bun.build rewrites neither a relative external
5
+ * import nor `new URL("…", import.meta.url)` when it bundles a module into a shallower output, and this
6
+ * file is bundled into `dist/index.js`, one level below the package root like itself
7
+ * (tests/unit/pgwasm-artefacts.test.ts enforces the rule). The `new URL` stays a literal so bundlers can
8
+ * see it.
9
+ */
10
+
11
+ import createPgDumpModule from "../artefacts/pg_dump.js";
12
+
13
+ /** The pg_dump WebAssembly module. */
14
+ export const pgDumpWasm = new URL("../artefacts/pg_dump.wasm", import.meta.url);
15
+
16
+ export { createPgDumpModule };
@@ -0,0 +1,43 @@
1
+ // Began as a copy of `@electric-sql/pglite-tools` (taken under PGlite's PostgreSQL License option,
2
+ // © ElectricSQL — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal.
3
+
4
+ /**
5
+ * The parts of pg_dump's Emscripten module this package uses, typed here rather than through
6
+ * `@types/emscripten` (a global-ambient package). Only what is called is declared.
7
+ */
8
+
9
+ export interface PgDumpFS {
10
+ analyzePath(path: string): { exists: boolean };
11
+ mkdirTree(path: string): void;
12
+ writeFile(path: string, data: Uint8Array | string): void;
13
+ chmod(path: string, mode: number): void;
14
+ readFile(path: string, options?: { encoding: "binary" }): Uint8Array;
15
+ }
16
+
17
+ /** pg_dump's module (`pg_dump.js`). */
18
+ export interface PgDumpModule {
19
+ readonly FS: PgDumpFS;
20
+ readonly ENV: Record<string, string>;
21
+ readonly HEAPU8: Uint8Array;
22
+ addFunction(fn: (pointer: number, length: number) => number, signature: string): number;
23
+ /** Run pg_dump's `main`; returns its exit status. */
24
+ callMain(args: string[]): number;
25
+ /** Route libpq's socket reads and writes to two functions from `addFunction` (pglitec.c). */
26
+ _pgl_set_rw_cbs(readCallback: number, writeCallback: number): void;
27
+ }
28
+
29
+ /** What the module factory accepts; the members this package sets. */
30
+ export interface PgDumpModuleOverrides {
31
+ readonly thisProgram: string;
32
+ readonly noExitRuntime: boolean;
33
+ readonly stdin: () => number | null;
34
+ readonly print: (text: string) => void;
35
+ readonly printErr: (text: string) => void;
36
+ readonly instantiateWasm: (
37
+ imports: Parameters<typeof WebAssembly.instantiate>[1],
38
+ successCallback: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void,
39
+ ) => Record<string, never>;
40
+ readonly preRun: ((module: PgDumpModule) => void)[];
41
+ }
42
+
43
+ export type PgDumpModuleFactory = (overrides: PgDumpModuleOverrides) => Promise<PgDumpModule>;
package/src/errors.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { PgwasmError, UnsupportedFeatureError } from "@pgxsinkit/pgwasm";
2
+
3
+ /**
4
+ * The database's Postgres build cannot run pg_dump: its wire does not deliver a reply inside the call
5
+ * that sends the message (`capabilities.synchronousExchange` is false). pg_dump's WebAssembly calls its
6
+ * socket callbacks synchronously and needs each reply before the callback returns. Nothing was loaded
7
+ * or run.
8
+ */
9
+ export class PgDumpUnsupportedBuildError extends UnsupportedFeatureError {
10
+ override name = "PgDumpUnsupportedBuildError";
11
+ /** The build's name. */
12
+ readonly build: string;
13
+
14
+ constructor(build: string) {
15
+ super(
16
+ `pg_dump needs a Postgres build whose wire replies synchronously (capabilities.synchronousExchange); the ` +
17
+ `"${build}" build does not.`,
18
+ );
19
+ this.build = build;
20
+ }
21
+ }
22
+
23
+ /** pg_dump exited with a failure, or crashed (`exitCode` null). */
24
+ export class PgDumpError extends PgwasmError {
25
+ override name = "PgDumpError";
26
+ /** pg_dump's exit status; `null` when it crashed instead of exiting. */
27
+ readonly exitCode: number | null;
28
+ /** Everything pg_dump wrote to standard error. */
29
+ readonly stderr: string;
30
+
31
+ constructor(message: string, exitCode: number | null, stderr: string, options?: ErrorOptions) {
32
+ super(message, options);
33
+ this.exitCode = exitCode;
34
+ this.stderr = stderr;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * The database session was not in a state to dump from, or could not be put back as it was after the
40
+ * dump. pg_dump runs on the database's own session: before it, the session must be outside any
41
+ * transaction block (pg_dump opens and ends its own); after it, pg_dump's transaction is ended and every
42
+ * session setting it changed is restored. `unrestored` names the settings that still differ.
43
+ */
44
+ export class PgDumpSessionError extends PgwasmError {
45
+ override name = "PgDumpSessionError";
46
+ readonly unrestored: readonly string[];
47
+
48
+ constructor(message: string, unrestored: readonly string[] = [], options?: ErrorOptions) {
49
+ super(message, options);
50
+ this.unrestored = unrestored;
51
+ }
52
+ }
package/src/framing.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Frontend messages out of libpq's `send()` calls.
3
+ *
4
+ * On a Unix-socket connection, which pg_dump's is, libpq sends its output in whole 8 KiB blocks as a
5
+ * message is added and keeps the rest for its next send (`pqPutMsgEnd`), so a longer message reaches
6
+ * pg_dump's write callback in pieces; one call can also carry several messages. The session must only
7
+ * be handed whole messages: a piece makes the backend read past the end of its input. The first message of a connection is a startup packet (a length, then its body);
8
+ * every later one is a type byte, then a length that counts itself.
9
+ */
10
+ export class FrontendFramer {
11
+ #pending: Uint8Array = new Uint8Array(0);
12
+ #startup = true;
13
+
14
+ /** Take a copy of `bytes`; return every message that is now complete, in order. */
15
+ push(bytes: Uint8Array): Uint8Array[] {
16
+ const joined = new Uint8Array(this.#pending.byteLength + bytes.byteLength);
17
+ joined.set(this.#pending, 0);
18
+ joined.set(bytes, this.#pending.byteLength);
19
+ const messages: Uint8Array[] = [];
20
+ let offset = 0;
21
+ for (;;) {
22
+ const header = this.#startup ? 4 : 5;
23
+ if (joined.byteLength - offset < header) break;
24
+ const lengthAt = offset + header - 4;
25
+ const length = new DataView(joined.buffer, joined.byteOffset + lengthAt, 4).getUint32(0, false);
26
+ if (length < 4) throw new Error(`pg_dump sent a frontend message with an invalid length (${length})`);
27
+ const end = lengthAt + length;
28
+ if (joined.byteLength < end) break;
29
+ messages.push(joined.slice(offset, end));
30
+ offset = end;
31
+ this.#startup = false;
32
+ }
33
+ this.#pending = joined.slice(offset);
34
+ return messages;
35
+ }
36
+
37
+ /** Bytes of an incomplete message, still waiting for the rest. */
38
+ get pendingBytes(): number {
39
+ return this.#pending.byteLength;
40
+ }
41
+ }
42
+
43
+ /** Backend bytes waiting for libpq's `recv()`, read in whatever sizes it asks for. */
44
+ export class ByteQueue {
45
+ readonly #chunks: Uint8Array[] = [];
46
+ #head = 0;
47
+
48
+ /** Keep a copy of `bytes`. */
49
+ push(bytes: Uint8Array): void {
50
+ if (bytes.byteLength > 0) this.#chunks.push(bytes.slice());
51
+ }
52
+
53
+ /** Move up to `target.byteLength` bytes into `target`; returns how many were moved. */
54
+ read(target: Uint8Array): number {
55
+ let written = 0;
56
+ while (written < target.byteLength && this.#chunks.length > 0) {
57
+ const chunk = this.#chunks[0];
58
+ if (chunk === undefined) break;
59
+ const take = Math.min(chunk.byteLength - this.#head, target.byteLength - written);
60
+ target.set(chunk.subarray(this.#head, this.#head + take), written);
61
+ written += take;
62
+ this.#head += take;
63
+ if (this.#head === chunk.byteLength) {
64
+ this.#chunks.shift();
65
+ this.#head = 0;
66
+ }
67
+ }
68
+ return written;
69
+ }
70
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { PgDumpError, PgDumpSessionError, PgDumpUnsupportedBuildError } from "./errors";
2
+ export { pgDump, type PgDumpOptions } from "./pg-dump";
package/src/output.ts ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * pg_dump's output file, as the `File` pgDump returns.
3
+ *
4
+ * A plain-format dump is an SQL script. pg_dump 18.6 brackets it in psql's `\restrict <key>` /
5
+ * `\unrestrict <key>` meta-commands, which only psql understands; the script is meant for `exec()`, so
6
+ * those two lines are removed. They are found by pg_dump's random key, so a row whose text happens to
7
+ * hold a line starting `\restrict` is left alone. The custom and tar formats and a compressed plain dump
8
+ * are returned byte for byte.
9
+ */
10
+
11
+ const encoder = new TextEncoder();
12
+
13
+ function startsWith(bytes: Uint8Array, prefix: ArrayLike<number>, at = 0): boolean {
14
+ if (at + prefix.length > bytes.byteLength) return false;
15
+ for (let index = 0; index < prefix.length; index++) {
16
+ if (bytes[at + index] !== prefix[index]) return false;
17
+ }
18
+ return true;
19
+ }
20
+
21
+ /** A format other than an uncompressed plain script: custom (`PGDMP`), tar (`ustar`), or gzip. */
22
+ function isArchive(bytes: Uint8Array): boolean {
23
+ return (
24
+ startsWith(bytes, encoder.encode("PGDMP")) ||
25
+ startsWith(bytes, encoder.encode("ustar"), 257) ||
26
+ startsWith(bytes, [0x1f, 0x8b])
27
+ );
28
+ }
29
+
30
+ function indexOfBytes(haystack: Uint8Array, needle: Uint8Array, from = 0): number {
31
+ const first = needle[0];
32
+ if (first === undefined) return -1;
33
+ for (let at = haystack.indexOf(first, from); at !== -1; at = haystack.indexOf(first, at + 1)) {
34
+ if (at + needle.byteLength > haystack.byteLength) return -1;
35
+ if (startsWith(haystack, needle, at)) return at;
36
+ }
37
+ return -1;
38
+ }
39
+
40
+ function lastIndexOfBytes(haystack: Uint8Array, needle: Uint8Array): number {
41
+ const first = needle[0];
42
+ if (first === undefined) return -1;
43
+ for (let at = haystack.lastIndexOf(first); at !== -1; at = at === 0 ? -1 : haystack.lastIndexOf(first, at - 1)) {
44
+ if (startsWith(haystack, needle, at)) return at;
45
+ }
46
+ return -1;
47
+ }
48
+
49
+ /** The end of the line starting at `start`, past its newline. */
50
+ function lineEnd(bytes: Uint8Array, start: number): number {
51
+ const newline = bytes.indexOf(0x0a, start);
52
+ return newline === -1 ? bytes.byteLength : newline + 1;
53
+ }
54
+
55
+ /** Remove the `\restrict <key>` line and its matching `\unrestrict <key>` line. */
56
+ export function withoutRestrictLines(script: Uint8Array): Uint8Array {
57
+ const restrict = indexOfBytes(script, encoder.encode("\n\\restrict "));
58
+ if (restrict === -1) return script;
59
+ const lineStart = restrict + 1;
60
+ const end = lineEnd(script, lineStart);
61
+ const key = new TextDecoder().decode(script.subarray(lineStart + "\\restrict ".length, end)).trim();
62
+ if (!/^[A-Za-z0-9]+$/.test(key)) return script;
63
+ const unrestrictLine = encoder.encode(`\n\\unrestrict ${key}\n`);
64
+ const unrestrict = lastIndexOfBytes(script, unrestrictLine);
65
+ const parts = [script.subarray(0, lineStart)];
66
+ if (unrestrict > end) {
67
+ parts.push(script.subarray(end, unrestrict + 1), script.subarray(unrestrict + unrestrictLine.byteLength));
68
+ } else {
69
+ parts.push(script.subarray(end));
70
+ }
71
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.byteLength, 0));
72
+ let offset = 0;
73
+ for (const part of parts) {
74
+ out.set(part, offset);
75
+ offset += part.byteLength;
76
+ }
77
+ return out;
78
+ }
79
+
80
+ /** The dump as a `File`: a plain script without its psql-only lines, or an archive as it is. */
81
+ export function dumpFile(output: Uint8Array, fileName: string): File {
82
+ if (isArchive(output)) {
83
+ return new File([output.slice()], fileName, { type: "application/octet-stream" });
84
+ }
85
+ return new File([withoutRestrictLines(output).slice()], fileName, { type: "text/plain" });
86
+ }
package/src/pg-dump.ts ADDED
@@ -0,0 +1,260 @@
1
+ // Began as a copy of `@electric-sql/pglite-tools` (taken under PGlite's PostgreSQL License option,
2
+ // © ElectricSQL — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal.
3
+
4
+ import type { Pgwasm } from "@pgxsinkit/pgwasm";
5
+ import { PgwasmClosedError, PgwasmFailedError } from "@pgxsinkit/pgwasm";
6
+ import { protocol, type PgwasmProtocol } from "@pgxsinkit/pgwasm/protocol";
7
+
8
+ import { createPgDumpModule, pgDumpWasm } from "./artefacts";
9
+ import { PgDumpError, PgDumpSessionError, PgDumpUnsupportedBuildError } from "./errors";
10
+ import { ByteQueue, FrontendFramer } from "./framing";
11
+ import { dumpFile } from "./output";
12
+ import { readSession, restoreSession, transactionStatus, type SessionState } from "./session";
13
+ import { compileModule } from "./wasm";
14
+
15
+ export interface PgDumpOptions {
16
+ /** The database to dump. Its Postgres build must reply synchronously (`capabilities.synchronousExchange`). */
17
+ readonly pg: Pgwasm;
18
+ /**
19
+ * More pg_dump arguments (https://www.postgresql.org/docs/current/app-pgdump.html), placed before the
20
+ * fixed ones, which win: `-U postgres --inserts -j 1 -f <output>`.
21
+ */
22
+ readonly args?: readonly string[];
23
+ /** The returned file's name. Defaults to `dump.sql`. */
24
+ readonly fileName?: string;
25
+ }
26
+
27
+ /** Where pg_dump's own filesystem has it; `argv[0]`, which pg_dump resolves to find itself. */
28
+ const PG_DUMP_PATH = "/bin/pg_dump";
29
+ /** The output file, in pg_dump's own filesystem, read back once it exits. */
30
+ const OUTPUT_PATH = "/tmp/out.sql";
31
+
32
+ const FIXED_ARGS: readonly string[] = [
33
+ // The user named in the startup packet; the session already runs as the database's own role.
34
+ "-U",
35
+ "postgres",
36
+ // INSERT statements rather than COPY … FROM stdin, so `exec()` can run the dump back.
37
+ "--inserts",
38
+ // One job: there is one session and no second connection.
39
+ "-j",
40
+ "1",
41
+ // A file in pg_dump's filesystem, which pgDump returns.
42
+ "-f",
43
+ OUTPUT_PATH,
44
+ ];
45
+
46
+ interface PgDumpRun {
47
+ /** pg_dump's exit status; null when it crashed. */
48
+ readonly exitCode: number | null;
49
+ readonly crash: unknown;
50
+ readonly stderr: string;
51
+ /** The output file, when pg_dump exited 0 and wrote one. */
52
+ readonly output: Uint8Array | undefined;
53
+ /** The first failure of the database's wire, which pg_dump only saw as a closed connection. */
54
+ readonly wireFailure: { readonly error: unknown } | undefined;
55
+ }
56
+
57
+ /**
58
+ * Run pg_dump once, in a fresh module over the compiled WebAssembly, its socket bridged to the database's
59
+ * wire. pg_dump's WebAssembly calls the write and read callbacks synchronously: a whole frontend message
60
+ * goes out on the build's synchronous exchange, whose reply is queued before the write callback returns,
61
+ * for the read callback to hand back.
62
+ */
63
+ async function runPgDump(wire: PgwasmProtocol, wasm: WebAssembly.Module, args: readonly string[]): Promise<PgDumpRun> {
64
+ let stderr = "";
65
+ let rejectInstantiation: (error: unknown) => void = () => undefined;
66
+ const instantiationFailed = new Promise<never>((_, reject) => {
67
+ rejectInstantiation = reject;
68
+ });
69
+ const module = await Promise.race([
70
+ createPgDumpModule({
71
+ thisProgram: PG_DUMP_PATH,
72
+ noExitRuntime: false,
73
+ // A stdin that is always at EOF, so a browser never prompts.
74
+ stdin: () => null,
75
+ print: () => undefined,
76
+ printErr: (text) => {
77
+ stderr += `${text}\n`;
78
+ },
79
+ instantiateWasm: (imports, successCallback) => {
80
+ // A throw from `successCallback` (the module's own start-up) must settle the race too, or pgDump
81
+ // would wait forever while holding the session.
82
+ WebAssembly.instantiate(wasm, imports)
83
+ .then((instance) => successCallback(instance, wasm))
84
+ .catch(rejectInstantiation);
85
+ return {};
86
+ },
87
+ preRun: [
88
+ (mod) => {
89
+ mod.ENV["HOME"] = "/home/postgres";
90
+ mod.ENV["USER"] = "postgres";
91
+ mod.ENV["LOGNAME"] = "postgres";
92
+ // pg_dump looks for its own executable when it starts, and warns when it finds none.
93
+ mod.FS.mkdirTree(PG_DUMP_PATH.slice(0, PG_DUMP_PATH.lastIndexOf("/")));
94
+ mod.FS.writeFile(PG_DUMP_PATH, "");
95
+ mod.FS.chmod(PG_DUMP_PATH, 0o555);
96
+ },
97
+ ],
98
+ }),
99
+ instantiationFailed,
100
+ ]);
101
+
102
+ const framer = new FrontendFramer();
103
+ const replies = new ByteQueue();
104
+ const exchanges: Promise<void>[] = [];
105
+ let wireFailure: { error: unknown } | undefined;
106
+ const write = module.addFunction((pointer, length) => {
107
+ for (const message of framer.push(module.HEAPU8.subarray(pointer, pointer + length))) {
108
+ // pg_dump only reads: nothing to persist. The build's synchronous exchange has queued the whole
109
+ // reply before this returns; a rejection is kept for after pg_dump exits.
110
+ const exchange = wire.execProtocolRawStream(message, {
111
+ persist: false,
112
+ onRawData: (chunk) => replies.push(chunk),
113
+ });
114
+ exchanges.push(
115
+ exchange.catch((error: unknown) => {
116
+ wireFailure ??= { error };
117
+ }),
118
+ );
119
+ }
120
+ return length;
121
+ }, "iii");
122
+ const read = module.addFunction(
123
+ (pointer, maxLength) => replies.read(module.HEAPU8.subarray(pointer, pointer + maxLength)),
124
+ "iii",
125
+ );
126
+ module._pgl_set_rw_cbs(read, write);
127
+
128
+ let exitCode: number | null;
129
+ let crash: unknown;
130
+ try {
131
+ exitCode = module.callMain([...args, ...FIXED_ARGS]);
132
+ } catch (error) {
133
+ exitCode = null;
134
+ crash = error;
135
+ }
136
+ await Promise.all(exchanges);
137
+
138
+ let output: Uint8Array | undefined;
139
+ if (exitCode === 0 && module.FS.analyzePath(OUTPUT_PATH).exists) {
140
+ try {
141
+ output = module.FS.readFile(OUTPUT_PATH);
142
+ } catch (error) {
143
+ crash = error;
144
+ }
145
+ }
146
+ return { exitCode, crash, stderr, output, wireFailure };
147
+ }
148
+
149
+ function failureOf(run: PgDumpRun): Error | undefined {
150
+ if (run.wireFailure !== undefined) {
151
+ const { error } = run.wireFailure;
152
+ return error instanceof Error ? error : new Error(String(error));
153
+ }
154
+ if (run.exitCode === null) {
155
+ return new PgDumpError(
156
+ `pg_dump crashed: ${run.crash instanceof Error ? run.crash.message : String(run.crash)}`,
157
+ null,
158
+ run.stderr,
159
+ { cause: run.crash },
160
+ );
161
+ }
162
+ if (run.exitCode !== 0) {
163
+ return new PgDumpError(
164
+ `pg_dump failed with exit code ${run.exitCode}${run.stderr === "" ? "" : `: ${run.stderr.trim()}`}`,
165
+ run.exitCode,
166
+ run.stderr,
167
+ );
168
+ }
169
+ if (run.output === undefined) {
170
+ return new PgDumpError(
171
+ "pg_dump exited without writing a single output file (the directory format writes several, which " +
172
+ "pgDump does not return)",
173
+ 0,
174
+ run.stderr,
175
+ run.crash === undefined ? undefined : { cause: run.crash },
176
+ );
177
+ }
178
+ return undefined;
179
+ }
180
+
181
+ const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
182
+
183
+ /**
184
+ * What to throw when the session could not be restored after pg_dump. When pg_dump had failed as well,
185
+ * its failure is not dropped: it is the cause of the error thrown.
186
+ */
187
+ function restoreError(restoreFailure: unknown, dumpFailure: { readonly error: unknown } | undefined): unknown {
188
+ // A failed or closed database fails every exchange; that is the error to report.
189
+ if (restoreFailure instanceof PgwasmFailedError || restoreFailure instanceof PgwasmClosedError) {
190
+ return restoreFailure;
191
+ }
192
+ const sessionError = restoreFailure instanceof PgDumpSessionError ? restoreFailure : undefined;
193
+ if (dumpFailure === undefined) {
194
+ return (
195
+ sessionError ??
196
+ new PgDumpSessionError("The database's session could not be restored after pg_dump.", [], {
197
+ cause: restoreFailure,
198
+ })
199
+ );
200
+ }
201
+ const message =
202
+ sessionError?.message ??
203
+ `The database's session could not be restored after pg_dump (${messageOf(restoreFailure)}).`;
204
+ return new PgDumpSessionError(
205
+ `${message} pg_dump itself had failed: ${messageOf(dumpFailure.error)}`,
206
+ sessionError?.unrestored ?? [],
207
+ { cause: dumpFailure.error },
208
+ );
209
+ }
210
+
211
+ /**
212
+ * Dump a database with pg_dump, as a `File`: by default a plain SQL script of INSERT statements, which
213
+ * `exec()` runs back into an empty database.
214
+ *
215
+ * pg_dump runs on the database's own session, which it holds for the whole dump: no query, transaction
216
+ * or other dump of this database runs until it is done, and none can be running inside a transaction
217
+ * block when it starts ({@link PgDumpSessionError}). Afterwards the session is as it was: pg_dump's
218
+ * transaction ended, its prepared statements gone, every setting it changed restored. It must not be
219
+ * called inside a `pg.transaction()` callback: it would wait forever for the session that transaction
220
+ * holds.
221
+ *
222
+ * @throws {PgDumpUnsupportedBuildError} the database's build cannot run pg_dump (checked first).
223
+ * @throws {PgDumpError} pg_dump failed; it carries the exit code and standard error.
224
+ * @throws {PgDumpSessionError} the session was inside a transaction block, or could not be restored
225
+ * (then, when pg_dump had failed too, its failure is the cause).
226
+ */
227
+ export async function pgDump({ pg, args = [], fileName = "dump.sql" }: PgDumpOptions): Promise<File> {
228
+ const wire = protocol(pg);
229
+ if (!wire.capabilities.synchronousExchange) throw new PgDumpUnsupportedBuildError(pg.build.name);
230
+ const wasm = compileModule(pgDumpWasm);
231
+
232
+ return await wire.runExclusiveSession(async () => {
233
+ if ((await transactionStatus(wire)) !== "I") {
234
+ throw new PgDumpSessionError(
235
+ "The database's session is inside a transaction block; pg_dump opens and ends its own transaction, " +
236
+ "so it runs only between transactions.",
237
+ );
238
+ }
239
+ const before: SessionState = await readSession(wire);
240
+
241
+ let outcome: { readonly run: PgDumpRun } | { readonly failure: unknown };
242
+ try {
243
+ outcome = { run: await runPgDump(wire, await wasm, args) };
244
+ } catch (failure) {
245
+ outcome = { failure };
246
+ }
247
+
248
+ try {
249
+ await restoreSession(wire, before);
250
+ } catch (restoreFailure) {
251
+ const dumpFailure = "failure" in outcome ? { error: outcome.failure } : failureOf(outcome.run);
252
+ throw restoreError(restoreFailure, dumpFailure instanceof Error ? { error: dumpFailure } : dumpFailure);
253
+ }
254
+
255
+ if ("failure" in outcome) throw outcome.failure;
256
+ const failure = failureOf(outcome.run);
257
+ if (failure !== undefined) throw failure;
258
+ return dumpFile(outcome.run.output ?? new Uint8Array(), fileName);
259
+ });
260
+ }