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