@otwdesign/db-core 1.2.0 → 1.3.1

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