@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,381 @@
1
+ import { STAGING_SCHEMA } from './format.ts'
2
+
3
+ /*
4
+ * The catalog queries a backup is written from. Each returns one JSON value (where an OID comes
5
+ * back as a string: compare them as such, and say what's true of one as a boolean); $1 is always the
6
+ * schemas backed up, as text[] (SCHEMAS_SQL and SERVER_SQL take none). They run with search_path empty, so every name the server prints
7
+ * (in a default, a view, a function's signature) comes schema-qualified, as pg_dump has it.
8
+ *
9
+ * Objects that belong to an extension are left out: CREATE EXTENSION makes them again.
10
+ */
11
+
12
+ /** The catalogs' OIDs, the same in every PostgreSQL. */
13
+ export const PG_TYPE = 1247
14
+ export const PG_PROC = 1255
15
+ export const PG_CLASS = 1259
16
+ export const PG_ATTRDEF = 2604
17
+ export const PG_CONSTRAINT = 2606
18
+ export const PG_NAMESPACE = 2615
19
+ export const PG_REWRITE = 2618
20
+ export const PG_EXTENSION = 3079
21
+
22
+ const notMember = (catalog: number, oid: string) =>
23
+ `NOT EXISTS (SELECT 1 FROM pg_depend e WHERE e.classid = ${catalog} AND e.objid = ${oid} AND e.deptype = 'e')`
24
+
25
+ /** Not made along with something else, as a range type's constructors and cast are. */
26
+ const notInternal = (catalog: number, oid: string) =>
27
+ `NOT EXISTS (SELECT 1 FROM pg_depend i WHERE i.classid = ${catalog} AND i.objid = ${oid} AND i.deptype = 'i')`
28
+
29
+ /**
30
+ * An object's privileges as the grants and revokes that turn a new object's into them: what its
31
+ * ACL has that the default for its owner hasn't, and the reverse. Null when it has the default.
32
+ * `kind` is acldefault's letter: r relation, s sequence, f function, T type, n schema, c column.
33
+ */
34
+ function acl(column: string, kind: string, owner: string): string {
35
+ const explode = (value: string) =>
36
+ `SELECT grantee, privilege_type, is_grantable FROM aclexplode(${value})`
37
+ const actual = explode(column)
38
+ const fresh = explode(`acldefault('${kind}', ${owner})`)
39
+ const list = (from: string, minus: string) => `(SELECT coalesce(json_agg(json_build_object(
40
+ 'role', CASE WHEN g.grantee = 0 THEN NULL ELSE pg_get_userbyid(g.grantee) END,
41
+ 'privilege', g.privilege_type, 'grantable', g.is_grantable) ORDER BY g.grantee, g.privilege_type), '[]')
42
+ FROM (${from} EXCEPT ${minus}) g)`
43
+ return `CASE WHEN ${column} IS NULL THEN NULL ELSE json_build_object(
44
+ 'grant', ${list(actual, fresh)}, 'revoke', ${list(fresh, actual)}) END`
45
+ }
46
+
47
+ /** A collation that isn't the type's own, as a qualified name, else null. */
48
+ const collation = (coll: string, type: string) => `CASE WHEN ${coll} <> 0
49
+ AND ${coll} <> (SELECT ty.typcollation FROM pg_type ty WHERE ty.oid = ${type})
50
+ THEN (SELECT quote_ident(cn.nspname) || '.' || quote_ident(co.collname) FROM pg_collation co
51
+ JOIN pg_namespace cn ON cn.oid = co.collnamespace WHERE co.oid = ${coll}) END`
52
+
53
+ const inSchemas = (namespace: string) =>
54
+ `${namespace} IN (SELECT oid FROM pg_namespace WHERE nspname = ANY($1))`
55
+
56
+ /** The session's settings: names printed qualified, values printed so they read back the same. */
57
+ export const SESSION_SQL = [
58
+ `SELECT set_config('search_path', '', true)`,
59
+ `SET LOCAL bytea_output = 'hex'`,
60
+ `SET LOCAL extra_float_digits = 3`,
61
+ `SET LOCAL datestyle = 'ISO, YMD'`,
62
+ `SET LOCAL intervalstyle = 'postgres'`,
63
+ `SET LOCAL TimeZone = 'UTC'`,
64
+ // A table's rows filtered by row-level security would make a backup quietly incomplete: with
65
+ // this off, reading such a table fails instead.
66
+ `SET LOCAL row_security = off`,
67
+ ]
68
+
69
+ export const SERVER_SQL = `SELECT json_build_object(
70
+ 'version', current_setting('server_version_num')::int, 'server', split_part(version(), ' ', 1)
71
+ || ' ' || current_setting('server_version'), 'database', current_database(), 'user', current_user)`
72
+
73
+ /** Every schema a backup could hold, with what's in it; takes no parameters. */
74
+ export const SCHEMAS_SQL = `SELECT coalesce(json_agg(json_build_object(
75
+ 'name', n.nspname, 'owner', pg_get_userbyid(n.nspowner),
76
+ 'mine', pg_has_role(n.nspowner, 'USAGE'),
77
+ 'tables', (SELECT count(*) FROM pg_class c WHERE c.relnamespace = n.oid
78
+ AND c.relkind IN ('r','p') AND NOT c.relispartition AND ${notMember(PG_CLASS, 'c.oid')}),
79
+ 'objects', (SELECT count(*) FROM pg_class c WHERE c.relnamespace = n.oid
80
+ AND c.relkind IN ('r','p','v','m','S','f') AND ${notMember(PG_CLASS, 'c.oid')})
81
+ + (SELECT count(*) FROM pg_proc p WHERE p.pronamespace = n.oid AND ${notMember(PG_PROC, 'p.oid')})
82
+ + (SELECT count(*) FROM pg_type t WHERE t.typnamespace = n.oid AND t.typtype IN ('e','d','r')
83
+ AND ${notMember(PG_TYPE, 't.oid')}),
84
+ 'extensions', (SELECT count(*) FROM pg_extension x WHERE x.extnamespace = n.oid))
85
+ ORDER BY n.nspname), '[]')
86
+ FROM pg_namespace n
87
+ WHERE n.nspname <> 'information_schema' AND n.nspname NOT LIKE 'pg\\_%' AND n.nspname <> '${STAGING_SCHEMA}'
88
+ AND ${notMember(PG_NAMESPACE, 'n.oid')}`
89
+
90
+ /** The name of the schema with OID `namespace`. */
91
+ const schemaOf = (namespace: string) =>
92
+ `(SELECT nspname FROM pg_namespace WHERE oid = ${namespace})`
93
+
94
+ /**
95
+ * What the backup can't hold, in the schemas it backs up, and what's database-wide (schema null):
96
+ * described as the server describes them, such as `aggregate public.median(numeric)`.
97
+ */
98
+ export const NOT_INCLUDED_SQL = `SELECT coalesce(json_agg(json_build_object('schema', x.schema, 'what', x.what)
99
+ ORDER BY x.schema NULLS FIRST, x.what), '[]') FROM (
100
+ SELECT ${schemaOf('p.pronamespace')} AS schema, pg_describe_object(${PG_PROC}, p.oid, 0) AS what
101
+ FROM pg_proc p JOIN pg_language l ON l.oid = p.prolang
102
+ WHERE ${inSchemas('p.pronamespace')} AND (p.prokind = 'a' OR l.lanname IN ('c', 'internal'))
103
+ AND ${notMember(PG_PROC, 'p.oid')} AND ${notInternal(PG_PROC, 'p.oid')}
104
+ UNION ALL SELECT ${schemaOf('t.typnamespace')}, pg_describe_object(${PG_TYPE}, t.oid, 0) FROM pg_type t
105
+ WHERE ${inSchemas('t.typnamespace')} AND t.typtype = 'b' AND t.typcategory <> 'A'
106
+ AND ${notMember(PG_TYPE, 't.oid')}
107
+ UNION ALL SELECT ${schemaOf('t.typnamespace')}, pg_describe_object(${PG_TYPE}, t.oid, 0) || ' (it has a canonical function)'
108
+ FROM pg_type t JOIN pg_range r ON r.rngtypid = t.oid
109
+ WHERE ${inSchemas('t.typnamespace')} AND r.rngcanonical <> 0 AND ${notMember(PG_TYPE, 't.oid')}
110
+ UNION ALL SELECT ${schemaOf('o.collnamespace')}, pg_describe_object('pg_collation'::regclass, o.oid, 0) FROM pg_collation o
111
+ WHERE ${inSchemas('o.collnamespace')} AND ${notMember(3456, 'o.oid')}
112
+ UNION ALL SELECT ${schemaOf('o.oprnamespace')}, pg_describe_object('pg_operator'::regclass, o.oid, 0) FROM pg_operator o
113
+ WHERE ${inSchemas('o.oprnamespace')} AND ${notMember(2617, 'o.oid')}
114
+ UNION ALL SELECT ${schemaOf('o.opfnamespace')}, pg_describe_object('pg_opfamily'::regclass, o.oid, 0) FROM pg_opfamily o
115
+ WHERE ${inSchemas('o.opfnamespace')} AND ${notMember(2753, 'o.oid')}
116
+ UNION ALL SELECT ${schemaOf('o.cfgnamespace')}, pg_describe_object('pg_ts_config'::regclass, o.oid, 0) FROM pg_ts_config o
117
+ WHERE ${inSchemas('o.cfgnamespace')} AND ${notMember(3602, 'o.oid')}
118
+ UNION ALL SELECT ${schemaOf('o.dictnamespace')}, pg_describe_object('pg_ts_dict'::regclass, o.oid, 0) FROM pg_ts_dict o
119
+ WHERE ${inSchemas('o.dictnamespace')} AND ${notMember(3600, 'o.oid')}
120
+ UNION ALL SELECT ${schemaOf('o.connamespace')}, pg_describe_object('pg_conversion'::regclass, o.oid, 0) FROM pg_conversion o
121
+ WHERE ${inSchemas('o.connamespace')} AND ${notMember(2607, 'o.oid')}
122
+ UNION ALL SELECT ${schemaOf('c.relnamespace')}, pg_describe_object(${PG_CLASS}, c.oid, 0) FROM pg_class c
123
+ WHERE ${inSchemas('c.relnamespace')} AND ${notMember(PG_CLASS, 'c.oid')}
124
+ AND (c.relkind = 'f' OR c.reloftype <> 0
125
+ OR (c.relkind IN ('r','p') AND NOT c.relispartition
126
+ AND EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhrelid = c.oid))
127
+ OR (c.relispartition AND NOT EXISTS (SELECT 1 FROM pg_inherits i JOIN pg_class pc ON pc.oid = i.inhparent
128
+ WHERE i.inhrelid = c.oid AND ${inSchemas('pc.relnamespace')})))
129
+ UNION ALL SELECT NULL, pg_describe_object('pg_cast'::regclass, k.oid, 0) FROM pg_cast k
130
+ WHERE k.oid >= 16384 AND ${notMember(2605, 'k.oid')} AND ${notInternal(2605, 'k.oid')}
131
+ UNION ALL SELECT NULL, pg_describe_object('pg_event_trigger'::regclass, v.oid, 0) FROM pg_event_trigger v
132
+ WHERE ${notMember(3466, 'v.oid')}
133
+ UNION ALL SELECT NULL, pg_describe_object('pg_publication'::regclass, b.oid, 0) FROM pg_publication b
134
+ UNION ALL SELECT NULL, pg_describe_object('pg_foreign_server'::regclass, f.oid, 0) FROM pg_foreign_server f
135
+ WHERE ${notMember(1417, 'f.oid')}
136
+ UNION ALL SELECT NULL, count(*) || ' large objects' FROM pg_largeobject_metadata HAVING count(*) > 0
137
+ ) x`
138
+
139
+ export const SCHEMA_DETAILS_SQL = `SELECT coalesce(json_agg(json_build_object(
140
+ 'name', n.nspname, 'owner', pg_get_userbyid(n.nspowner),
141
+ 'comment', obj_description(n.oid, 'pg_namespace'), 'acl', ${acl('n.nspacl', 'n', 'n.nspowner')},
142
+ 'defaults', (SELECT coalesce(json_agg(json_build_object('role', pg_get_userbyid(d.defaclrole),
143
+ 'type', d.defaclobjtype, 'grants', (SELECT coalesce(json_agg(json_build_object(
144
+ 'role', CASE WHEN g.grantee = 0 THEN NULL ELSE pg_get_userbyid(g.grantee) END,
145
+ 'privilege', g.privilege_type, 'grantable', g.is_grantable)), '[]') FROM aclexplode(d.defaclacl) g))), '[]')
146
+ FROM pg_default_acl d WHERE d.defaclnamespace = n.oid))
147
+ ORDER BY n.nspname), '[]')
148
+ FROM pg_namespace n WHERE n.nspname = ANY($1)`
149
+
150
+ /** The extensions besides plpgsql, each with its schema; the backup keeps the ones it needs. */
151
+ export const EXTENSIONS_SQL = `SELECT coalesce(json_agg(json_build_object('oid', x.oid, 'name', x.extname,
152
+ 'schema', n.nspname) ORDER BY x.extname), '[]')
153
+ FROM pg_extension x JOIN pg_namespace n ON n.oid = x.extnamespace WHERE x.extname <> 'plpgsql'`
154
+
155
+ /**
156
+ * The extensions something in the schemas needs: a column of citext, a default calling
157
+ * uuid_generate_v4(), an index with pg_trgm's operator class.
158
+ */
159
+ export const NEEDED_EXTENSIONS_SQL = `SELECT coalesce(json_agg(DISTINCT m.refobjid), '[]')
160
+ FROM pg_depend d
161
+ JOIN pg_depend m ON m.classid = d.refclassid AND m.objid = d.refobjid AND m.deptype = 'e'
162
+ AND m.refclassid = ${PG_EXTENSION}
163
+ WHERE d.deptype IN ('n', 'a') AND d.classid IN (${PG_CLASS}, ${PG_TYPE}, ${PG_PROC}, ${PG_ATTRDEF}, ${PG_CONSTRAINT}, ${PG_REWRITE})
164
+ AND NOT EXISTS (SELECT 1 FROM pg_depend e WHERE e.classid = d.classid AND e.objid = d.objid AND e.deptype = 'e')
165
+ AND CASE d.classid
166
+ WHEN ${PG_CLASS} THEN (SELECT relnamespace FROM pg_class WHERE oid = d.objid)
167
+ WHEN ${PG_TYPE} THEN (SELECT typnamespace FROM pg_type WHERE oid = d.objid)
168
+ WHEN ${PG_PROC} THEN (SELECT pronamespace FROM pg_proc WHERE oid = d.objid)
169
+ WHEN ${PG_ATTRDEF} THEN (SELECT c.relnamespace FROM pg_attrdef a JOIN pg_class c ON c.oid = a.adrelid WHERE a.oid = d.objid)
170
+ WHEN ${PG_CONSTRAINT} THEN (SELECT connamespace FROM pg_constraint WHERE oid = d.objid)
171
+ WHEN ${PG_REWRITE} THEN (SELECT c.relnamespace FROM pg_rewrite r JOIN pg_class c ON c.oid = r.ev_class WHERE r.oid = d.objid)
172
+ END IN (SELECT oid FROM pg_namespace WHERE nspname = ANY($1))`
173
+
174
+ export const TYPES_SQL = `SELECT coalesce(json_agg(json_build_object(
175
+ 'oid', t.oid, 'schema', n.nspname, 'name', t.typname, 'kind', t.typtype,
176
+ 'owner', pg_get_userbyid(t.typowner), 'comment', obj_description(t.oid, 'pg_type'),
177
+ 'acl', ${acl('t.typacl', 'T', 't.typowner')},
178
+ 'labels', CASE WHEN t.typtype = 'e' THEN (SELECT json_agg(v.enumlabel ORDER BY v.enumsortorder)
179
+ FROM pg_enum v WHERE v.enumtypid = t.oid) END,
180
+ 'attributes', CASE WHEN t.typtype = 'c' THEN (SELECT json_agg(json_build_object('name', a.attname,
181
+ 'type', format_type(a.atttypid, a.atttypmod), 'collation', ${collation('a.attcollation', 'a.atttypid')},
182
+ 'comment', col_description(a.attrelid, a.attnum)) ORDER BY a.attnum)
183
+ FROM pg_attribute a WHERE a.attrelid = t.typrelid AND a.attnum > 0 AND NOT a.attisdropped) END,
184
+ 'base', CASE WHEN t.typtype = 'd' THEN format_type(t.typbasetype, t.typtypmod) END,
185
+ 'notNull', t.typnotnull,
186
+ 'default', CASE WHEN t.typtype = 'd' THEN coalesce(pg_get_expr(t.typdefaultbin, 0), t.typdefault) END,
187
+ 'collation', CASE WHEN t.typtype = 'd' THEN ${collation('t.typcollation', 't.typbasetype')} END,
188
+ 'checks', CASE WHEN t.typtype = 'd' THEN (SELECT json_agg(json_build_object('name', c.conname,
189
+ 'def', pg_get_constraintdef(c.oid), 'comment', obj_description(c.oid, 'pg_constraint')) ORDER BY c.conname)
190
+ FROM pg_constraint c WHERE c.contypid = t.oid AND c.contype = 'c') END,
191
+ 'range', CASE WHEN t.typtype = 'r' THEN (SELECT json_build_object(
192
+ 'subtype', format_type(r.rngsubtype, NULL),
193
+ 'opclass', CASE WHEN NOT oc.opcdefault THEN quote_ident(ocn.nspname) || '.' || quote_ident(oc.opcname) END,
194
+ 'collation', ${collation('r.rngcollation', 'r.rngsubtype')},
195
+ 'diff', CASE WHEN r.rngsubdiff <> 0 THEN r.rngsubdiff::regproc::text END,
196
+ 'multirange', (SELECT quote_ident(mn.nspname) || '.' || quote_ident(mt.typname) FROM pg_type mt
197
+ JOIN pg_namespace mn ON mn.oid = mt.typnamespace WHERE mt.oid = r.rngmultitypid))
198
+ FROM pg_range r JOIN pg_opclass oc ON oc.oid = r.rngsubopc JOIN pg_namespace ocn ON ocn.oid = oc.opcnamespace
199
+ WHERE r.rngtypid = t.oid AND r.rngcanonical = 0) END)
200
+ ORDER BY n.nspname, t.typname), '[]')
201
+ FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace
202
+ WHERE n.nspname = ANY($1) AND ${notMember(PG_TYPE, 't.oid')}
203
+ AND (t.typtype IN ('e', 'd')
204
+ OR (t.typtype = 'r' AND NOT EXISTS (SELECT 1 FROM pg_range r WHERE r.rngtypid = t.oid AND r.rngcanonical <> 0))
205
+ OR (t.typtype = 'c' AND (SELECT relkind FROM pg_class WHERE oid = t.typrelid) = 'c'))`
206
+
207
+ export const FUNCTIONS_SQL = `SELECT coalesce(json_agg(json_build_object(
208
+ 'oid', p.oid, 'schema', n.nspname, 'name', p.proname, 'kind', p.prokind,
209
+ 'signature', p.oid::regprocedure::text, 'def', pg_get_functiondef(p.oid),
210
+ 'owner', pg_get_userbyid(p.proowner), 'comment', obj_description(p.oid, 'pg_proc'),
211
+ 'acl', ${acl('p.proacl', 'f', 'p.proowner')})
212
+ ORDER BY n.nspname, p.proname, p.oid::regprocedure::text), '[]')
213
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace JOIN pg_language l ON l.oid = p.prolang
214
+ WHERE n.nspname = ANY($1) AND p.prokind IN ('f', 'p', 'w') AND l.lanname NOT IN ('c', 'internal')
215
+ AND ${notMember(PG_PROC, 'p.oid')}`
216
+
217
+ /** A sequence's settings, for CREATE SEQUENCE or an identity column's options. */
218
+ const sequenceSettings = (c: string, s: string) => `json_build_object(
219
+ 'name', quote_ident(sn.nspname) || '.' || quote_ident(${c}.relname),
220
+ 'type', format_type(${s}.seqtypid, NULL), 'start', ${s}.seqstart::text,
221
+ 'increment', ${s}.seqincrement::text, 'min', ${s}.seqmin::text, 'max', ${s}.seqmax::text,
222
+ 'cache', ${s}.seqcache::text, 'cycle', ${s}.seqcycle,
223
+ 'last', (SELECT ps.last_value::text FROM pg_sequences ps WHERE ps.schemaname = sn.nspname
224
+ AND ps.sequencename = ${c}.relname))`
225
+
226
+ /** Sequences of their own; an identity column's comes with its table. */
227
+ export const SEQUENCES_SQL = `SELECT coalesce(json_agg(json_build_object(
228
+ 'oid', c.oid, 'schema', sn.nspname, 'name', c.relname, 'settings', ${sequenceSettings('c', 's')},
229
+ 'unlogged', c.relpersistence = 'u', 'owner', pg_get_userbyid(c.relowner),
230
+ 'comment', obj_description(c.oid, 'pg_class'), 'acl', ${acl('c.relacl', 's', 'c.relowner')},
231
+ 'ownedBy', (SELECT json_build_object('table', d.refobjid, 'column', a.attname) FROM pg_depend d
232
+ JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid
233
+ WHERE d.classid = ${PG_CLASS} AND d.objid = c.oid AND d.refclassid = ${PG_CLASS} AND d.deptype = 'a' LIMIT 1))
234
+ ORDER BY sn.nspname, c.relname), '[]')
235
+ FROM pg_class c JOIN pg_sequence s ON s.seqrelid = c.oid JOIN pg_namespace sn ON sn.oid = c.relnamespace
236
+ WHERE c.relkind = 'S' AND sn.nspname = ANY($1) AND ${notMember(PG_CLASS, 'c.oid')}
237
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = ${PG_CLASS} AND d.objid = c.oid AND d.deptype = 'i')`
238
+
239
+ /** A relation's columns: types, defaults, identity and generation, collations, comments, grants. */
240
+ const columns = (c: string) => `(SELECT coalesce(json_agg(json_build_object(
241
+ 'name', a.attname, 'type', format_type(a.atttypid, a.atttypmod), 'notNull', a.attnotnull,
242
+ 'default', CASE WHEN a.attgenerated = '' THEN pg_get_expr(d.adbin, d.adrelid) END,
243
+ 'generated', CASE WHEN a.attgenerated <> '' THEN json_build_object('kind', a.attgenerated,
244
+ 'expr', pg_get_expr(d.adbin, d.adrelid)) END,
245
+ 'identity', CASE WHEN a.attidentity <> '' THEN (SELECT json_build_object('kind', a.attidentity,
246
+ 'sequence', ${sequenceSettings('sc', 's')})
247
+ FROM pg_depend sd JOIN pg_class sc ON sc.oid = sd.objid JOIN pg_sequence s ON s.seqrelid = sc.oid
248
+ JOIN pg_namespace sn ON sn.oid = sc.relnamespace
249
+ WHERE sd.classid = ${PG_CLASS} AND sd.refclassid = ${PG_CLASS} AND sd.refobjid = a.attrelid
250
+ AND sd.refobjsubid = a.attnum AND sd.deptype = 'i' LIMIT 1) END,
251
+ 'collation', ${collation('a.attcollation', 'a.atttypid')}, 'local', a.attislocal,
252
+ 'comment', col_description(a.attrelid, a.attnum), 'acl', ${acl('a.attacl', 'c', `${c}.relowner`)})
253
+ ORDER BY a.attnum), '[]')
254
+ FROM pg_attribute a LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
255
+ WHERE a.attrelid = ${c}.oid AND a.attnum > 0 AND NOT a.attisdropped)`
256
+
257
+ export const TABLES_SQL = `SELECT coalesce(json_agg(json_build_object(
258
+ 'oid', c.oid, 'schema', n.nspname, 'name', c.relname, 'kind', c.relkind,
259
+ 'unlogged', c.relpersistence = 'u',
260
+ 'parent', (SELECT i.inhparent FROM pg_inherits i WHERE i.inhrelid = c.oid AND c.relispartition),
261
+ 'bound', CASE WHEN c.relispartition THEN pg_get_expr(c.relpartbound, c.oid) END,
262
+ 'partitionKey', CASE WHEN c.relkind = 'p' THEN pg_get_partkeydef(c.oid) END,
263
+ 'options', c.reloptions, 'rls', c.relrowsecurity, 'forceRls', c.relforcerowsecurity,
264
+ 'replicaIdentity', c.relreplident,
265
+ 'replicaIndex', (SELECT ic.relname FROM pg_index x JOIN pg_class ic ON ic.oid = x.indexrelid
266
+ WHERE x.indrelid = c.oid AND x.indisreplident),
267
+ 'owner', pg_get_userbyid(c.relowner), 'comment', obj_description(c.oid, 'pg_class'),
268
+ 'acl', ${acl('c.relacl', 'r', 'c.relowner')}, 'columns', ${columns('c')},
269
+ 'checks', (SELECT coalesce(json_agg(json_build_object('name', co.conname, 'def', pg_get_constraintdef(co.oid),
270
+ 'valid', co.convalidated, 'comment', obj_description(co.oid, 'pg_constraint')) ORDER BY co.conname), '[]')
271
+ FROM pg_constraint co WHERE co.conrelid = c.oid AND co.contype = 'c' AND co.conislocal),
272
+ 'notNulls', (SELECT coalesce(json_agg(json_build_object('name', co.conname, 'column', a.attname,
273
+ 'def', pg_get_constraintdef(co.oid), 'valid', co.convalidated, 'local', co.conislocal,
274
+ 'noInherit', co.connoinherit, 'comment', obj_description(co.oid, 'pg_constraint'))), '[]')
275
+ FROM pg_constraint co JOIN pg_attribute a ON a.attrelid = co.conrelid AND a.attnum = co.conkey[1]
276
+ WHERE co.conrelid = c.oid AND co.contype = 'n'))
277
+ ORDER BY n.nspname, c.relname), '[]')
278
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
279
+ WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1) AND ${notMember(PG_CLASS, 'c.oid')}
280
+ AND c.reloftype = 0
281
+ AND (c.relispartition OR NOT EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhrelid = c.oid))
282
+ AND (NOT c.relispartition OR EXISTS (SELECT 1 FROM pg_inherits i JOIN pg_class pc ON pc.oid = i.inhparent
283
+ WHERE i.inhrelid = c.oid AND ${inSchemas('pc.relnamespace')}))`
284
+
285
+ export const VIEWS_SQL = `SELECT coalesce(json_agg(json_build_object(
286
+ 'oid', c.oid, 'schema', n.nspname, 'name', c.relname, 'kind', c.relkind,
287
+ 'def', pg_get_viewdef(c.oid), 'options', c.reloptions, 'populated', c.relispopulated,
288
+ 'owner', pg_get_userbyid(c.relowner), 'comment', obj_description(c.oid, 'pg_class'),
289
+ 'acl', ${acl('c.relacl', 'r', 'c.relowner')}, 'columns', ${columns('c')})
290
+ ORDER BY n.nspname, c.relname), '[]')
291
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
292
+ WHERE c.relkind IN ('v', 'm') AND n.nspname = ANY($1) AND ${notMember(PG_CLASS, 'c.oid')}`
293
+
294
+ /** Primary keys, unique and exclusion constraints, and foreign keys. */
295
+ export const CONSTRAINTS_SQL = `SELECT coalesce(json_agg(json_build_object(
296
+ 'oid', co.oid, 'name', co.conname, 'type', co.contype, 'table', co.conrelid,
297
+ 'def', pg_get_constraintdef(co.oid), 'inherited', co.conparentid <> 0,
298
+ 'partitioned', c.relkind = 'p', 'comment', obj_description(co.oid, 'pg_constraint'))
299
+ ORDER BY n.nspname, c.relname, co.conname), '[]')
300
+ FROM pg_constraint co JOIN pg_class c ON c.oid = co.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
301
+ WHERE co.contype IN ('p', 'u', 'x', 'f') AND n.nspname = ANY($1) AND c.relkind IN ('r', 'p')
302
+ AND ${notMember(PG_CLASS, 'c.oid')}`
303
+
304
+ export const INDEXES_SQL = `SELECT coalesce(json_agg(json_build_object(
305
+ 'oid', x.indexrelid, 'schema', n.nspname, 'name', ic.relname, 'table', x.indrelid,
306
+ 'def', pg_get_indexdef(x.indexrelid), 'clustered', x.indisclustered,
307
+ 'parent', (SELECT i.inhparent FROM pg_inherits i WHERE i.inhrelid = x.indexrelid),
308
+ 'constraint', EXISTS (SELECT 1 FROM pg_constraint co WHERE co.conindid = x.indexrelid
309
+ AND co.conrelid = x.indrelid AND co.contype IN ('p', 'u', 'x')),
310
+ 'comment', obj_description(x.indexrelid, 'pg_class'))
311
+ ORDER BY n.nspname, ic.relname), '[]')
312
+ FROM pg_index x JOIN pg_class ic ON ic.oid = x.indexrelid JOIN pg_class tc ON tc.oid = x.indrelid
313
+ JOIN pg_namespace n ON n.oid = tc.relnamespace
314
+ WHERE n.nspname = ANY($1) AND tc.relkind IN ('r', 'p', 'm') AND ${notMember(PG_CLASS, 'tc.oid')}`
315
+
316
+ export const TRIGGERS_SQL = `SELECT coalesce(json_agg(json_build_object(
317
+ 'name', t.tgname, 'table', t.tgrelid, 'def', pg_get_triggerdef(t.oid), 'enabled', t.tgenabled,
318
+ 'comment', obj_description(t.oid, 'pg_trigger'))
319
+ ORDER BY n.nspname, c.relname, t.tgname), '[]')
320
+ FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_namespace n ON n.oid = c.relnamespace
321
+ WHERE NOT t.tgisinternal AND t.tgparentid = 0 AND n.nspname = ANY($1)
322
+ AND ${notMember(PG_CLASS, 'c.oid')}`
323
+
324
+ /** Rules besides a view's own. */
325
+ export const RULES_SQL = `SELECT coalesce(json_agg(json_build_object('name', r.rulename, 'table', r.ev_class,
326
+ 'def', pg_get_ruledef(r.oid), 'comment', obj_description(r.oid, 'pg_rewrite'))
327
+ ORDER BY n.nspname, c.relname, r.rulename), '[]')
328
+ FROM pg_rewrite r JOIN pg_class c ON c.oid = r.ev_class JOIN pg_namespace n ON n.oid = c.relnamespace
329
+ WHERE r.rulename <> '_RETURN' AND n.nspname = ANY($1) AND ${notMember(PG_CLASS, 'c.oid')}`
330
+
331
+ export const POLICIES_SQL = `SELECT coalesce(json_agg(json_build_object(
332
+ 'name', p.polname, 'table', p.polrelid, 'command', p.polcmd, 'permissive', p.polpermissive,
333
+ 'roles', (SELECT json_agg(CASE WHEN r = 0 THEN NULL ELSE pg_get_userbyid(r) END) FROM unnest(p.polroles) r),
334
+ 'using', pg_get_expr(p.polqual, p.polrelid), 'check', pg_get_expr(p.polwithcheck, p.polrelid),
335
+ 'comment', obj_description(p.oid, 'pg_policy'))
336
+ ORDER BY n.nspname, c.relname, p.polname), '[]')
337
+ FROM pg_policy p JOIN pg_class c ON c.oid = p.polrelid JOIN pg_namespace n ON n.oid = c.relnamespace
338
+ WHERE n.nspname = ANY($1)`
339
+
340
+ export const STATISTICS_SQL = `SELECT coalesce(json_agg(json_build_object(
341
+ 'name', quote_ident(n.nspname) || '.' || quote_ident(s.stxname),
342
+ 'def', pg_get_statisticsobjdef(s.oid), 'comment', obj_description(s.oid, 'pg_statistic_ext'))
343
+ ORDER BY n.nspname, s.stxname), '[]')
344
+ FROM pg_statistic_ext s JOIN pg_namespace n ON n.oid = s.stxnamespace WHERE n.nspname = ANY($1)`
345
+
346
+ /**
347
+ * What depends on what, among the objects a backup creates before its data: [catalog, oid,
348
+ * referenced catalog, referenced oid, how], with column defaults, a view's rule and check
349
+ * constraints standing for their table, view or domain, and a row type for its relation.
350
+ */
351
+ export const DEPENDENCIES_SQL = `SELECT coalesce(json_agg(json_build_array(x.cat, x.oid, x.refcat, x.refoid, x.how)), '[]')
352
+ FROM (
353
+ SELECT DISTINCT
354
+ CASE WHEN d.classid IN (${PG_ATTRDEF}, ${PG_REWRITE}) THEN ${PG_CLASS}
355
+ WHEN d.classid = ${PG_CONSTRAINT} THEN CASE WHEN co.contypid <> 0 THEN ${PG_TYPE} ELSE ${PG_CLASS} END
356
+ WHEN d.classid = ${PG_CLASS} AND cc.relkind = 'c' THEN ${PG_TYPE}
357
+ ELSE d.classid::int END AS cat,
358
+ CASE WHEN d.classid = ${PG_ATTRDEF} THEN ad.adrelid
359
+ WHEN d.classid = ${PG_REWRITE} THEN rw.ev_class
360
+ WHEN d.classid = ${PG_CONSTRAINT} THEN CASE WHEN co.contypid <> 0 THEN co.contypid ELSE co.conrelid END
361
+ WHEN d.classid = ${PG_CLASS} AND cc.relkind = 'c' THEN cc.reltype
362
+ ELSE d.objid END AS oid,
363
+ CASE WHEN d.refclassid = ${PG_TYPE} AND rc.relkind IS NOT NULL AND rc.relkind <> 'c' THEN ${PG_CLASS}
364
+ ELSE d.refclassid::int END AS refcat,
365
+ CASE WHEN d.refclassid = ${PG_TYPE} AND rc.relkind IS NOT NULL AND rc.relkind <> 'c' THEN rc.oid
366
+ WHEN d.refclassid = ${PG_TYPE} AND rt.typcategory = 'A' AND rt.typelem <> 0 THEN rt.typelem
367
+ ELSE d.refobjid END AS refoid,
368
+ CASE WHEN d.classid = ${PG_ATTRDEF} AND att.attgenerated = '' THEN 'default' ELSE 'hard' END AS how
369
+ FROM pg_depend d
370
+ LEFT JOIN pg_attrdef ad ON d.classid = ${PG_ATTRDEF} AND ad.oid = d.objid
371
+ LEFT JOIN pg_attribute att ON att.attrelid = ad.adrelid AND att.attnum = ad.adnum
372
+ LEFT JOIN pg_rewrite rw ON d.classid = ${PG_REWRITE} AND rw.oid = d.objid
373
+ LEFT JOIN pg_constraint co ON d.classid = ${PG_CONSTRAINT} AND co.oid = d.objid
374
+ LEFT JOIN pg_class cc ON d.classid = ${PG_CLASS} AND cc.oid = d.objid
375
+ LEFT JOIN pg_type rt ON d.refclassid = ${PG_TYPE} AND rt.oid = d.refobjid
376
+ LEFT JOIN pg_class rc ON rc.oid = rt.typrelid
377
+ WHERE d.deptype = 'n' AND d.refclassid IN (${PG_TYPE}, ${PG_PROC}, ${PG_CLASS})
378
+ AND (d.classid IN (${PG_TYPE}, ${PG_PROC}, ${PG_CLASS}, ${PG_ATTRDEF})
379
+ OR (d.classid = ${PG_REWRITE} AND rw.rulename = '_RETURN')
380
+ OR (d.classid = ${PG_CONSTRAINT} AND co.contype = 'c'))
381
+ ) x`