@otwdesign/db-core 1.3.2 → 1.4.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 (72) hide show
  1. package/dist/backup/api.js +67 -9
  2. package/dist/backup/api.js.map +1 -1
  3. package/dist/backup/catalog.d.ts +9 -2
  4. package/dist/backup/catalog.js +42 -18
  5. package/dist/backup/catalog.js.map +1 -1
  6. package/dist/backup/dump.d.ts +6 -2
  7. package/dist/backup/dump.js +188 -20
  8. package/dist/backup/dump.js.map +1 -1
  9. package/dist/backup/restore.d.ts +9 -1
  10. package/dist/backup/restore.js +131 -11
  11. package/dist/backup/restore.js.map +1 -1
  12. package/dist/backup/split.d.ts +7 -2
  13. package/dist/backup/split.js +38 -6
  14. package/dist/backup/split.js.map +1 -1
  15. package/dist/backup/staging.d.ts +6 -1
  16. package/dist/backup/staging.js +38 -10
  17. package/dist/backup/staging.js.map +1 -1
  18. package/dist/drivers/mysql.d.ts +6 -0
  19. package/dist/drivers/mysql.js +142 -18
  20. package/dist/drivers/mysql.js.map +1 -1
  21. package/dist/drivers/pglite.d.ts +18 -3
  22. package/dist/drivers/pglite.js +357 -55
  23. package/dist/drivers/pglite.js.map +1 -1
  24. package/dist/drivers/postgres-catalog.d.ts +16 -1
  25. package/dist/drivers/postgres-catalog.js +34 -0
  26. package/dist/drivers/postgres-catalog.js.map +1 -1
  27. package/dist/drivers/postgres.d.ts +10 -0
  28. package/dist/drivers/postgres.js +203 -29
  29. package/dist/drivers/postgres.js.map +1 -1
  30. package/dist/drivers/read-only.d.ts +4 -0
  31. package/dist/drivers/read-only.js +156 -0
  32. package/dist/drivers/read-only.js.map +1 -0
  33. package/dist/drivers/sql.d.ts +51 -4
  34. package/dist/drivers/sql.js +112 -35
  35. package/dist/drivers/sql.js.map +1 -1
  36. package/dist/drivers/sqlite.d.ts +33 -1
  37. package/dist/drivers/sqlite.js +678 -107
  38. package/dist/drivers/sqlite.js.map +1 -1
  39. package/dist/export.d.ts +4 -5
  40. package/dist/export.js +21 -3
  41. package/dist/export.js.map +1 -1
  42. package/dist/format.js +7 -1
  43. package/dist/format.js.map +1 -1
  44. package/dist/handler.js +37 -15
  45. package/dist/handler.js.map +1 -1
  46. package/dist/index.d.ts +2 -2
  47. package/dist/index.js +1 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/types.d.ts +37 -3
  50. package/dist/words.d.ts +19 -0
  51. package/dist/words.js +76 -0
  52. package/dist/words.js.map +1 -0
  53. package/package.json +8 -7
  54. package/src/backup/api.ts +82 -14
  55. package/src/backup/catalog.ts +43 -18
  56. package/src/backup/dump.ts +208 -21
  57. package/src/backup/restore.ts +152 -12
  58. package/src/backup/split.ts +38 -6
  59. package/src/backup/staging.ts +51 -10
  60. package/src/drivers/mysql.ts +171 -21
  61. package/src/drivers/pglite.ts +419 -56
  62. package/src/drivers/postgres-catalog.ts +51 -1
  63. package/src/drivers/postgres.ts +241 -33
  64. package/src/drivers/read-only.ts +174 -0
  65. package/src/drivers/sql.ts +170 -37
  66. package/src/drivers/sqlite.ts +750 -104
  67. package/src/export.ts +26 -6
  68. package/src/format.ts +9 -1
  69. package/src/handler.ts +55 -19
  70. package/src/index.ts +7 -2
  71. package/src/types.ts +38 -1
  72. package/src/words.ts +67 -0
