@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,114 @@
1
+ import { DbAdminError } from '../errors.ts'
2
+
3
+ /*
4
+ * The backup file: plain SQL that psql can run too, with one JSON line at the top saying what's in
5
+ * it, and one at the bottom saying it's whole. A download that stopped early has no last line, so
6
+ * it's refused before anything it would change is committed.
7
+ */
8
+
9
+ /** The file's first line starts with this, then the header as JSON. */
10
+ export const HEADER_PREFIX = '-- otw-db backup '
11
+ /** Its last line starts with this, then the summary as JSON. */
12
+ export const TRAILER_PREFIX = '-- otw-db backup complete '
13
+ /** The format this code writes, and the newest it reads. */
14
+ export const BACKUP_VERSION = 1
15
+ /** Where a restore's upload waits, in the database it restores; never in a backup. */
16
+ export const STAGING_SCHEMA = 'otw_db_restore'
17
+
18
+ /** What a backup holds, from its first line. */
19
+ export interface BackupHeader {
20
+ format: 'otw-db'
21
+ version: number
22
+ createdAt: string
23
+ database: string
24
+ /** Such as `PostgreSQL 17.5`. */
25
+ server: string
26
+ /** server_version_num: 170005 for 17.5. */
27
+ serverVersion: number
28
+ /** The schemas it replaces when restored. */
29
+ schemas: string[]
30
+ /** Roles its owners, grants and policies name: a server without them skips those. */
31
+ roles: string[]
32
+ /** What the database had that the backup doesn't, such as `aggregate public.median(numeric)`. */
33
+ notIncluded: string[]
34
+ }
35
+
36
+ /** How much a backup holds, from its last line. */
37
+ export interface BackupSummary {
38
+ tables: number
39
+ rows: number
40
+ }
41
+
42
+ export function headerLine(header: BackupHeader): string {
43
+ return `${HEADER_PREFIX}${JSON.stringify(header)}\n`
44
+ }
45
+
46
+ export function trailerLine(summary: BackupSummary): string {
47
+ return `${TRAILER_PREFIX}${JSON.stringify(summary)}\n`
48
+ }
49
+
50
+ /** The header from a backup's first line; refuses anything else, or a newer format. */
51
+ export function readHeader(line: string): BackupHeader {
52
+ const header = line.startsWith(HEADER_PREFIX) ? parse(line.slice(HEADER_PREFIX.length)) : null
53
+ if (
54
+ header?.format !== 'otw-db' ||
55
+ typeof header.version !== 'number' ||
56
+ !names(header.schemas) ||
57
+ !header.schemas.length
58
+ ) {
59
+ throw new DbAdminError(
60
+ "This file isn't an otw-db backup: its first line should start with “-- otw-db backup”.",
61
+ 400,
62
+ 'not-a-backup',
63
+ )
64
+ }
65
+ if (header.version > BACKUP_VERSION) {
66
+ throw new DbAdminError(
67
+ `This backup was made by a newer otw-db (format ${header.version}): update otw-db to restore it.`,
68
+ 400,
69
+ 'newer-backup',
70
+ )
71
+ }
72
+ return {
73
+ ...header,
74
+ roles: names(header.roles) ? header.roles : [],
75
+ notIncluded: names(header.notIncluded) ? header.notIncluded : [],
76
+ serverVersion: typeof header.serverVersion === 'number' ? header.serverVersion : 0,
77
+ } as BackupHeader
78
+ }
79
+
80
+ /** A list of names, as a header has them: strings, and not absurdly many. */
81
+ function names(value: unknown): value is string[] {
82
+ return Array.isArray(value) && value.length <= 10_000 && value.every((v) => typeof v === 'string')
83
+ }
84
+
85
+ function parse(json: string): Partial<BackupHeader> | null {
86
+ try {
87
+ return JSON.parse(json) as Partial<BackupHeader>
88
+ } catch {
89
+ return null
90
+ }
91
+ }
92
+
93
+ /** The summary from a backup's last line, or null when the file stops before it. */
94
+ export function readTrailer(line: string): BackupSummary | null {
95
+ if (!line.startsWith(TRAILER_PREFIX)) return null
96
+ try {
97
+ const summary = JSON.parse(line.slice(TRAILER_PREFIX.length)) as BackupSummary
98
+ return typeof summary?.tables === 'number' && typeof summary.rows === 'number' ? summary : null
99
+ } catch {
100
+ return null
101
+ }
102
+ }
103
+
104
+ /** `shop-main-2026-11-08-1430.sql.gz`: the connection, the database and when, safe as a file name. */
105
+ export function backupFileName(
106
+ connection: string,
107
+ database: string,
108
+ at: Date,
109
+ extension: 'sql.gz' | 'dump',
110
+ ): string {
111
+ const stamp = at.toISOString().slice(0, 16).replace('T', '-').replace(':', '')
112
+ const safe = (part: string) => part.replace(/[^\w.-]+/g, '_').slice(0, 60)
113
+ return `${safe(connection)}-${safe(database)}-${stamp}.${extension}`
114
+ }
@@ -0,0 +1,185 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { DbAdminError } from '../errors.ts'
3
+ import { STAGING_SCHEMA } from './format.ts'
4
+
5
+ /*
6
+ * pg_dump and pg_restore, where the server running the tool has them (a VPS, a container with
7
+ * the PostgreSQL client), never on a serverless host. Found once, on first use.
8
+ */
9
+
10
+ export interface PgTool {
11
+ available: boolean
12
+ /** Such as `pg_dump (PostgreSQL) 17.11`. */
13
+ version?: string
14
+ /** Why it can't be used: missing, or older than the server. */
15
+ reason?: string
16
+ }
17
+
18
+ const found = new Map<string, Promise<{ version: string; major: number } | null>>()
19
+
20
+ function find(name: 'pg_dump' | 'pg_restore') {
21
+ let tool = found.get(name)
22
+ if (!tool) {
23
+ tool = new Promise((resolve) => {
24
+ const child = spawn(name, ['--version'], { stdio: ['ignore', 'pipe', 'ignore'] })
25
+ let out = ''
26
+ child.stdout.on('data', (data: Buffer) => (out += data.toString()))
27
+ child.on('error', () => resolve(null))
28
+ child.on('close', (code) => {
29
+ const major = /\)\s+(\d+)/.exec(out)?.[1]
30
+ resolve(code === 0 && major ? { version: out.trim(), major: Number(major) } : null)
31
+ })
32
+ })
33
+ found.set(name, tool)
34
+ }
35
+ return tool
36
+ }
37
+
38
+ /** Whether `name` can work with a server of `serverVersion` (server_version_num). */
39
+ export async function pgTool(
40
+ name: 'pg_dump' | 'pg_restore',
41
+ serverVersion: number,
42
+ ): Promise<PgTool> {
43
+ const tool = await find(name)
44
+ if (!tool)
45
+ return { available: false, reason: `${name} isn't installed on the server running this tool.` }
46
+ const server = Math.floor(serverVersion / 10_000)
47
+ // pg_dump refuses a newer server; pg_restore reads what a pg_dump as new as itself wrote.
48
+ if (tool.major < server) {
49
+ return {
50
+ available: false,
51
+ version: tool.version,
52
+ reason: `${tool.version} is older than the database's PostgreSQL ${server}.`,
53
+ }
54
+ }
55
+ return { available: true, version: tool.version }
56
+ }
57
+
58
+ /**
59
+ * A connection URL as libpq takes it, with the password apart, for the environment rather than
60
+ * the command line, where other users could read it. Supabase's pooler is used in session mode,
61
+ * as a dump runs in one session. node-postgres's own parameters go: libpq refuses those it
62
+ * doesn't know.
63
+ */
64
+ export function libpqTarget(connectionUrl: string): { url: string; env: Record<string, string> } {
65
+ const hostless = connectionUrl.includes('@/')
66
+ const url = new URL(hostless ? connectionUrl.replace('@/', '@localhost/') : connectionUrl)
67
+ if (/\.pooler\.supabase\.com$/i.test(url.hostname) && url.port === '6543') url.port = '5432'
68
+ const password = decodeURIComponent(url.password)
69
+ url.password = ''
70
+ const kept: string[] = []
71
+ // By hand rather than through searchParams, which would write the others' %20 as +.
72
+ for (const pair of url.search.slice(1).split('&').filter(Boolean)) {
73
+ const [key = '', value = ''] = pair.split('=')
74
+ if (key === 'uselibpqcompat') continue
75
+ if (key === 'ssl') {
76
+ if (value !== 'false' && value !== '0') kept.push('sslmode=require')
77
+ continue
78
+ }
79
+ if (key === 'sslmode' && value === 'no-verify') {
80
+ kept.push('sslmode=require')
81
+ continue
82
+ }
83
+ kept.push(pair)
84
+ }
85
+ url.search = kept.join('&')
86
+ const href = hostless ? url.href.replace('@localhost/', '@/') : url.href
87
+ return { url: href, env: password ? { PGPASSWORD: password } : {} }
88
+ }
89
+
90
+ /** A schema as a pg_dump pattern that matches it alone: quoted, so * and ? are taken as they are. */
91
+ export function schemaPattern(schema: string): string {
92
+ return `"${schema.replaceAll('"', '""')}"`
93
+ }
94
+
95
+ export function dumpArgs(url: string, schemas: readonly string[]): string[] {
96
+ return [
97
+ '--format=custom',
98
+ '--no-password',
99
+ ...schemas.map((schema) => `--schema=${schemaPattern(schema)}`),
100
+ `--exclude-schema=${schemaPattern(STAGING_SCHEMA)}`,
101
+ `--dbname=${url}`,
102
+ ]
103
+ }
104
+
105
+ /**
106
+ * pg_dump's archive, streamed as it writes it. Waits for its first bytes, so a refusal (a wrong
107
+ * password, a newer server) is an error here rather than a broken download.
108
+ */
109
+ export async function runDump(
110
+ connectionUrl: string,
111
+ schemas: readonly string[],
112
+ ): Promise<ReadableStream<Uint8Array>> {
113
+ const { url, env } = libpqTarget(connectionUrl)
114
+ const child = spawn('pg_dump', dumpArgs(url, schemas), {
115
+ env: { ...process.env, ...env },
116
+ stdio: ['ignore', 'pipe', 'pipe'],
117
+ })
118
+ let errors = ''
119
+ child.stderr.on('data', (data: Buffer) => (errors = (errors + data.toString()).slice(-4_000)))
120
+ const exited = new Promise<number | null>((resolve) => {
121
+ child.on('close', resolve)
122
+ child.on('error', () => resolve(-1))
123
+ })
124
+ const failure = () =>
125
+ new DbAdminError(
126
+ `pg_dump failed: ${errors.trim() || 'it stopped early.'}`,
127
+ 502,
128
+ 'pg-dump-failed',
129
+ )
130
+ const reader = child.stdout[Symbol.asyncIterator]()
131
+ const first = await Promise.race([reader.next(), exited.then(() => null)])
132
+ if (first === null || first.done) {
133
+ const code = await exited
134
+ if (code !== 0) throw failure()
135
+ }
136
+ let sentFirst = false
137
+ return new ReadableStream<Uint8Array>({
138
+ async pull(controller) {
139
+ if (!sentFirst) {
140
+ sentFirst = true
141
+ if (first && !first.done) return controller.enqueue(first.value as Uint8Array)
142
+ }
143
+ const next = await reader.next()
144
+ if (!next.done) return controller.enqueue(next.value as Uint8Array)
145
+ // A broken archive must not look like a whole one: an error the download sees.
146
+ if ((await exited) !== 0) controller.error(failure())
147
+ else controller.close()
148
+ },
149
+ cancel() {
150
+ child.kill()
151
+ },
152
+ })
153
+ }
154
+
155
+ /** pg_restore of `file` in one transaction: replacing what the archive holds, or nothing. */
156
+ export async function runRestore(connectionUrl: string, file: string): Promise<void> {
157
+ const { url, env } = libpqTarget(connectionUrl)
158
+ const child = spawn(
159
+ 'pg_restore',
160
+ [
161
+ '--clean',
162
+ '--if-exists',
163
+ '--no-owner',
164
+ '--single-transaction',
165
+ '--exit-on-error',
166
+ '--no-password',
167
+ `--dbname=${url}`,
168
+ file,
169
+ ],
170
+ { env: { ...process.env, ...env }, stdio: ['ignore', 'ignore', 'pipe'] },
171
+ )
172
+ let errors = ''
173
+ child.stderr.on('data', (data: Buffer) => (errors = (errors + data.toString()).slice(-4_000)))
174
+ const code = await new Promise<number | null>((resolve) => {
175
+ child.on('close', resolve)
176
+ child.on('error', () => resolve(-1))
177
+ })
178
+ if (code !== 0) {
179
+ throw new DbAdminError(
180
+ `pg_restore failed, so nothing was restored: ${errors.trim() || `it exited with ${code}.`}`,
181
+ 400,
182
+ 'restore-failed',
183
+ )
184
+ }
185
+ }
@@ -0,0 +1,270 @@
1
+ import { Readable } from 'node:stream'
2
+ import { createGunzip } from 'node:zlib'
3
+ import { DbAdminError, QueryError } from '../errors.ts'
4
+ import type { Session } from '../types.ts'
5
+ import {
6
+ readHeader,
7
+ readTrailer,
8
+ STAGING_SCHEMA,
9
+ type BackupHeader,
10
+ type BackupSummary,
11
+ } from './format.ts'
12
+ import { StatementSplitter } from './split.ts'
13
+
14
+ /*
15
+ * A backup restored in one transaction: its statements run as they stream in, and nothing is
16
+ * committed unless every one ran and the file ends with its completion line. A restore that
17
+ * fails, or a file cut short, leaves the database as it was.
18
+ */
19
+
20
+ /** What restoring a backup would replace here, and what stops it. */
21
+ export interface RestorePlan {
22
+ server: string
23
+ serverVersion: number
24
+ schemas: {
25
+ schema: string
26
+ exists: boolean
27
+ tables: number
28
+ views: number
29
+ functions: number
30
+ /** PostgreSQL's estimate. */
31
+ rows: number
32
+ }[]
33
+ /** Objects outside the backup's schemas that depend on what's in them: restoring would drop them. */
34
+ blocked: string[]
35
+ /** Roles the backup's owners, grants and policies name that this server lacks: those are skipped. */
36
+ missingRoles: string[]
37
+ warnings: string[]
38
+ }
39
+
40
+ export interface RestoreProgress {
41
+ statements: number
42
+ /** The backup's bytes read so far, compressed if it is. */
43
+ bytes: number
44
+ }
45
+
46
+ export interface RestoreResult extends BackupSummary {
47
+ statements: number
48
+ }
49
+
50
+ const SERVER_SQL = `SELECT json_build_object('version', current_setting('server_version_num')::int,
51
+ 'server', split_part(version(), ' ', 1) || ' ' || current_setting('server_version'))`
52
+
53
+ const SCHEMAS_SQL = `SELECT coalesce(json_agg(json_build_object('schema', s.name, 'exists', n.oid IS NOT NULL,
54
+ 'tables', (SELECT count(*) FROM pg_class c WHERE c.relnamespace = n.oid AND c.relkind IN ('r','p') AND NOT c.relispartition),
55
+ 'views', (SELECT count(*) FROM pg_class c WHERE c.relnamespace = n.oid AND c.relkind IN ('v','m')),
56
+ 'functions', (SELECT count(*) FROM pg_proc p WHERE p.pronamespace = n.oid),
57
+ 'rows', (SELECT coalesce(sum(greatest(c.reltuples, 0)), 0)::bigint FROM pg_class c
58
+ WHERE c.relnamespace = n.oid AND c.relkind = 'r'))
59
+ ORDER BY s.name), '[]')
60
+ FROM unnest($1::text[]) AS s(name) LEFT JOIN pg_namespace n ON n.nspname = s.name`
61
+
62
+ /**
63
+ * What outside the schemas depends on what's in them. A column default, a view's rule, a trigger
64
+ * or a policy belongs to its table's schema, an operator family's member to the family's; a cast,
65
+ * a publication's table or an event trigger to none, so it's outside. The common catalogs are
66
+ * looked up directly; pg_identify_object, slower, answers for the rest.
67
+ */
68
+ const BLOCKED_SQL = `WITH ns AS (SELECT oid FROM pg_namespace WHERE nspname = ANY($1)),
69
+ inside AS (
70
+ SELECT 'pg_class'::regclass::oid AS cat, c.oid FROM pg_class c WHERE c.relnamespace IN (SELECT oid FROM ns)
71
+ UNION ALL SELECT 'pg_type'::regclass::oid, t.oid FROM pg_type t WHERE t.typnamespace IN (SELECT oid FROM ns)
72
+ UNION ALL SELECT 'pg_proc'::regclass::oid, p.oid FROM pg_proc p WHERE p.pronamespace IN (SELECT oid FROM ns)
73
+ UNION ALL SELECT 'pg_extension'::regclass::oid, x.oid FROM pg_extension x WHERE x.extnamespace IN (SELECT oid FROM ns)
74
+ ),
75
+ deps AS (
76
+ SELECT d.classid, d.objid, d.objsubid, d.refclassid, d.refobjid,
77
+ CASE d.classid
78
+ WHEN 'pg_class'::regclass THEN (SELECT relnamespace FROM pg_class WHERE oid = d.objid)
79
+ WHEN 'pg_type'::regclass THEN (SELECT typnamespace FROM pg_type WHERE oid = d.objid)
80
+ WHEN 'pg_proc'::regclass THEN (SELECT pronamespace FROM pg_proc WHERE oid = d.objid)
81
+ WHEN 'pg_constraint'::regclass THEN (SELECT connamespace FROM pg_constraint WHERE oid = d.objid)
82
+ WHEN 'pg_extension'::regclass THEN (SELECT extnamespace FROM pg_extension WHERE oid = d.objid)
83
+ WHEN 'pg_attrdef'::regclass THEN (SELECT c.relnamespace FROM pg_attrdef a JOIN pg_class c ON c.oid = a.adrelid WHERE a.oid = d.objid)
84
+ WHEN 'pg_rewrite'::regclass THEN (SELECT c.relnamespace FROM pg_rewrite r JOIN pg_class c ON c.oid = r.ev_class WHERE r.oid = d.objid)
85
+ WHEN 'pg_trigger'::regclass THEN (SELECT c.relnamespace FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid WHERE t.oid = d.objid)
86
+ WHEN 'pg_policy'::regclass THEN (SELECT c.relnamespace FROM pg_policy p JOIN pg_class c ON c.oid = p.polrelid WHERE p.oid = d.objid)
87
+ 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)
88
+ 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)
89
+ ELSE (SELECT n.oid FROM pg_namespace n WHERE n.nspname = (pg_identify_object(d.classid, d.objid, d.objsubid)).schema)
90
+ END AS ns
91
+ FROM pg_depend d JOIN inside i ON i.cat = d.refclassid AND i.oid = d.refobjid
92
+ WHERE d.deptype IN ('n', 'a')
93
+ AND NOT EXISTS (SELECT 1 FROM pg_depend e WHERE e.classid = d.classid AND e.objid = d.objid AND e.deptype = 'e')
94
+ )
95
+ SELECT coalesce(json_agg(x.what ORDER BY x.what), '[]') FROM (
96
+ SELECT DISTINCT pg_describe_object(classid, objid, objsubid) || ' needs '
97
+ || pg_describe_object(refclassid, refobjid, 0) AS what
98
+ FROM deps WHERE ns IS NULL OR ns NOT IN (SELECT oid FROM ns) LIMIT 50) x`
99
+
100
+ const MISSING_ROLES_SQL = `SELECT coalesce(json_agg(r ORDER BY r), '[]') FROM unnest($1::text[]) r
101
+ WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r)`
102
+
103
+ /** What restoring `header`'s backup would do here. Runs in any session. */
104
+ export async function restorePlan(session: Session, header: BackupHeader): Promise<RestorePlan> {
105
+ // Names described schema-qualified, whatever the login's search_path.
106
+ await session.query(`SELECT set_config('search_path', '', true)`)
107
+ const server = await json<{ version: number; server: string }>(session, SERVER_SQL)
108
+ const schemas = await json<RestorePlan['schemas']>(session, SCHEMAS_SQL, [header.schemas])
109
+ const blocked = await json<string[]>(session, BLOCKED_SQL, [header.schemas])
110
+ const missingRoles = await json<string[]>(session, MISSING_ROLES_SQL, [header.roles])
111
+ const warnings: string[] = []
112
+ if (Math.floor(server.version / 10_000) < Math.floor(header.serverVersion / 10_000)) {
113
+ warnings.push(
114
+ `The backup comes from ${header.server}, newer than this server's ${server.server}: what it uses that this version lacks will fail, and nothing will change.`,
115
+ )
116
+ }
117
+ return {
118
+ server: server.server,
119
+ serverVersion: server.version,
120
+ schemas: schemas.map((s) => ({
121
+ ...s,
122
+ tables: Number(s.tables),
123
+ views: Number(s.views),
124
+ functions: Number(s.functions),
125
+ rows: Number(s.rows),
126
+ })),
127
+ blocked,
128
+ missingRoles,
129
+ warnings,
130
+ }
131
+ }
132
+
133
+ /** Refuses a backup that would drop what's outside it, or touch the restore's own upload. */
134
+ export function refuseBlocked(header: BackupHeader, plan: RestorePlan): void {
135
+ if (header.schemas.includes(STAGING_SCHEMA)) {
136
+ throw new DbAdminError(
137
+ `A backup can't hold ${STAGING_SCHEMA}, where restores wait.`,
138
+ 400,
139
+ 'bad-backup',
140
+ )
141
+ }
142
+ if (plan.blocked.length) {
143
+ throw new DbAdminError(
144
+ `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.`,
145
+ 409,
146
+ 'restore-blocked',
147
+ )
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Runs the backup in `bytes` (gzipped or not) in `session`, a write session the caller ends:
153
+ * commit once this returns, roll back if it throws. `check` sees the header before anything runs.
154
+ */
155
+ export async function restoreSql(
156
+ session: Session,
157
+ bytes: AsyncIterable<Uint8Array>,
158
+ options: {
159
+ check(header: BackupHeader): Promise<void>
160
+ onProgress?(progress: RestoreProgress): void
161
+ },
162
+ ): Promise<RestoreResult> {
163
+ const progress: RestoreProgress = { statements: 0, bytes: 0 }
164
+ const counted = (async function* () {
165
+ for await (const chunk of bytes) {
166
+ progress.bytes += chunk.byteLength
167
+ yield chunk
168
+ }
169
+ })()
170
+ const decoder = new TextDecoder('utf-8', { fatal: true })
171
+ const splitter = new StatementSplitter()
172
+ let header: BackupHeader | null = null
173
+ let start = ''
174
+ /** The end of the text so far, for the last line. */
175
+ let tail = ''
176
+ let reported = 0
177
+ const run = async (statements: string[]) => {
178
+ for (const statement of statements) {
179
+ try {
180
+ await session.query(statement)
181
+ } catch (error) {
182
+ throw failed(progress.statements + 1, statement, error)
183
+ }
184
+ progress.statements += 1
185
+ const now = performance.now()
186
+ if (options.onProgress && now - reported > 250) {
187
+ reported = now
188
+ options.onProgress({ ...progress })
189
+ }
190
+ }
191
+ }
192
+ try {
193
+ for await (const chunk of await text(counted)) {
194
+ const piece = decoder.decode(chunk, { stream: true })
195
+ tail = (tail + piece).slice(-16_384)
196
+ if (!header) {
197
+ start += piece
198
+ const end = start.indexOf('\n')
199
+ if (end === -1) {
200
+ if (start.length > 1_000_000) readHeader(start.slice(0, 200))
201
+ continue
202
+ }
203
+ header = readHeader(start.slice(0, end))
204
+ await options.check(header)
205
+ await run(splitter.push(start))
206
+ start = ''
207
+ continue
208
+ }
209
+ await run(splitter.push(piece))
210
+ }
211
+ const last = decoder.decode()
212
+ tail += last
213
+ if (!header) header = readHeader(start + last)
214
+ await run(splitter.push(last))
215
+ await run(splitter.end())
216
+ } catch (error) {
217
+ if (error instanceof DbAdminError) throw error
218
+ if (error instanceof TypeError && /encoded data|invalid/i.test(error.message)) {
219
+ throw new DbAdminError(
220
+ "The backup isn't valid UTF-8 text: it may be damaged.",
221
+ 400,
222
+ 'bad-backup',
223
+ )
224
+ }
225
+ const message = (error as Error).message ?? String(error)
226
+ // zlib's, for a damaged or cut .gz; the splitter's, for SQL that ends mid-string.
227
+ throw new DbAdminError(`The backup can't be read: ${message}`, 400, 'bad-backup')
228
+ }
229
+ const lastLine = tail.trimEnd().split('\n').pop() ?? ''
230
+ const summary = readTrailer(lastLine)
231
+ if (!summary) {
232
+ throw new DbAdminError(
233
+ 'The backup stops before its end, so nothing was restored: it may have been cut off while downloading. Download it again.',
234
+ 400,
235
+ 'incomplete-backup',
236
+ )
237
+ }
238
+ options.onProgress?.({ ...progress })
239
+ return { ...summary, statements: progress.statements }
240
+ }
241
+
242
+ /** The bytes as they come, unzipped when they start as gzip does. */
243
+ async function text(bytes: AsyncIterator<Uint8Array> & AsyncIterable<Uint8Array>) {
244
+ const first = await bytes.next()
245
+ if (first.done) return (async function* () {})()
246
+ const head = first.value
247
+ const all = (async function* () {
248
+ yield head
249
+ yield* { [Symbol.asyncIterator]: () => bytes }
250
+ })()
251
+ if (head[0] !== 0x1f || head[1] !== 0x8b) return all
252
+ return Readable.from(all).pipe(createGunzip()) as AsyncIterable<Uint8Array>
253
+ }
254
+
255
+ /** A statement's failure, saying which and where. */
256
+ function failed(n: number, statement: string, error: unknown): DbAdminError {
257
+ const message = (error as Error).message ?? String(error)
258
+ const shown = statement.length > 600 ? `${statement.slice(0, 600)}…` : statement
259
+ const detail = error instanceof QueryError ? error.details : undefined
260
+ return new DbAdminError(
261
+ `Statement ${n.toLocaleString('en')} of the backup failed, so nothing was restored: ${message}${detail?.detail ? `\n${detail.detail}` : ''}\n\n${shown}`,
262
+ 400,
263
+ 'restore-failed',
264
+ )
265
+ }
266
+
267
+ async function json<T>(session: Session, sql: string, values?: unknown[]): Promise<T> {
268
+ const { rows } = await session.query(sql, values)
269
+ return JSON.parse(rows[0]![0]!) as T
270
+ }