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