@@ -110,7 +110,7 @@ export async function* backupSql(
110
110
  yield section('Extensions', plan.extensionStatements())
111
111
  yield section('Types, functions, sequences, tables and views', plan.preData())
112
112
  for (const table of plan.dataTables()) {
113
- yield `\n-- Data: ${table.schema}.${table.name}\n`
113
+ yield `\n-- Data: ${inComment(`${table.schema}.${table.name}`)}\n`
114
114
  let rows = 0
115
115
  for await (const piece of tableRows(session, table)) {
116
116
  rows += piece.rows
@@ -182,7 +182,10 @@ interface SequenceSettings {
182
182
  max: string
183
183
  cache: string
184
184
  cycle: boolean
185
- last: string | null
185
+ /** Whether the backing-up login may read where it has got to. */
186
+ readable: boolean
187
+ /** Where it has got to: its last value, and whether that one was handed out. */
188
+ state?: { last: string; called: boolean }
186
189
  }
187
190
 
188
191
  interface SequenceRow extends Owned {
@@ -292,7 +295,7 @@ interface Catalog {
292
295
  async function readCatalog(session: Session, schemas: readonly string[]): Promise<Catalog> {
293
296
  const read = <T>(sql: string) => json<T>(session, sql, [schemas])
294
297
  // One after another: a session runs one statement at a time.
295
- return {
298
+ const catalog: Catalog = {
296
299
  schemas: await read(Q.SCHEMA_DETAILS_SQL),
297
300
  extensions: await json(session, Q.EXTENSIONS_SQL),
298
301
  needed: await read(Q.NEEDED_EXTENSIONS_SQL),
@@ -311,6 +314,34 @@ async function readCatalog(session: Session, schemas: readonly string[]): Promis
311
314
  notIncluded: (await notIncluded(session, schemas)).map((x) => x.what),
312
315
  user: (await json<Server>(session, Q.SERVER_SQL)).user,
313
316
  }
317
+ await readSequences(session, [
318
+ ...catalog.sequences.map((s) => s.settings),
319
+ ...catalog.tables.flatMap((t) =>
320
+ t.columns.flatMap((c) => (c.identity ? [c.identity.sequence] : [])),
321
+ ),
322
+ ])
323
+ return catalog
324
+ }
325
+
326
+ /**
327
+ * Where each sequence has got to, read from the sequence itself: its last value, and whether
328
+ * that one was handed out. pg_sequences shows no value for a sequence nobody has called, which
329
+ * is also what one looks like after ALTER SEQUENCE … RESTART: restored from that, it would start
330
+ * over from its first value. Many at a time, each a relation of its own.
331
+ */
332
+ async function readSequences(session: Session, sequences: SequenceSettings[]): Promise<void> {
333
+ const readable = sequences.filter((s) => s.readable)
334
+ for (let at = 0; at < readable.length; at += 200) {
335
+ const some = readable.slice(at, at + 200)
336
+ const { rows } = await session.query(
337
+ some
338
+ .map((s, i) => `SELECT ${i}, last_value::text, is_called FROM ${s.name}`)
339
+ .join(' UNION ALL '),
340
+ )
341
+ for (const [i, last, called] of rows) {
342
+ some[Number(i)]!.state = { last: last!, called: called === 't' || called === 'true' }
343
+ }
344
+ }
314
345
  }
315
346
 
316
347
  /** An object made before the data, and what it waits for. */
@@ -615,9 +646,11 @@ class Plan {
615
646
  t.columns.flatMap((c) => (c.identity ? [c.identity.sequence] : [])),
616
647
  ),
617
648
  ]
618
- return settings
619
- .filter((s) => s.last !== null)
620
- .map((s) => `SELECT pg_catalog.setval(${literal(s.name)}, ${s.last}, true);`)
649
+ return settings.flatMap((s) =>
650
+ s.state
651
+ ? [`SELECT pg_catalog.setval(${literal(s.name)}, ${s.state.last}, ${s.state.called});`]
652
+ : [],
653
+ )
621
654
  }
622
655
 
623
656
  postData(): string[] {
@@ -680,11 +713,14 @@ class Plan {
680
713
  if (t.forceRls) out.push(`ALTER TABLE ${name} FORCE ROW LEVEL SECURITY;`)
681
714
  }
682
715
  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};`)
716
+ const head = `CREATE POLICY ${quote(p.name)} ON ${this.#name(p.table)} AS ${p.permissive ? 'PERMISSIVE' : 'RESTRICTIVE'} FOR ${POLICY_COMMANDS[p.command] ?? 'ALL'} TO `
717
+ const tail = `${p.using ? ` USING (${p.using})` : ''}${p.check ? ` WITH CHECK (${p.check})` : ''}`
718
+ const named = (p.roles ?? []).filter((r): r is string => r !== null)
719
+ out.push(
720
+ named.length && named.length === p.roles?.length
721
+ ? policyForRoles(p.name, head, named, tail)
722
+ : `${head}PUBLIC${tail};`,
723
+ )
688
724
  }
689
725
  for (const s of c.statistics) out.push(`${s.def};`)
690
726
  for (const s of c.sequences) {
@@ -764,10 +800,16 @@ class Plan {
764
800
  for (const t of c.triggers)
765
801
  comment(`TRIGGER ${quote(t.name)} ON ${this.#name(t.table)}`, t.comment)
766
802
  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)
803
+ for (const p of c.policies) {
804
+ if (p.comment === null) continue
805
+ const on = `COMMENT ON POLICY ${quote(p.name)} ON ${this.#name(p.table)} IS ${literal(p.comment)}`
806
+ // A policy for roles this server has none of isn't made, so there's nothing to comment on.
807
+ comments.push(p.roles?.some((r) => r !== null) ? guarded(on) : `${on};`)
808
+ }
769
809
  for (const s of c.statistics) comment(`STATISTICS ${s.name}`, s.comment)
770
- return [...comments, ...owners, ...grants]
810
+ const made = c.types.length + c.functions.length + c.sequences.length + c.tables.length
811
+ const fresh = made + c.views.length ? [freshPrivileges(c.schemas.map((s) => s.name))] : []
812
+ return [...comments, ...owners, ...fresh, ...grants]
771
813
  }
772
814
  }
773
815
 
@@ -927,11 +969,136 @@ export function guarded(statement: string): string {
927
969
  return `DO ${tag} BEGIN EXECUTE ${literal(statement)}; EXCEPTION WHEN undefined_object OR insufficient_privilege THEN RAISE NOTICE 'otw-db skipped: %', SQLERRM; END ${tag};`
928
970
  }
929
971
 
972
+ /**
973
+ * A policy for named roles, made for those of them the restoring server has. Skipping it whole
974
+ * when one is missing would cost the others what it gave them, and a RESTRICTIVE policy gives a
975
+ * limit: without it, the roles that are there would see every row. With none of its roles there,
976
+ * nobody is left for it to apply to, and it's skipped with a notice.
977
+ */
978
+ function policyForRoles(name: string, head: string, roles: string[], tail: string): string {
979
+ const body = `
980
+ DECLARE
981
+ roles text;
982
+ BEGIN
983
+ SELECT pg_catalog.string_agg(pg_catalog.quote_ident(r.name), ', ' ORDER BY r.at) INTO roles
984
+ FROM pg_catalog.unnest(ARRAY[${roles.map(literal).join(', ')}]::text[]) WITH ORDINALITY AS r(name, at)
985
+ WHERE EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = r.name);
986
+ IF roles IS NULL THEN
987
+ RAISE NOTICE 'otw-db skipped: policy % is for roles this server has none of', ${literal(name)};
988
+ RETURN;
989
+ END IF;
990
+ EXECUTE ${literal(head)} || roles || ${literal(tail)};
991
+ EXCEPTION WHEN insufficient_privilege THEN
992
+ RAISE NOTICE 'otw-db skipped: %', SQLERRM;
993
+ END
994
+ `
995
+ const tag = dollarTag(body)
996
+ return `DO ${tag}${body}${tag};`
997
+ }
998
+
999
+ /**
1000
+ * Puts the privileges of what the restore just made in `schemas` (the kinds emptySchema drops, and
1001
+ * no others: what stays through a restore keeps its own) back to a new object's own,
1002
+ * before the backup's grants and revokes, which are written as changes from exactly that. A
1003
+ * server's default privileges (ALTER DEFAULT PRIVILEGES, as hosted servers set for their API
1004
+ * roles) give each new object more than that, or less: left alone, a function the backup had
1005
+ * revoked from everyone would come back callable by those roles.
1006
+ */
1007
+ function freshPrivileges(schemas: string[]): string {
1008
+ const notMember = (catalog: number, oid: string) =>
1009
+ `NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend e WHERE e.classid = ${catalog} AND e.objid = ${oid} AND e.deptype = 'e')`
1010
+ const entries = (acl: string) =>
1011
+ `SELECT a.grantee, a.privilege_type, a.is_grantable FROM pg_catalog.aclexplode(${acl}) a`
1012
+ const inside = `ARRAY[${schemas.map(literal).join(', ')}]::text[]`
1013
+ // What emptySchema left where it was, which the backup doesn't hold: its privileges are its
1014
+ // own, and nothing here could put them back. A foreign table, a table a backup can't hold, and
1015
+ // a partition of a table outside the schemas, which went nowhere when they were emptied.
1016
+ const stays = (c: string) => `(${c}.relkind = 'f' OR ${KEPT_TABLE(c)}
1017
+ OR (${c}.relispartition AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_inherits pi
1018
+ JOIN pg_catalog.pg_class pp ON pp.oid = pi.inhparent
1019
+ JOIN pg_catalog.pg_namespace pn ON pn.oid = pp.relnamespace
1020
+ WHERE pi.inhrelid = ${c}.oid AND pn.nspname = ANY (${inside}))))`
1021
+ const body = `
1022
+ DECLARE
1023
+ fix text;
1024
+ BEGIN
1025
+ FOREACH fix IN ARRAY ARRAY(
1026
+ WITH made AS (
1027
+ SELECT CASE c.relkind WHEN 'S' THEN 'SEQUENCE' ELSE 'TABLE' END AS kind,
1028
+ pg_catalog.format('%I.%I', n.nspname, c.relname) AS name, c.relacl AS acl,
1029
+ pg_catalog.acldefault(CASE c.relkind WHEN 'S' THEN 's' ELSE 'r' END::"char", c.relowner) AS fresh
1030
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
1031
+ WHERE n.nspname = ANY (${inside}) AND c.relacl IS NOT NULL
1032
+ AND c.relkind IN ('r', 'p', 'v', 'm', 'S') AND ${notMember(Q.PG_CLASS, 'c.oid')}
1033
+ AND NOT ${stays('c')}
1034
+ -- Nor the sequences their columns own, which stayed with them.
1035
+ AND NOT (c.relkind = 'S' AND EXISTS (SELECT 1 FROM pg_catalog.pg_depend o
1036
+ JOIN pg_catalog.pg_class oc ON oc.oid = o.refobjid
1037
+ WHERE o.classid = ${Q.PG_CLASS} AND o.objid = c.oid AND o.refclassid = ${Q.PG_CLASS}
1038
+ AND o.deptype IN ('a', 'i') AND ${stays('oc')}))
1039
+ UNION ALL
1040
+ SELECT 'ROUTINE', p.oid::pg_catalog.regprocedure::text, p.proacl, pg_catalog.acldefault('f', p.proowner)
1041
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
1042
+ JOIN pg_catalog.pg_language l ON l.oid = p.prolang
1043
+ WHERE n.nspname = ANY (${inside}) AND p.proacl IS NOT NULL
1044
+ -- Those a restore makes, as emptySchema drops them: an aggregate or a C function stays
1045
+ -- through a restore, and its privileges are its own.
1046
+ AND p.prokind IN ('f', 'p', 'w') AND l.lanname NOT IN ('c', 'internal')
1047
+ AND ${notMember(Q.PG_PROC, 'p.oid')}
1048
+ UNION ALL
1049
+ SELECT 'TYPE', pg_catalog.format('%I.%I', n.nspname, t.typname), t.typacl, pg_catalog.acldefault('T', t.typowner)
1050
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
1051
+ WHERE n.nspname = ANY (${inside}) AND t.typacl IS NOT NULL
1052
+ AND ${notMember(Q.PG_TYPE, 't.oid')}
1053
+ AND (t.typtype IN ('d', 'e', 'r') OR (t.typtype = 'c' AND EXISTS (
1054
+ SELECT 1 FROM pg_catalog.pg_class r WHERE r.oid = t.typrelid AND r.relkind = 'c')))
1055
+ ),
1056
+ changes AS (
1057
+ SELECT m.kind, m.name, true AS more, x.grantee, x.privilege_type
1058
+ FROM made m CROSS JOIN LATERAL (${entries('m.acl')} EXCEPT ${entries('m.fresh')}) x
1059
+ UNION ALL
1060
+ SELECT m.kind, m.name, false, x.grantee, x.privilege_type
1061
+ FROM made m CROSS JOIN LATERAL (${entries('m.fresh')} EXCEPT ${entries('m.acl')}) x
1062
+ )
1063
+ -- What a default added is revoked before what it took away is granted: a privilege that came
1064
+ -- with a grant option is both.
1065
+ SELECT pg_catalog.format(
1066
+ CASE WHEN c.more THEN 'REVOKE %s ON %s %s FROM %s' ELSE 'GRANT %s ON %s %s TO %s' END,
1067
+ c.privilege_type, c.kind, c.name,
1068
+ CASE WHEN c.grantee = 0 THEN 'PUBLIC' ELSE pg_catalog.quote_ident(pg_catalog.pg_get_userbyid(c.grantee)) END)
1069
+ FROM changes c ORDER BY c.more DESC, c.kind, c.name, c.grantee, c.privilege_type
1070
+ ) LOOP
1071
+ BEGIN
1072
+ EXECUTE fix;
1073
+ EXCEPTION WHEN insufficient_privilege THEN
1074
+ RAISE NOTICE 'otw-db skipped: %', SQLERRM;
1075
+ END;
1076
+ END LOOP;
1077
+ END
1078
+ `
1079
+ const tag = dollarTag(body)
1080
+ return `DO ${tag}${body}${tag};`
1081
+ }
1082
+
1083
+ /**
1084
+ * Whether the table `c` is one a backup can't hold, and so one a restore leaves where it is: a
1085
+ * typed table, or one that inherits another. (Foreign tables are their own kind, and a partition
1086
+ * goes or stays with its parent.)
1087
+ */
1088
+ const KEPT_TABLE = (
1089
+ c: string,
1090
+ ) => `(${c}.reloftype <> 0 OR (${c}.relkind IN ('r', 'p') AND NOT ${c}.relispartition
1091
+ AND EXISTS (SELECT 1 FROM pg_catalog.pg_inherits ki WHERE ki.inhrelid = ${c}.oid)))`
1092
+
930
1093
  /**
931
1094
  * A schema emptied of what a backup makes again, or made, with `made` run after, when the server
932
1095
  * 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.
1096
+ * drops extensions, tables, views, sequences, functions and types. What a backup can't hold
1097
+ * stays: operators, aggregates and the like, and the tables it can't hold (foreign tables, typed
1098
+ * tables, tables that inherit another, partitions of a table outside the schemas) with the
1099
+ * sequences their columns own. One of those that
1100
+ * needs something dropped here would go with it, by CASCADE: the restore's plan looks for that
1101
+ * first, and refuses.
935
1102
  */
936
1103
  export function emptySchema(schema: string, made: string[]): string {
937
1104
  const target = literal(schema)
@@ -962,11 +1129,18 @@ ${then}
962
1129
  UNION ALL
963
1130
  SELECT CASE WHEN c.relkind IN ('v', 'm') THEN 2 ELSE 3 END, c.relname,
964
1131
  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)
1132
+ WHEN 'm' THEN 'MATERIALIZED VIEW' WHEN 'S' THEN 'SEQUENCE' ELSE 'TABLE' END, target, c.relname)
967
1133
  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
1134
+ WHERE n.nspname = target AND c.relkind IN ('v', 'm', 'r', 'p', 'S') AND NOT c.relispartition
969
1135
  AND ${notMember(Q.PG_CLASS, 'c.oid')}
1136
+ AND NOT ${KEPT_TABLE('c')}
1137
+ AND NOT (c.relkind = 'S' AND EXISTS (SELECT 1 FROM pg_catalog.pg_depend o
1138
+ JOIN pg_catalog.pg_class oc ON oc.oid = o.refobjid
1139
+ WHERE o.classid = ${Q.PG_CLASS} AND o.objid = c.oid AND o.refclassid = ${Q.PG_CLASS}
1140
+ AND o.deptype IN ('a', 'i')
1141
+ -- A partition isn't dropped by name: it goes with its parent, and its sequence
1142
+ -- with it, or stays, its parent being outside the schemas, and its sequence too.
1143
+ AND (oc.relkind = 'f' OR oc.relispartition OR ${KEPT_TABLE('oc')})))
970
1144
  UNION ALL
971
1145
  SELECT 4, p.proname, pg_catalog.format('DROP ROUTINE IF EXISTS %s CASCADE', p.oid::pg_catalog.regprocedure)
972
1146
  FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
@@ -990,6 +1164,15 @@ END
990
1164
  return `DO ${tag}${body}${tag};`
991
1165
  }
992
1166
 
1167
+ /**
1168
+ * A name as a `--` comment can hold it: on the comment's line. A name may hold a line feed or a
1169
+ * carriage return, and either ends the comment for the server: what followed it in the name
1170
+ * would be SQL, run by whoever restores the backup.
1171
+ */
1172
+ function inComment(text: string): string {
1173
+ return text.replace(/[\n\r]+/g, ' ')
1174
+ }
1175
+
993
1176
  function section(title: string, statements: string[]): string {
994
1177
  return statements.length ? `\n-- ${title}\n\n${statements.join('\n')}\n` : ''
995
1178
  }
@@ -997,14 +1180,18 @@ function section(title: string, statements: string[]): string {
997
1180
  function preamble(header: BackupHeader): string {
998
1181
  const lines = [
999
1182
  '--',
1000
- `-- Database ${header.database} on ${header.server}: schemas ${header.schemas.join(', ')}.`,
1183
+ `-- Database ${inComment(header.database)} on ${inComment(header.server)}: schemas ${inComment(header.schemas.join(', '))}.`,
1001
1184
  `-- Made ${header.createdAt} by otw-db.`,
1002
1185
  '--',
1003
1186
  '-- Restoring it replaces everything in those schemas, and drops what elsewhere depends on it.',
1004
1187
  '-- Restore it on the Database screen, or with psql, in one transaction:',
1005
1188
  '-- gunzip -c this.sql.gz | psql --single-transaction -v ON_ERROR_STOP=1 -d <database URL>',
1006
1189
  ...(header.notIncluded.length
1007
- ? ['--', '-- Not in this backup:', ...header.notIncluded.map((what) => `-- ${what}`)]
1190
+ ? [
1191
+ '--',
1192
+ '-- Not in this backup:',
1193
+ ...header.notIncluded.map((what) => `-- ${inComment(what)}`),
1194
+ ]
1008
1195
  : []),
1009
1196
  '--',
1010
1197
  '',
@@ -1,7 +1,9 @@
1
- import { Readable } from 'node:stream'
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { pipeline, Readable } from 'node:stream'
2
3
  import { createGunzip } from 'node:zlib'
3
4
  import { DbAdminError, QueryError } from '../errors.ts'
4
5
  import type { Session } from '../types.ts'
6
+ import { firstWords } from '../words.ts'
5
7
  import {
6
8
  readHeader,
7
9
  readTrailer,
@@ -30,7 +32,11 @@ export interface RestorePlan {
30
32
  /** PostgreSQL's estimate. */
31
33
  rows: number
32
34
  }[]
33
- /** Objects outside the backup's schemas that depend on what's in them: restoring would drop them. */
35
+ /**
36
+ * What restoring would drop that the backup can't make again: objects outside its schemas that
37
+ * depend on what's in them, and objects in them that it can't hold but that need what it
38
+ * replaces.
39
+ */
34
40
  blocked: string[]
35
41
  /** Roles the backup's owners, grants and policies name that this server lacks: those are skipped. */
36
42
  missingRoles: string[]
@@ -46,8 +52,33 @@ export interface RestoreProgress {
46
52
  /** What a restore put back: the backup's tables and rows, and the statements it ran. */
47
53
  export interface RestoreResult extends BackupSummary {
48
54
  statements: number
55
+ /** The SHA-256 of the file as it was sent, in hex: which file ran, for the audit log. */
56
+ sha256: string
49
57
  }
50
58
 
59
+ /**
60
+ * What a statement of a backup never starts with. All but COPY would end the restore's one
61
+ * transaction, or start another, and what came after would stay whatever failed later; COPY
62
+ * waits for rows the file can't send, or hands them to a program. A backup holds its rows as
63
+ * INSERTs. A file someone edited is refused at the first of these, before it runs.
64
+ */
65
+ const NEVER_IN_A_BACKUP =
66
+ /^(BEGIN|START|COMMIT|END|ROLLBACK|ABORT|SAVEPOINT|RELEASE|PREPARE(?= TRANSACTION\b)|COPY)\b/i
67
+
68
+ /** Refuses a statement that would step out of the restore's transaction. */
69
+ function refuseOutside(n: number, statement: string): void {
70
+ const word = NEVER_IN_A_BACKUP.exec(firstWords(statement))?.[1]
71
+ if (!word) return
72
+ throw new DbAdminError(
73
+ `Statement ${n.toLocaleString('en')} of the backup is ${word.toUpperCase()}, which a backup never holds: a restore is one transaction from its first statement to its last, and its rows are INSERTs. The file was changed after it was made, so nothing was restored.`,
74
+ 400,
75
+ 'bad-backup',
76
+ )
77
+ }
78
+
79
+ /** "canceling statement due to lock timeout": something else holds what a statement needs. */
80
+ export const LOCK_NOT_AVAILABLE = '55P03'
81
+
51
82
  const SERVER_SQL = `SELECT json_build_object('version', current_setting('server_version_num')::int,
52
83
  'server', split_part(version(), ' ', 1) || ' ' || current_setting('server_version'))`
53
84
 
@@ -61,17 +92,47 @@ const SCHEMAS_SQL = `SELECT coalesce(json_agg(json_build_object('schema', s.name
61
92
  FROM unnest($1::text[]) AS s(name) LEFT JOIN pg_namespace n ON n.nspname = s.name`
62
93
 
63
94
  /**
64
- * What outside the schemas depends on what's in them. A column default, a view's rule, a trigger
65
- * or a policy belongs to its table's schema, an operator family's member to the family's; a cast,
66
- * a publication's table or an event trigger to none, so it's outside. The common catalogs are
95
+ * What a restore of the schemas would drop that the backup can't make again. First, what outside
96
+ * the schemas depends on what's in them. A column default, a view's rule, a trigger or a policy
97
+ * belongs to its table's schema, an operator family's member to the family's; a cast, a
98
+ * publication's table or an event trigger to none, so it's outside. The common catalogs are
67
99
  * looked up directly; pg_identify_object, slower, answers for the rest.
100
+ *
101
+ * Then, inside the schemas, what a backup can't hold and a restore leaves where it is (a foreign
102
+ * table, a typed table, a table that inherits another, an aggregate, an operator) but which
103
+ * needs something the restore replaces: dropping that, by CASCADE, would take it too. And a
104
+ * foreign key from a table the restore replaces to one it leaves, which the backup doesn't hold.
68
105
  */
69
106
  const BLOCKED_SQL = `WITH ns AS (SELECT oid FROM pg_namespace WHERE nspname = ANY($1)),
107
+ kept_table AS (
108
+ SELECT c.oid FROM pg_class c WHERE c.relnamespace IN (SELECT oid FROM ns)
109
+ AND (c.relkind = 'f' OR c.reloftype <> 0
110
+ OR (c.relkind IN ('r', 'p') AND NOT c.relispartition
111
+ AND EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhrelid = c.oid))
112
+ OR (c.relispartition AND NOT EXISTS (SELECT 1 FROM pg_inherits i JOIN pg_class pc ON pc.oid = i.inhparent
113
+ WHERE i.inhrelid = c.oid AND pc.relnamespace IN (SELECT oid FROM ns))))),
114
+ -- Those tables, and the sequences their columns own, which stay with them.
115
+ kept_rel AS (
116
+ SELECT oid FROM kept_table
117
+ UNION SELECT s.oid FROM pg_class s JOIN pg_depend o ON o.classid = 'pg_class'::regclass AND o.objid = s.oid
118
+ WHERE s.relkind = 'S' AND o.refclassid = 'pg_class'::regclass AND o.deptype IN ('a', 'i')
119
+ AND o.refobjid IN (SELECT oid FROM kept_table)),
120
+ kept_proc AS (
121
+ SELECT p.oid FROM pg_proc p JOIN pg_language l ON l.oid = p.prolang
122
+ WHERE p.pronamespace IN (SELECT oid FROM ns) AND (p.prokind = 'a' OR l.lanname IN ('c', 'internal'))
123
+ -- Not one made along with something else, as a range type's constructors are: those go
124
+ -- and come back with it.
125
+ AND NOT EXISTS (SELECT 1 FROM pg_depend i WHERE i.classid = 'pg_proc'::regclass AND i.objid = p.oid AND i.deptype = 'i')),
70
126
  inside AS (
71
127
  SELECT 'pg_class'::regclass::oid AS cat, c.oid FROM pg_class c WHERE c.relnamespace IN (SELECT oid FROM ns)
72
128
  UNION ALL SELECT 'pg_type'::regclass::oid, t.oid FROM pg_type t WHERE t.typnamespace IN (SELECT oid FROM ns)
73
129
  UNION ALL SELECT 'pg_proc'::regclass::oid, p.oid FROM pg_proc p WHERE p.pronamespace IN (SELECT oid FROM ns)
74
130
  UNION ALL SELECT 'pg_extension'::regclass::oid, x.oid FROM pg_extension x WHERE x.extnamespace IN (SELECT oid FROM ns)
131
+ -- What those extensions made, wherever it is and of whatever kind: a foreign-data wrapper
132
+ -- has no schema, and a server built on it goes when the extension is dropped.
133
+ UNION SELECT m.classid, m.objid FROM pg_depend m JOIN pg_extension x ON x.oid = m.refobjid
134
+ WHERE m.deptype = 'e' AND m.refclassid = 'pg_extension'::regclass
135
+ AND x.extnamespace IN (SELECT oid FROM ns)
75
136
  ),
76
137
  deps AS (
77
138
  SELECT d.classid, d.objid, d.objsubid, d.refclassid, d.refobjid,
@@ -88,15 +149,57 @@ const BLOCKED_SQL = `WITH ns AS (SELECT oid FROM pg_namespace WHERE nspname = AN
88
149
  WHEN 'pg_amop'::regclass THEN (SELECT f.opfnamespace FROM pg_amop o JOIN pg_opfamily f ON f.oid = o.amopfamily WHERE o.oid = d.objid)
89
150
  WHEN 'pg_amproc'::regclass THEN (SELECT f.opfnamespace FROM pg_amproc o JOIN pg_opfamily f ON f.oid = o.amprocfamily WHERE o.oid = d.objid)
90
151
  ELSE (SELECT n.oid FROM pg_namespace n WHERE n.nspname = (pg_identify_object(d.classid, d.objid, d.objsubid)).schema)
91
- END AS ns
152
+ END AS ns,
153
+ -- The table a dependent is part of: itself, or its index's, default's, rule's, trigger's,
154
+ -- policy's, constraint's or statistics' table.
155
+ CASE d.classid
156
+ WHEN 'pg_class'::regclass THEN coalesce((SELECT x.indrelid FROM pg_index x WHERE x.indexrelid = d.objid), d.objid)
157
+ WHEN 'pg_constraint'::regclass THEN (SELECT nullif(conrelid, 0) FROM pg_constraint WHERE oid = d.objid)
158
+ WHEN 'pg_attrdef'::regclass THEN (SELECT adrelid FROM pg_attrdef WHERE oid = d.objid)
159
+ WHEN 'pg_rewrite'::regclass THEN (SELECT ev_class FROM pg_rewrite WHERE oid = d.objid)
160
+ WHEN 'pg_trigger'::regclass THEN (SELECT tgrelid FROM pg_trigger WHERE oid = d.objid)
161
+ WHEN 'pg_policy'::regclass THEN (SELECT polrelid FROM pg_policy WHERE oid = d.objid)
162
+ WHEN 'pg_statistic_ext'::regclass THEN (SELECT stxrelid FROM pg_statistic_ext WHERE oid = d.objid)
163
+ END AS rel
92
164
  FROM pg_depend d JOIN inside i ON i.cat = d.refclassid AND i.oid = d.refobjid
93
165
  WHERE d.deptype IN ('n', 'a')
94
166
  AND NOT EXISTS (SELECT 1 FROM pg_depend e WHERE e.classid = d.classid AND e.objid = d.objid AND e.deptype = 'e')
167
+ -- Nor a member of an extension's operator family: the family is the extension's, its
168
+ -- members are listed apart.
169
+ AND NOT EXISTS (SELECT 1 FROM pg_depend e WHERE e.classid = 'pg_opfamily'::regclass AND e.deptype = 'e'
170
+ AND e.objid = CASE d.classid
171
+ WHEN 'pg_amop'::regclass THEN (SELECT amopfamily FROM pg_amop WHERE oid = d.objid)
172
+ WHEN 'pg_amproc'::regclass THEN (SELECT amprocfamily FROM pg_amproc WHERE oid = d.objid) END)
173
+ ),
174
+ judged AS (
175
+ SELECT deps.*,
176
+ ns IS NULL OR ns NOT IN (SELECT oid FROM ns) AS outside,
177
+ -- What the restore leaves where it is: part of a table it leaves, an aggregate or a C
178
+ -- function, a C type, or a kind of thing a backup never holds (an operator, a collation…).
179
+ coalesce(rel IN (SELECT oid FROM kept_rel), false)
180
+ OR (classid = 'pg_proc'::regclass AND objid IN (SELECT oid FROM kept_proc))
181
+ OR (classid = 'pg_type'::regclass AND EXISTS (SELECT 1 FROM pg_type t WHERE t.oid = objid
182
+ AND t.typtype = 'b' AND t.typcategory <> 'A'))
183
+ OR classid NOT IN ('pg_class'::regclass, 'pg_type'::regclass, 'pg_proc'::regclass,
184
+ 'pg_constraint'::regclass, 'pg_attrdef'::regclass, 'pg_rewrite'::regclass,
185
+ 'pg_trigger'::regclass, 'pg_policy'::regclass, 'pg_statistic_ext'::regclass) AS kept,
186
+ (refclassid = 'pg_class'::regclass AND refobjid IN (SELECT oid FROM kept_rel))
187
+ OR (refclassid = 'pg_proc'::regclass AND refobjid IN (SELECT oid FROM kept_proc))
188
+ OR (refclassid = 'pg_type'::regclass AND EXISTS (SELECT 1 FROM pg_type t WHERE t.oid = refobjid
189
+ AND (t.typrelid IN (SELECT oid FROM kept_rel) OR (t.typtype = 'b' AND t.typcategory <> 'A')))) AS ref_kept
190
+ FROM deps
95
191
  )
96
192
  SELECT coalesce(json_agg(x.what ORDER BY x.what), '[]') FROM (
97
193
  SELECT DISTINCT pg_describe_object(classid, objid, objsubid) || ' needs '
98
- || pg_describe_object(refclassid, refobjid, 0) AS what
99
- FROM deps WHERE ns IS NULL OR ns NOT IN (SELECT oid FROM ns) LIMIT 50) x`
194
+ || pg_describe_object(refclassid, refobjid, 0)
195
+ || CASE WHEN outside OR kept THEN '' ELSE ', which the backup can’t hold' END AS what
196
+ FROM judged
197
+ WHERE outside OR (kept AND NOT ref_kept)
198
+ OR (NOT kept AND refclassid = 'pg_class'::regclass AND refobjid IN (SELECT oid FROM kept_rel)
199
+ AND classid = 'pg_constraint'::regclass
200
+ AND EXISTS (SELECT 1 FROM pg_constraint co WHERE co.oid = objid AND co.contype = 'f'
201
+ AND co.confrelid = refobjid))
202
+ LIMIT 50) x`
100
203
 
101
204
  const MISSING_ROLES_SQL = `SELECT coalesce(json_agg(r ORDER BY r), '[]') FROM unnest($1::text[]) r
102
205
  WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r)`
@@ -142,7 +245,7 @@ export function refuseBlocked(header: BackupHeader, plan: RestorePlan): void {
142
245
  }
143
246
  if (plan.blocked.length) {
144
247
  throw new DbAdminError(
145
- `Restoring would also drop what's outside the backup's schemas (${header.schemas.join(', ')}):\n${plan.blocked.join('\n')}\nBack up those schemas too, or remove what depends on them, then restore.`,
248
+ `Restoring would also drop what the backup can't hold, or what's outside its schemas (${header.schemas.join(', ')}):\n${plan.blocked.join('\n')}\nBack up those schemas too, or remove what's listed here, then restore.`,
146
249
  409,
147
250
  'restore-blocked',
148
251
  )
@@ -162,9 +265,11 @@ export async function restoreSql(
162
265
  },
163
266
  ): Promise<RestoreResult> {
164
267
  const progress: RestoreProgress = { statements: 0, bytes: 0 }
268
+ const hash = createHash('sha256')
165
269
  const counted = (async function* () {
166
270
  for await (const chunk of bytes) {
167
271
  progress.bytes += chunk.byteLength
272
+ hash.update(chunk)
168
273
  yield chunk
169
274
  }
170
275
  })()
@@ -175,13 +280,29 @@ export async function restoreSql(
175
280
  /** The end of the text so far, for the last line. */
176
281
  let tail = ''
177
282
  let reported = 0
283
+ // A mark only this transaction has: gone once it ends, whatever a new one is called.
284
+ const mark = randomUUID()
285
+ await session.query(`SELECT set_config('otw_db.restore', $1, true)`, [mark])
178
286
  const run = async (statements: string[]) => {
179
287
  for (const statement of statements) {
288
+ refuseOutside(progress.statements + 1, statement)
180
289
  try {
181
290
  await session.query(statement)
182
291
  } catch (error) {
292
+ // A lock it waited too long for isn't the backup's fault: the caller says the database
293
+ // is busy, and keeps the upload for another try.
294
+ if (error instanceof QueryError && error.sqlState === LOCK_NOT_AVAILABLE) throw error
183
295
  throw failed(progress.statements + 1, statement, error)
184
296
  }
297
+ // Behind the check of its words: whatever a statement was, if the transaction is over, it
298
+ // is the last to run. The next would run with nothing to undo it.
299
+ if (session.inTransaction?.() === false) {
300
+ throw new DbAdminError(
301
+ `Statement ${(progress.statements + 1).toLocaleString('en')} of the backup ended the restore’s transaction, which a backup never does: the file was changed after it was made. The restore stopped there, and nothing after that statement ran, but what came before it may have been kept. Look at the database before it’s used, and restore a backup nobody has edited.`,
302
+ 400,
303
+ 'bad-backup',
304
+ )
305
+ }
185
306
  progress.statements += 1
186
307
  const now = performance.now()
187
308
  if (options.onProgress && now - reported > 250) {
@@ -216,7 +337,8 @@ export async function restoreSql(
216
337
  await run(splitter.end())
217
338
  } catch (error) {
218
339
  if (error instanceof DbAdminError) throw error
219
- if (error instanceof TypeError && /encoded data|invalid/i.test(error.message)) {
340
+ // The decoder's own refusal, by its code: other TypeErrors aren't about the file's bytes.
341
+ if ((error as { code?: string }).code === 'ERR_ENCODING_INVALID_ENCODED_DATA') {
220
342
  throw new DbAdminError(
221
343
  "The backup isn't valid UTF-8 text: it may be damaged.",
222
344
  400,
@@ -236,8 +358,18 @@ export async function restoreSql(
236
358
  'incomplete-backup',
237
359
  )
238
360
  }
361
+ // The transaction about to be committed must be the one this began: COMMIT AND CHAIN leaves
362
+ // another open in its place, which the server reports no differently.
363
+ const { rows } = await session.query(`SELECT current_setting('otw_db.restore', true)`)
364
+ if (rows[0]?.[0] !== mark) {
365
+ throw new DbAdminError(
366
+ 'The backup left the restore’s transaction for another, which a backup never does: the file was changed after it was made. What came after that was undone, but what came before it may have been kept. Look at the database before it’s used, and restore a backup nobody has edited.',
367
+ 400,
368
+ 'bad-backup',
369
+ )
370
+ }
239
371
  options.onProgress?.({ ...progress })
240
- return { ...summary, statements: progress.statements }
372
+ return { ...summary, statements: progress.statements, sha256: hash.digest('hex') }
241
373
  }
242
374
 
243
375
  /** The bytes as they come, unzipped when they start as gzip does. */
@@ -250,7 +382,15 @@ async function text(bytes: AsyncIterator<Uint8Array> & AsyncIterable<Uint8Array>
250
382
  yield* { [Symbol.asyncIterator]: () => bytes }
251
383
  })()
252
384
  if (head[0] !== 0x1f || head[1] !== 0x8b) return all
253
- return Readable.from(all).pipe(createGunzip()) as AsyncIterable<Uint8Array>
385
+ // pipeline(), not pipe(): pipe() leaves the source's failure (a piece missing, a connection
386
+ // gone) as an 'error' event nobody hears, which ends the process, while whoever reads the text
387
+ // waits for good. pipeline() hands it to the reader, and stops reading pieces when the reader
388
+ // stops. Bytes, one piece ahead at most: a piece is 4 MB, and sixteen would wait otherwise.
389
+ const gunzip = createGunzip()
390
+ pipeline(Readable.from(all, { objectMode: false, highWaterMark: 1 }), gunzip, () => {
391
+ // The failure reaches the reader through gunzip, which pipeline() destroys with it.
392
+ })
393
+ return gunzip as AsyncIterable<Uint8Array>
254
394
  }
255
395
 
256
396
  /** A statement's failure, saying which and where. */