@otwdesign/db-core 1.2.0 → 1.3.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.
Files changed (49) hide show
  1. package/dist/backup/api.d.ts +55 -0
  2. package/dist/backup/api.js +441 -0
  3. package/dist/backup/api.js.map +1 -0
  4. package/dist/backup/catalog.d.ts +47 -0
  5. package/dist/backup/catalog.js +348 -0
  6. package/dist/backup/catalog.js.map +1 -0
  7. package/dist/backup/dump.d.ts +48 -0
  8. package/dist/backup/dump.js +860 -0
  9. package/dist/backup/dump.js.map +1 -0
  10. package/dist/backup/format.d.ts +38 -0
  11. package/dist/backup/format.js +70 -0
  12. package/dist/backup/format.js.map +1 -0
  13. package/dist/backup/pg-tools.d.ts +29 -0
  14. package/dist/backup/pg-tools.js +154 -0
  15. package/dist/backup/pg-tools.js.map +1 -0
  16. package/dist/backup/restore.d.ts +41 -0
  17. package/dist/backup/restore.js +196 -0
  18. package/dist/backup/restore.js.map +1 -0
  19. package/dist/backup/split.d.ts +18 -0
  20. package/dist/backup/split.js +316 -0
  21. package/dist/backup/split.js.map +1 -0
  22. package/dist/backup/staging.d.ts +29 -0
  23. package/dist/backup/staging.js +96 -0
  24. package/dist/backup/staging.js.map +1 -0
  25. package/dist/browser.d.ts +5 -0
  26. package/dist/drivers/pglite.js +57 -0
  27. package/dist/drivers/pglite.js.map +1 -1
  28. package/dist/drivers/postgres.js +45 -0
  29. package/dist/drivers/postgres.js.map +1 -1
  30. package/dist/handler.d.ts +5 -0
  31. package/dist/handler.js +48 -1
  32. package/dist/handler.js.map +1 -1
  33. package/dist/index.d.ts +5 -0
  34. package/dist/types.d.ts +30 -1
  35. package/package.json +2 -2
  36. package/src/backup/api.ts +543 -0
  37. package/src/backup/catalog.ts +381 -0
  38. package/src/backup/dump.ts +1102 -0
  39. package/src/backup/format.ts +114 -0
  40. package/src/backup/pg-tools.ts +185 -0
  41. package/src/backup/restore.ts +270 -0
  42. package/src/backup/split.ts +300 -0
  43. package/src/backup/staging.ts +143 -0
  44. package/src/browser.ts +5 -0
  45. package/src/drivers/pglite.ts +55 -0
  46. package/src/drivers/postgres.ts +46 -0
  47. package/src/handler.ts +56 -1
  48. package/src/index.ts +6 -0
  49. package/src/types.ts +29 -1
@@ -0,0 +1,860 @@
1
+ import { DbAdminError } from "../errors.js";
2
+ import { literal, quote } from "../drivers/postgres-catalog.js";
3
+ import * as Q from "./catalog.js";
4
+ import { BACKUP_VERSION, headerLine, trailerLine } from "./format.js";
5
+ /*
6
+ * A PostgreSQL backup as SQL, written from the catalog in one read-only snapshot. In order:
7
+ *
8
+ * 1. each schema emptied (or made, with its owner and privileges, when the server lacks it);
9
+ * 2. the extensions: those its objects need, then the database's others where the server has them;
10
+ * 3. types, functions, sequences, tables and views, each after what it depends on;
11
+ * 4. the rows, then where each sequence had got to;
12
+ * 5. keys, indexes, foreign keys, triggers, rules, row-level security and policies, statistics,
13
+ * materialized views refreshed;
14
+ * 6. comments, owners and privileges.
15
+ *
16
+ * What it can't write (aggregates, operators, C functions…) is listed in the header, never left
17
+ * out unsaid. Roles aren't in a backup: an owner, grant or policy that names a role the restoring
18
+ * server lacks is skipped, with a notice.
19
+ */
20
+ /** PostgreSQL 14: older servers lack catalog columns the backup reads. */
21
+ export const MIN_SERVER_VERSION = 140000;
22
+ /** Rows an INSERT carries at most, and about how many bytes. */
23
+ const ROWS_PER_INSERT = 500;
24
+ const BYTES_PER_INSERT = 1_000_000;
25
+ const FETCH = 1_000;
26
+ /** Settings for the snapshot, then who and where it is. Refuses servers older than 14. */
27
+ export async function prepare(session) {
28
+ for (const sql of Q.SESSION_SQL)
29
+ await session.query(sql);
30
+ const server = await json(session, Q.SERVER_SQL);
31
+ if (server.version < MIN_SERVER_VERSION) {
32
+ throw new DbAdminError(`Backups need PostgreSQL 14 or newer; this server is ${server.server}.`, 400, 'server-too-old');
33
+ }
34
+ return server;
35
+ }
36
+ export async function schemaChoices(session) {
37
+ const schemas = await json(session, Q.SCHEMAS_SQL);
38
+ return schemas.map((s) => ({
39
+ ...s,
40
+ tables: Number(s.tables),
41
+ objects: Number(s.objects),
42
+ extensions: Number(s.extensions),
43
+ selected: s.mine && (Number(s.objects) > 0 || Number(s.extensions) === 0),
44
+ }));
45
+ }
46
+ /** What a backup of `schemas` would leave out: per schema, and database-wide (schema null). */
47
+ export function notIncluded(session, schemas) {
48
+ return json(session, Q.NOT_INCLUDED_SQL, [schemas]);
49
+ }
50
+ /**
51
+ * The backup of `schemas`, as text pieces. The session must be a snapshot already prepared; the
52
+ * caller ends it. `summary` is filled in as the rows go by.
53
+ */
54
+ export async function* backupSql(session, server, schemas, now, summary = { tables: 0, rows: 0 }) {
55
+ const catalog = await readCatalog(session, schemas);
56
+ const plan = new Plan(catalog);
57
+ const header = {
58
+ format: 'otw-db',
59
+ version: BACKUP_VERSION,
60
+ createdAt: now.toISOString(),
61
+ database: server.database,
62
+ server: server.server,
63
+ serverVersion: server.version,
64
+ schemas: [...schemas],
65
+ roles: [...plan.roles].sort(),
66
+ notIncluded: catalog.notIncluded,
67
+ };
68
+ yield headerLine(header);
69
+ yield preamble(header);
70
+ yield section('Schemas', plan.schemaStatements());
71
+ yield section('Extensions', plan.extensionStatements());
72
+ yield section('Types, functions, sequences, tables and views', plan.preData());
73
+ for (const table of plan.dataTables()) {
74
+ yield `\n-- Data: ${table.schema}.${table.name}\n`;
75
+ let rows = 0;
76
+ for await (const piece of tableRows(session, table)) {
77
+ rows += piece.rows;
78
+ yield piece.sql;
79
+ }
80
+ summary.tables += 1;
81
+ summary.rows += rows;
82
+ }
83
+ yield section('Sequences', plan.sequenceValues());
84
+ yield section('Keys, indexes and constraints', plan.postData());
85
+ yield section('Comments, owners and privileges', plan.finishing());
86
+ yield '\n';
87
+ yield trailerLine(summary);
88
+ }
89
+ async function readCatalog(session, schemas) {
90
+ const read = (sql) => json(session, sql, [schemas]);
91
+ // One after another: a session runs one statement at a time.
92
+ return {
93
+ schemas: await read(Q.SCHEMA_DETAILS_SQL),
94
+ extensions: await json(session, Q.EXTENSIONS_SQL),
95
+ needed: await read(Q.NEEDED_EXTENSIONS_SQL),
96
+ types: await read(Q.TYPES_SQL),
97
+ functions: await read(Q.FUNCTIONS_SQL),
98
+ sequences: await read(Q.SEQUENCES_SQL),
99
+ tables: await read(Q.TABLES_SQL),
100
+ views: await read(Q.VIEWS_SQL),
101
+ constraints: await read(Q.CONSTRAINTS_SQL),
102
+ indexes: await read(Q.INDEXES_SQL),
103
+ triggers: await read(Q.TRIGGERS_SQL),
104
+ rules: await read(Q.RULES_SQL),
105
+ policies: await read(Q.POLICIES_SQL),
106
+ statistics: await read(Q.STATISTICS_SQL),
107
+ dependencies: await json(session, Q.DEPENDENCIES_SQL),
108
+ notIncluded: (await notIncluded(session, schemas)).map((x) => x.what),
109
+ user: (await json(session, Q.SERVER_SQL)).user,
110
+ };
111
+ }
112
+ const key = (catalog, oid) => `${catalog}:${oid}`;
113
+ /** The statements of a backup, from its catalog. */
114
+ class Plan {
115
+ roles = new Set();
116
+ #catalog;
117
+ #schemas;
118
+ #relations = new Map();
119
+ #indexes = new Map();
120
+ /** Pre-data, in the order placed: matviews are refreshed in the same order. */
121
+ #placed = [];
122
+ #deferred = [];
123
+ constructor(catalog) {
124
+ this.#catalog = catalog;
125
+ this.#schemas = new Set(catalog.schemas.map((s) => s.name));
126
+ for (const t of catalog.tables)
127
+ this.#relations.set(t.oid, t);
128
+ for (const v of catalog.views)
129
+ this.#relations.set(v.oid, v);
130
+ for (const s of catalog.sequences)
131
+ this.#relations.set(s.oid, { ...s, kind: 'S' });
132
+ for (const i of catalog.indexes)
133
+ this.#indexes.set(i.oid, i);
134
+ this.#collectRoles();
135
+ }
136
+ #name(oid) {
137
+ const relation = this.#relations.get(oid);
138
+ if (!relation)
139
+ throw new Error(`otw-db: relation ${oid} isn't in the backup`);
140
+ return qualified(relation.schema, relation.name);
141
+ }
142
+ #collectRoles() {
143
+ const c = this.#catalog;
144
+ const owners = [...c.types, ...c.functions, ...c.sequences, ...c.tables, ...c.views];
145
+ for (const o of owners) {
146
+ if (o.owner !== c.user)
147
+ this.roles.add(o.owner);
148
+ this.#aclRoles(o.acl);
149
+ }
150
+ for (const t of [...c.tables, ...c.views])
151
+ for (const col of t.columns)
152
+ this.#aclRoles(col.acl);
153
+ for (const s of c.schemas) {
154
+ this.#aclRoles(s.acl);
155
+ for (const d of s.defaults) {
156
+ this.roles.add(d.role);
157
+ for (const g of d.grants)
158
+ if (g.role)
159
+ this.roles.add(g.role);
160
+ }
161
+ }
162
+ for (const p of c.policies)
163
+ for (const r of p.roles ?? [])
164
+ if (r)
165
+ this.roles.add(r);
166
+ }
167
+ #aclRoles(acl) {
168
+ for (const entry of [...(acl?.grant ?? []), ...(acl?.revoke ?? [])]) {
169
+ if (entry.role)
170
+ this.roles.add(entry.role);
171
+ }
172
+ }
173
+ /** Each schema emptied, or made when the server hasn't got it. */
174
+ schemaStatements() {
175
+ return this.#catalog.schemas.map((schema) => {
176
+ const made = [];
177
+ if (schema.owner !== this.#catalog.user) {
178
+ made.push(`ALTER SCHEMA ${quote(schema.name)} OWNER TO ${quote(schema.owner)}`);
179
+ }
180
+ made.push(...privileges(`SCHEMA ${quote(schema.name)}`, schema.acl));
181
+ for (const d of schema.defaults) {
182
+ const on = DEFAULT_ON[d.type];
183
+ if (!on)
184
+ continue;
185
+ for (const [grantee, grantable, list] of grouped(d.grants)) {
186
+ made.push(`ALTER DEFAULT PRIVILEGES FOR ROLE ${quote(d.role)} IN SCHEMA ${quote(schema.name)} GRANT ${list.join(', ')} ON ${on} TO ${grantee}${grantable ? ' WITH GRANT OPTION' : ''}`);
187
+ }
188
+ }
189
+ if (schema.comment !== null) {
190
+ made.push(`COMMENT ON SCHEMA ${quote(schema.name)} IS ${literal(schema.comment)}`);
191
+ }
192
+ return emptySchema(schema.name, made);
193
+ });
194
+ }
195
+ /**
196
+ * The database's extensions. Those in the schemas, and those their objects are seen to use (a
197
+ * column of citext, an index with pg_trgm's operators), must be made. The rest are made where
198
+ * the server has them, and skipped with a notice where it hasn't: a function's body may call
199
+ * one, and PostgreSQL records nothing a body uses.
200
+ */
201
+ extensionStatements() {
202
+ const needed = new Set(this.#catalog.needed.map(Number));
203
+ return this.#catalog.extensions.map((x) => {
204
+ const inBackup = this.#schemas.has(x.schema);
205
+ const statements = [
206
+ ...(inBackup ? [] : [`CREATE SCHEMA IF NOT EXISTS ${quote(x.schema)}`]),
207
+ `CREATE EXTENSION IF NOT EXISTS ${quote(x.name)} WITH SCHEMA ${quote(x.schema)}`,
208
+ ];
209
+ if (inBackup || needed.has(Number(x.oid)))
210
+ return statements.map((s) => `${s};`).join('\n');
211
+ const body = `BEGIN ${statements.map((s) => `EXECUTE ${literal(s)};`).join(' ')} EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'otw-db skipped extension ${x.name.replaceAll("'", "''")}: %', SQLERRM; END`;
212
+ const tag = dollarTag(body);
213
+ return `DO ${tag} ${body} ${tag};`;
214
+ });
215
+ }
216
+ /**
217
+ * Types, functions, sequences, tables and views, each after what it needs: Kahn's order, ties
218
+ * broken by kind, then schema, then name, so the same database gives the same file.
219
+ */
220
+ preData() {
221
+ const items = this.#items().sort((a, b) => a.rank - b.rank || compare(a.schema, b.schema) || compare(a.name, b.name));
222
+ const at = new Map(items.map((item, i) => [item.key, i]));
223
+ const unmet = items.map((item) => item.needs.size);
224
+ const dependents = items.map(() => []);
225
+ items.forEach((item, i) => {
226
+ for (const need of item.needs.keys())
227
+ dependents[at.get(need)].push(i);
228
+ });
229
+ const placed = new Array(items.length).fill(false);
230
+ const ready = new Heap();
231
+ unmet.forEach((count, i) => count === 0 && ready.push(i));
232
+ const out = [];
233
+ const place = (i, deferDefaults) => {
234
+ placed[i] = true;
235
+ const item = items[i];
236
+ this.#placed.push(item);
237
+ out.push(...item.build(deferDefaults));
238
+ for (const d of dependents[i])
239
+ if (--unmet[d] === 0 && !placed[d])
240
+ ready.push(d);
241
+ };
242
+ for (let left = items.length; left > 0; left -= 1) {
243
+ const next = ready.pop();
244
+ if (next !== undefined) {
245
+ if (placed[next]) {
246
+ left += 1;
247
+ continue;
248
+ }
249
+ place(next, false);
250
+ continue;
251
+ }
252
+ // A cycle: a table whose default calls a function that needs the table. The table goes
253
+ // first and its defaults are set once the function exists.
254
+ const waiting = (i) => !placed[i];
255
+ const deferrable = items.findIndex((item, i) => waiting(i) &&
256
+ [...item.needs].every(([need, how]) => placed[at.get(need)] || how === 'default'));
257
+ // Something even that can't order: the first in line goes, and a restore says what failed.
258
+ place(deferrable === -1 ? items.findIndex((_, i) => waiting(i)) : deferrable, deferrable !== -1);
259
+ }
260
+ return [...out, ...this.#deferred];
261
+ }
262
+ #items() {
263
+ const c = this.#catalog;
264
+ const items = [];
265
+ for (const t of c.types) {
266
+ items.push({
267
+ key: key(Q.PG_TYPE, t.oid),
268
+ rank: t.kind === 'e' || t.kind === 'r' ? 0 : 1,
269
+ schema: t.schema,
270
+ name: t.name,
271
+ build: () => typeStatements(t),
272
+ needs: new Map(),
273
+ });
274
+ }
275
+ for (const f of c.functions) {
276
+ items.push({
277
+ key: key(Q.PG_PROC, f.oid),
278
+ rank: 2,
279
+ schema: f.schema,
280
+ name: f.name,
281
+ build: () => [`${f.def.trimEnd()};`],
282
+ needs: new Map(),
283
+ });
284
+ }
285
+ for (const s of c.sequences) {
286
+ items.push({
287
+ key: key(Q.PG_CLASS, s.oid),
288
+ rank: 3,
289
+ schema: s.schema,
290
+ name: s.name,
291
+ build: () => [
292
+ `CREATE ${s.unlogged ? 'UNLOGGED ' : ''}SEQUENCE ${qualified(s.schema, s.name)} AS ${s.settings.type}${sequenceOptions(s.settings)};`,
293
+ ],
294
+ needs: new Map(),
295
+ });
296
+ }
297
+ for (const t of c.tables) {
298
+ const needs = new Map();
299
+ if (t.parent)
300
+ needs.set(key(Q.PG_CLASS, t.parent), 'hard');
301
+ items.push({
302
+ key: key(Q.PG_CLASS, t.oid),
303
+ rank: 4,
304
+ schema: t.schema,
305
+ name: t.name,
306
+ build: (defer) => this.#tableStatements(t, defer),
307
+ needs,
308
+ });
309
+ }
310
+ for (const v of c.views) {
311
+ items.push({
312
+ key: key(Q.PG_CLASS, v.oid),
313
+ rank: v.kind === 'v' ? 5 : 6,
314
+ schema: v.schema,
315
+ name: v.name,
316
+ build: () => viewStatements(v),
317
+ needs: new Map(),
318
+ });
319
+ }
320
+ const byKey = new Map(items.map((item) => [item.key, item]));
321
+ for (const [cat, oid, refcat, refoid, how] of c.dependencies) {
322
+ const item = byKey.get(key(cat, oid));
323
+ const need = key(refcat, refoid);
324
+ if (!item || need === item.key || !byKey.has(need))
325
+ continue;
326
+ // A hard need stays hard, whatever else needs the same.
327
+ if (item.needs.get(need) !== 'hard')
328
+ item.needs.set(need, how);
329
+ }
330
+ return items;
331
+ }
332
+ #tableStatements(t, deferDefaults) {
333
+ const name = qualified(t.schema, t.name);
334
+ const unlogged = t.unlogged ? 'UNLOGGED ' : '';
335
+ const tail = `${t.partitionKey ? ` PARTITION BY ${t.partitionKey}` : ''}${withOptions(t.options)}`;
336
+ const after = [];
337
+ if (t.parent) {
338
+ // A partition takes its columns from its parent.
339
+ return [
340
+ `CREATE ${unlogged}TABLE ${name} PARTITION OF ${this.#name(t.parent)} ${t.bound}${tail};`,
341
+ ...t.checks
342
+ .filter((check) => check.valid)
343
+ .map((check) => `ALTER TABLE ONLY ${name} ADD CONSTRAINT ${quote(check.name)} ${check.def};`),
344
+ ];
345
+ }
346
+ const named = new Map(t.notNulls.map((n) => [n.column, n]));
347
+ const lines = t.columns.map((column) => {
348
+ let line = ` ${quote(column.name)} ${column.type}`;
349
+ if (column.collation)
350
+ line += ` COLLATE ${column.collation}`;
351
+ if (column.generated) {
352
+ line += ` GENERATED ALWAYS AS (${column.generated.expr}) ${column.generated.kind === 's' ? 'STORED' : 'VIRTUAL'}`;
353
+ }
354
+ if (column.identity) {
355
+ const s = column.identity.sequence;
356
+ line += ` GENERATED ${column.identity.kind === 'a' ? 'ALWAYS' : 'BY DEFAULT'} AS IDENTITY (SEQUENCE NAME ${s.name}${sequenceOptions(s)})`;
357
+ }
358
+ if (column.default !== null) {
359
+ if (deferDefaults) {
360
+ after.push(`ALTER TABLE ONLY ${name} ALTER COLUMN ${quote(column.name)} SET DEFAULT ${column.default};`);
361
+ }
362
+ else
363
+ line += ` DEFAULT ${column.default}`;
364
+ }
365
+ const notNull = named.get(column.name);
366
+ if (notNull && !notNull.valid) {
367
+ // Checked once the rows are in, as it was made: NOT VALID.
368
+ }
369
+ else if (notNull) {
370
+ line += ` CONSTRAINT ${quote(notNull.name)} NOT NULL${notNull.noInherit ? ' NO INHERIT' : ''}`;
371
+ }
372
+ else if (column.notNull)
373
+ line += ' NOT NULL';
374
+ return line;
375
+ });
376
+ for (const check of t.checks) {
377
+ if (check.valid)
378
+ lines.push(` CONSTRAINT ${quote(check.name)} ${check.def}`);
379
+ }
380
+ this.#deferred.push(...after);
381
+ return [`CREATE ${unlogged}TABLE ${name} (\n${lines.join(',\n')}\n)${tail};`];
382
+ }
383
+ /** The tables whose rows the backup holds: a partitioned table's live in its partitions. */
384
+ dataTables() {
385
+ return this.#catalog.tables
386
+ .filter((t) => t.kind === 'r')
387
+ .map((t) => {
388
+ const columns = t.columns.filter((c) => !c.generated);
389
+ return {
390
+ schema: t.schema,
391
+ name: t.name,
392
+ columns: columns.map((c) => c.name),
393
+ overriding: columns.some((c) => c.identity?.kind === 'a'),
394
+ };
395
+ });
396
+ }
397
+ /** Where each sequence had got to, its own and identity columns' alike. */
398
+ sequenceValues() {
399
+ const settings = [
400
+ ...this.#catalog.sequences.map((s) => s.settings),
401
+ ...this.#catalog.tables.flatMap((t) => t.columns.flatMap((c) => (c.identity ? [c.identity.sequence] : []))),
402
+ ];
403
+ return settings
404
+ .filter((s) => s.last !== null)
405
+ .map((s) => `SELECT pg_catalog.setval(${literal(s.name)}, ${s.last}, true);`);
406
+ }
407
+ postData() {
408
+ const c = this.#catalog;
409
+ const out = [];
410
+ for (const t of c.tables) {
411
+ const name = qualified(t.schema, t.name);
412
+ for (const check of t.checks.filter((k) => !k.valid)) {
413
+ out.push(`ALTER TABLE ONLY ${name} ADD CONSTRAINT ${quote(check.name)} ${check.def};`);
414
+ }
415
+ for (const n of t.notNulls.filter((k) => !k.valid && k.local)) {
416
+ out.push(`ALTER TABLE ONLY ${name} ADD CONSTRAINT ${quote(n.name)} ${n.def};`);
417
+ }
418
+ }
419
+ // Keys first: a foreign key needs the key it references. A partition's own key is made, then
420
+ // attached to its parent's, as pg_dump does.
421
+ for (const k of c.constraints.filter((k) => k.type !== 'f')) {
422
+ out.push(`ALTER TABLE ONLY ${this.#name(k.table)} ADD CONSTRAINT ${quote(k.name)} ${k.def};`);
423
+ }
424
+ for (const index of c.indexes.filter((i) => !i.constraint))
425
+ out.push(`${index.def};`);
426
+ for (const index of c.indexes) {
427
+ const parent = index.parent === null ? undefined : this.#indexes.get(index.parent);
428
+ if (parent) {
429
+ out.push(`ALTER INDEX ${qualified(parent.schema, parent.name)} ATTACH PARTITION ${qualified(index.schema, index.name)};`);
430
+ }
431
+ if (index.clustered) {
432
+ out.push(`ALTER TABLE ${this.#name(index.table)} CLUSTER ON ${quote(index.name)};`);
433
+ }
434
+ }
435
+ for (const t of c.tables) {
436
+ const name = qualified(t.schema, t.name);
437
+ if (t.replicaIdentity === 'f')
438
+ out.push(`ALTER TABLE ONLY ${name} REPLICA IDENTITY FULL;`);
439
+ if (t.replicaIdentity === 'n')
440
+ out.push(`ALTER TABLE ONLY ${name} REPLICA IDENTITY NOTHING;`);
441
+ if (t.replicaIdentity === 'i' && t.replicaIndex) {
442
+ out.push(`ALTER TABLE ONLY ${name} REPLICA IDENTITY USING INDEX ${quote(t.replicaIndex)};`);
443
+ }
444
+ }
445
+ // A partitioned table's foreign key reaches its partitions itself, and can't be ONLY.
446
+ for (const k of c.constraints.filter((k) => k.type === 'f' && !k.inherited)) {
447
+ const only = k.partitioned ? '' : 'ONLY ';
448
+ out.push(`ALTER TABLE ${only}${this.#name(k.table)} ADD CONSTRAINT ${quote(k.name)} ${k.def};`);
449
+ }
450
+ for (const trigger of c.triggers) {
451
+ out.push(`${trigger.def};`);
452
+ const state = TRIGGER_STATES[trigger.enabled];
453
+ if (state) {
454
+ out.push(`ALTER TABLE ${this.#name(trigger.table)} ${state} TRIGGER ${quote(trigger.name)};`);
455
+ }
456
+ }
457
+ for (const rule of c.rules)
458
+ out.push(rule.def.trimEnd().replace(/;?$/, ';'));
459
+ for (const t of c.tables) {
460
+ const name = qualified(t.schema, t.name);
461
+ if (t.rls)
462
+ out.push(`ALTER TABLE ${name} ENABLE ROW LEVEL SECURITY;`);
463
+ if (t.forceRls)
464
+ out.push(`ALTER TABLE ${name} FORCE ROW LEVEL SECURITY;`);
465
+ }
466
+ for (const p of c.policies) {
467
+ const roles = (p.roles ?? [null]).map((r) => (r === null ? 'PUBLIC' : quote(r)));
468
+ const statement = `CREATE POLICY ${quote(p.name)} ON ${this.#name(p.table)} AS ${p.permissive ? 'PERMISSIVE' : 'RESTRICTIVE'} FOR ${POLICY_COMMANDS[p.command] ?? 'ALL'} TO ${roles.join(', ')}${p.using ? ` USING (${p.using})` : ''}${p.check ? ` WITH CHECK (${p.check})` : ''}`;
469
+ // A policy for a role the server lacks can't be made: without it, that role has less access,
470
+ // never more.
471
+ out.push(p.roles?.some((r) => r !== null) ? guarded(statement) : `${statement};`);
472
+ }
473
+ for (const s of c.statistics)
474
+ out.push(`${s.def};`);
475
+ for (const s of c.sequences) {
476
+ if (s.ownedBy) {
477
+ out.push(`ALTER SEQUENCE ${qualified(s.schema, s.name)} OWNED BY ${this.#name(s.ownedBy.table)}.${quote(s.ownedBy.column)};`);
478
+ }
479
+ }
480
+ for (const item of this.#placed) {
481
+ const view = c.views.find((v) => key(Q.PG_CLASS, v.oid) === item.key);
482
+ if (view?.kind === 'm' && view.populated) {
483
+ out.push(`REFRESH MATERIALIZED VIEW ${qualified(view.schema, view.name)};`);
484
+ }
485
+ }
486
+ return out;
487
+ }
488
+ /** Comments, then owners (only those that aren't the backing-up login), then privileges. */
489
+ finishing() {
490
+ const c = this.#catalog;
491
+ const comments = [];
492
+ const owners = [];
493
+ const grants = [];
494
+ const comment = (on, text) => {
495
+ if (text !== null)
496
+ comments.push(`COMMENT ON ${on} IS ${literal(text)};`);
497
+ };
498
+ const own = (alter, owner) => {
499
+ if (owner !== c.user)
500
+ owners.push(guarded(`ALTER ${alter} OWNER TO ${quote(owner)}`));
501
+ };
502
+ for (const t of c.types) {
503
+ const name = qualified(t.schema, t.name);
504
+ const kind = t.kind === 'd' ? 'DOMAIN' : 'TYPE';
505
+ comment(`${kind} ${name}`, t.comment);
506
+ for (const a of t.attributes ?? [])
507
+ comment(`COLUMN ${name}.${quote(a.name)}`, a.comment);
508
+ for (const k of t.checks ?? [])
509
+ comment(`CONSTRAINT ${quote(k.name)} ON DOMAIN ${name}`, k.comment);
510
+ own(`${kind} ${name}`, t.owner);
511
+ grants.push(...privileges(`${kind} ${name}`, t.acl).map(guardedIfNamed));
512
+ }
513
+ for (const f of c.functions) {
514
+ const kind = f.kind === 'p' ? 'PROCEDURE' : 'FUNCTION';
515
+ comment(`${kind} ${f.signature}`, f.comment);
516
+ own(`${kind} ${f.signature}`, f.owner);
517
+ grants.push(...privileges(`${kind} ${f.signature}`, f.acl).map(guardedIfNamed));
518
+ }
519
+ for (const s of c.sequences) {
520
+ const name = qualified(s.schema, s.name);
521
+ comment(`SEQUENCE ${name}`, s.comment);
522
+ // A sequence a column owns has its table's owner, and PostgreSQL won't change it alone.
523
+ if (!s.ownedBy)
524
+ own(`SEQUENCE ${name}`, s.owner);
525
+ grants.push(...privileges(`SEQUENCE ${name}`, s.acl).map(guardedIfNamed));
526
+ }
527
+ for (const r of [...c.tables, ...c.views]) {
528
+ const name = qualified(r.schema, r.name);
529
+ const kind = 'def' in r ? (r.kind === 'm' ? 'MATERIALIZED VIEW' : 'VIEW') : 'TABLE';
530
+ comment(`${kind} ${name}`, r.comment);
531
+ for (const col of r.columns) {
532
+ comment(`COLUMN ${name}.${quote(col.name)}`, col.comment);
533
+ grants.push(...privileges(`TABLE ${name}`, col.acl, quote(col.name)).map(guardedIfNamed));
534
+ }
535
+ own(`${kind} ${name}`, r.owner);
536
+ grants.push(...privileges(`TABLE ${name}`, r.acl).map(guardedIfNamed));
537
+ if ('checks' in r) {
538
+ for (const k of [...r.checks, ...r.notNulls.filter((n) => n.local)]) {
539
+ comment(`CONSTRAINT ${quote(k.name)} ON ${name}`, k.comment);
540
+ }
541
+ }
542
+ }
543
+ for (const k of c.constraints) {
544
+ if (k.type === 'f' && k.inherited)
545
+ continue;
546
+ comment(`CONSTRAINT ${quote(k.name)} ON ${this.#name(k.table)}`, k.comment);
547
+ }
548
+ for (const i of c.indexes) {
549
+ if (!i.constraint)
550
+ comment(`INDEX ${qualified(i.schema, i.name)}`, i.comment);
551
+ }
552
+ for (const t of c.triggers)
553
+ comment(`TRIGGER ${quote(t.name)} ON ${this.#name(t.table)}`, t.comment);
554
+ for (const r of c.rules)
555
+ comment(`RULE ${quote(r.name)} ON ${this.#name(r.table)}`, r.comment);
556
+ for (const p of c.policies)
557
+ comment(`POLICY ${quote(p.name)} ON ${this.#name(p.table)}`, p.comment);
558
+ for (const s of c.statistics)
559
+ comment(`STATISTICS ${s.name}`, s.comment);
560
+ return [...comments, ...owners, ...grants];
561
+ }
562
+ }
563
+ /** A table's rows as INSERTs, read a batch at a time through a cursor. */
564
+ async function* tableRows(session, table) {
565
+ const name = qualified(table.schema, table.name);
566
+ if (!table.columns.length) {
567
+ // Nothing to insert but the rows themselves: every column is generated.
568
+ const [[count]] = (await session.query(`SELECT count(*) FROM ONLY ${name}`)).rows;
569
+ const rows = Number(count);
570
+ if (rows)
571
+ yield { sql: `INSERT INTO ${name} DEFAULT VALUES;\n`.repeat(rows), rows };
572
+ return;
573
+ }
574
+ const columns = table.columns.map(quote);
575
+ // Every value as its type's own text: it reads back the same, whatever the type.
576
+ await session.query(`DECLARE otw_db_rows NO SCROLL CURSOR FOR SELECT ${columns.map((c) => `${c}::text`).join(', ')} FROM ONLY ${name}`);
577
+ const head = `INSERT INTO ${name} (${columns.join(', ')}) ${table.overriding ? 'OVERRIDING SYSTEM VALUE ' : ''}VALUES\n`;
578
+ let tuples = [];
579
+ let bytes = 0;
580
+ const flush = () => {
581
+ const piece = { sql: `${head}${tuples.join(',\n')};\n`, rows: tuples.length };
582
+ tuples = [];
583
+ bytes = 0;
584
+ return piece;
585
+ };
586
+ for (;;) {
587
+ const { rows } = await session.query(`FETCH FORWARD ${FETCH} FROM otw_db_rows`);
588
+ if (!rows.length)
589
+ break;
590
+ for (const row of rows) {
591
+ const tuple = `(${row.map(literal).join(', ')})`;
592
+ tuples.push(tuple);
593
+ bytes += tuple.length;
594
+ if (tuples.length >= ROWS_PER_INSERT || bytes >= BYTES_PER_INSERT)
595
+ yield flush();
596
+ }
597
+ }
598
+ if (tuples.length)
599
+ yield flush();
600
+ await session.query('CLOSE otw_db_rows');
601
+ }
602
+ function typeStatements(t) {
603
+ const name = qualified(t.schema, t.name);
604
+ switch (t.kind) {
605
+ case 'e':
606
+ return [
607
+ `CREATE TYPE ${name} AS ENUM (${(t.labels ?? []).map((l) => literal(l)).join(', ')});`,
608
+ ];
609
+ case 'c': {
610
+ const attributes = (t.attributes ?? []).map((a) => ` ${quote(a.name)} ${a.type}${a.collation ? ` COLLATE ${a.collation}` : ''}`);
611
+ return [`CREATE TYPE ${name} AS (\n${attributes.join(',\n')}\n);`];
612
+ }
613
+ case 'd': {
614
+ let statement = `CREATE DOMAIN ${name} AS ${t.base}`;
615
+ if (t.collation)
616
+ statement += ` COLLATE ${t.collation}`;
617
+ if (t.default !== null)
618
+ statement += ` DEFAULT ${t.default}`;
619
+ if (t.notNull)
620
+ statement += ' NOT NULL';
621
+ return [
622
+ `${statement};`,
623
+ ...(t.checks ?? []).map((k) => `ALTER DOMAIN ${name} ADD CONSTRAINT ${quote(k.name)} ${k.def};`),
624
+ ];
625
+ }
626
+ case 'r': {
627
+ const r = t.range;
628
+ const options = [`SUBTYPE = ${r.subtype}`];
629
+ if (r.opclass)
630
+ options.push(`SUBTYPE_OPCLASS = ${r.opclass}`);
631
+ if (r.collation)
632
+ options.push(`COLLATION = ${r.collation}`);
633
+ if (r.diff)
634
+ options.push(`SUBTYPE_DIFF = ${r.diff}`);
635
+ if (r.multirange)
636
+ options.push(`MULTIRANGE_TYPE_NAME = ${r.multirange}`);
637
+ return [`CREATE TYPE ${name} AS RANGE (${options.join(', ')});`];
638
+ }
639
+ }
640
+ }
641
+ function viewStatements(v) {
642
+ const name = qualified(v.schema, v.name);
643
+ const query = v.def.trim().replace(/;$/, '');
644
+ const statements = v.kind === 'v'
645
+ ? [`CREATE VIEW ${name}${withOptions(v.options)} AS\n${query};`]
646
+ : [`CREATE MATERIALIZED VIEW ${name}${withOptions(v.options)} AS\n${query}\n WITH NO DATA;`];
647
+ for (const column of v.columns) {
648
+ if (column.default !== null) {
649
+ statements.push(`ALTER VIEW ${name} ALTER COLUMN ${quote(column.name)} SET DEFAULT ${column.default};`);
650
+ }
651
+ }
652
+ return statements;
653
+ }
654
+ function sequenceOptions(s) {
655
+ return ` START WITH ${s.start} INCREMENT BY ${s.increment} MINVALUE ${s.min} MAXVALUE ${s.max} CACHE ${s.cache}${s.cycle ? ' CYCLE' : ''}`;
656
+ }
657
+ function withOptions(options) {
658
+ return options?.length ? ` WITH (${options.join(', ')})` : '';
659
+ }
660
+ /** The grants and revokes that give an object its privileges; `column` for a column's. */
661
+ function privileges(on, acl, column) {
662
+ if (!acl)
663
+ return [];
664
+ const list = (privileges) => privileges.map((p) => (column ? `${p} (${column})` : p)).join(', ');
665
+ return [
666
+ ...grouped(acl.revoke).map(([grantee, , p]) => `REVOKE ${list(p)} ON ${on} FROM ${grantee}`),
667
+ ...grouped(acl.grant).map(([grantee, grantable, p]) => `GRANT ${list(p)} ON ${on} TO ${grantee}${grantable ? ' WITH GRANT OPTION' : ''}`),
668
+ ];
669
+ }
670
+ /** Privileges grouped by grantee and grant option: SELECT and INSERT to "app". */
671
+ function grouped(entries) {
672
+ const groups = new Map();
673
+ for (const e of entries) {
674
+ const grantee = e.role === null ? 'PUBLIC' : quote(e.role);
675
+ const id = `${grantee} ${e.grantable}`;
676
+ const group = groups.get(id) ?? { grantee, grantable: e.grantable, privileges: [] };
677
+ group.privileges.push(e.privilege);
678
+ groups.set(id, group);
679
+ }
680
+ return [...groups.values()].map((g) => [g.grantee, g.grantable, g.privileges]);
681
+ }
682
+ /** A statement that names a role: skipped, with a notice, where the role is missing. */
683
+ function guardedIfNamed(statement) {
684
+ return / (?:TO|FROM) PUBLIC(?: WITH GRANT OPTION)?$/.test(statement)
685
+ ? `${statement};`
686
+ : guarded(statement);
687
+ }
688
+ /**
689
+ * `statement`, run so that a missing role or a privilege the restoring login lacks skips it with
690
+ * a notice instead of failing the restore.
691
+ */
692
+ export function guarded(statement) {
693
+ const tag = dollarTag(statement);
694
+ return `DO ${tag} BEGIN EXECUTE ${literal(statement)}; EXCEPTION WHEN undefined_object OR insufficient_privilege THEN RAISE NOTICE 'otw-db skipped: %', SQLERRM; END ${tag};`;
695
+ }
696
+ /**
697
+ * A schema emptied of what a backup makes again, or made, with `made` run after, when the server
698
+ * hasn't got it. Emptying keeps the schema itself, its owner and its privileges as they are. It
699
+ * drops extensions, tables, views, sequences, functions and types; operators, aggregates and the
700
+ * like, which a backup can't hold, stay.
701
+ */
702
+ export function emptySchema(schema, made) {
703
+ const target = literal(schema);
704
+ const notMember = (catalog, oid) => `NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend e WHERE e.classid = ${catalog} AND e.objid = ${oid} AND e.deptype = 'e')`;
705
+ const then = made
706
+ .map((statement) => ` BEGIN EXECUTE ${literal(statement)}; EXCEPTION WHEN undefined_object OR insufficient_privilege THEN RAISE NOTICE 'otw-db skipped: %', SQLERRM; END;`)
707
+ .join('\n');
708
+ const body = `
709
+ DECLARE
710
+ target constant text := ${target};
711
+ drop_it text;
712
+ BEGIN
713
+ IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = target) THEN
714
+ EXECUTE pg_catalog.format('CREATE SCHEMA %I', target);
715
+ ${then}
716
+ RETURN;
717
+ END IF;
718
+ -- Each statement is written before any runs: one that a CASCADE has made pointless finds IF EXISTS.
719
+ FOREACH drop_it IN ARRAY ARRAY(
720
+ SELECT d.sql FROM (
721
+ SELECT 1 AS step, x.extname AS name, pg_catalog.format('DROP EXTENSION IF EXISTS %I CASCADE', x.extname) AS sql
722
+ FROM pg_catalog.pg_extension x JOIN pg_catalog.pg_namespace n ON n.oid = x.extnamespace
723
+ WHERE n.nspname = target
724
+ UNION ALL
725
+ SELECT CASE WHEN c.relkind IN ('v', 'm') THEN 2 ELSE 3 END, c.relname,
726
+ pg_catalog.format('DROP %s IF EXISTS %I.%I CASCADE', CASE c.relkind WHEN 'v' THEN 'VIEW'
727
+ WHEN 'm' THEN 'MATERIALIZED VIEW' WHEN 'S' THEN 'SEQUENCE' WHEN 'f' THEN 'FOREIGN TABLE'
728
+ ELSE 'TABLE' END, target, c.relname)
729
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
730
+ WHERE n.nspname = target AND c.relkind IN ('v', 'm', 'r', 'p', 'f', 'S') AND NOT c.relispartition
731
+ AND ${notMember(Q.PG_CLASS, 'c.oid')}
732
+ UNION ALL
733
+ SELECT 4, p.proname, pg_catalog.format('DROP ROUTINE IF EXISTS %s CASCADE', p.oid::pg_catalog.regprocedure)
734
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
735
+ JOIN pg_catalog.pg_language l ON l.oid = p.prolang
736
+ WHERE n.nspname = target AND p.prokind IN ('f', 'p', 'w') AND l.lanname NOT IN ('c', 'internal')
737
+ AND ${notMember(Q.PG_PROC, 'p.oid')}
738
+ UNION ALL
739
+ SELECT 5, t.typname, pg_catalog.format('DROP %s IF EXISTS %I.%I CASCADE',
740
+ CASE t.typtype WHEN 'd' THEN 'DOMAIN' ELSE 'TYPE' END, target, t.typname)
741
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
742
+ WHERE n.nspname = target AND ${notMember(Q.PG_TYPE, 't.oid')}
743
+ AND (t.typtype IN ('d', 'e', 'r') OR (t.typtype = 'c' AND EXISTS (
744
+ SELECT 1 FROM pg_catalog.pg_class r WHERE r.oid = t.typrelid AND r.relkind = 'c')))
745
+ ) d ORDER BY d.step, d.name
746
+ ) LOOP
747
+ EXECUTE drop_it;
748
+ END LOOP;
749
+ END
750
+ `;
751
+ const tag = dollarTag(body);
752
+ return `DO ${tag}${body}${tag};`;
753
+ }
754
+ function section(title, statements) {
755
+ return statements.length ? `\n-- ${title}\n\n${statements.join('\n')}\n` : '';
756
+ }
757
+ function preamble(header) {
758
+ const lines = [
759
+ '--',
760
+ `-- Database ${header.database} on ${header.server}: schemas ${header.schemas.join(', ')}.`,
761
+ `-- Made ${header.createdAt} by otw-db.`,
762
+ '--',
763
+ '-- Restoring it replaces everything in those schemas, and drops what elsewhere depends on it.',
764
+ '-- Restore it on the Database screen, or with psql, in one transaction:',
765
+ '-- gunzip -c this.sql.gz | psql --single-transaction -v ON_ERROR_STOP=1 -d <database URL>',
766
+ ...(header.notIncluded.length
767
+ ? ['--', '-- Not in this backup:', ...header.notIncluded.map((what) => `-- ${what}`)]
768
+ : []),
769
+ '--',
770
+ '',
771
+ 'SET statement_timeout = 0;',
772
+ "SET client_encoding = 'UTF8';",
773
+ 'SET standard_conforming_strings = on;',
774
+ "SELECT pg_catalog.set_config('search_path', '', false);",
775
+ 'SET check_function_bodies = false;',
776
+ 'SET xmloption = content;',
777
+ 'SET client_min_messages = warning;',
778
+ 'SET row_security = off;',
779
+ "SET datestyle = 'ISO, YMD';",
780
+ "SET intervalstyle = 'postgres';",
781
+ '',
782
+ ];
783
+ return lines.join('\n');
784
+ }
785
+ const DEFAULT_ON = {
786
+ r: 'TABLES',
787
+ S: 'SEQUENCES',
788
+ f: 'FUNCTIONS',
789
+ T: 'TYPES',
790
+ };
791
+ const TRIGGER_STATES = {
792
+ D: 'DISABLE',
793
+ R: 'ENABLE REPLICA',
794
+ A: 'ENABLE ALWAYS',
795
+ };
796
+ const POLICY_COMMANDS = {
797
+ r: 'SELECT',
798
+ a: 'INSERT',
799
+ w: 'UPDATE',
800
+ d: 'DELETE',
801
+ '*': 'ALL',
802
+ };
803
+ function qualified(schema, name) {
804
+ return `${quote(schema)}.${quote(name)}`;
805
+ }
806
+ /** A dollar quote's delimiter that `text` doesn't hold. */
807
+ function dollarTag(text) {
808
+ let tag = '$otwdb$';
809
+ for (let n = 1; text.includes(tag); n += 1)
810
+ tag = `$otwdb${n}$`;
811
+ return tag;
812
+ }
813
+ /** The smallest index first: the ready objects, in the order they sort. */
814
+ class Heap {
815
+ #items = [];
816
+ push(value) {
817
+ const a = this.#items;
818
+ a.push(value);
819
+ for (let i = a.length - 1; i > 0;) {
820
+ const parent = (i - 1) >> 1;
821
+ if (a[parent] <= a[i])
822
+ break;
823
+ [a[parent], a[i]] = [a[i], a[parent]];
824
+ i = parent;
825
+ }
826
+ }
827
+ pop() {
828
+ const a = this.#items;
829
+ if (!a.length)
830
+ return undefined;
831
+ const top = a[0];
832
+ const last = a.pop();
833
+ if (a.length) {
834
+ a[0] = last;
835
+ for (let i = 0;;) {
836
+ const l = 2 * i + 1;
837
+ const r = l + 1;
838
+ let least = i;
839
+ if (l < a.length && a[l] < a[least])
840
+ least = l;
841
+ if (r < a.length && a[r] < a[least])
842
+ least = r;
843
+ if (least === i)
844
+ break;
845
+ [a[least], a[i]] = [a[i], a[least]];
846
+ i = least;
847
+ }
848
+ }
849
+ return top;
850
+ }
851
+ }
852
+ /** Binary order, as a byte-wise collation would have it: the same everywhere. */
853
+ function compare(a, b) {
854
+ return a < b ? -1 : a > b ? 1 : 0;
855
+ }
856
+ async function json(session, sql, values) {
857
+ const { rows } = await session.query(sql, values);
858
+ return JSON.parse(rows[0][0]);
859
+ }
860
+ //# sourceMappingURL=dump.js.map