@otwdesign/db-core 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/backup/api.d.ts +55 -0
  2. package/dist/backup/api.js +441 -0
  3. package/dist/backup/api.js.map +1 -0
  4. package/dist/backup/catalog.d.ts +47 -0
  5. package/dist/backup/catalog.js +348 -0
  6. package/dist/backup/catalog.js.map +1 -0
  7. package/dist/backup/dump.d.ts +49 -0
  8. package/dist/backup/dump.js +860 -0
  9. package/dist/backup/dump.js.map +1 -0
  10. package/dist/backup/format.d.ts +38 -0
  11. package/dist/backup/format.js +70 -0
  12. package/dist/backup/format.js.map +1 -0
  13. package/dist/backup/pg-tools.d.ts +30 -0
  14. package/dist/backup/pg-tools.js +154 -0
  15. package/dist/backup/pg-tools.js.map +1 -0
  16. package/dist/backup/restore.d.ts +42 -0
  17. package/dist/backup/restore.js +196 -0
  18. package/dist/backup/restore.js.map +1 -0
  19. package/dist/backup/split.d.ts +18 -0
  20. package/dist/backup/split.js +316 -0
  21. package/dist/backup/split.js.map +1 -0
  22. package/dist/backup/staging.d.ts +29 -0
  23. package/dist/backup/staging.js +96 -0
  24. package/dist/backup/staging.js.map +1 -0
  25. package/dist/browser.d.ts +5 -0
  26. package/dist/drivers/pglite.js +57 -0
  27. package/dist/drivers/pglite.js.map +1 -1
  28. package/dist/drivers/postgres.js +45 -0
  29. package/dist/drivers/postgres.js.map +1 -1
  30. package/dist/handler.d.ts +5 -0
  31. package/dist/handler.js +48 -1
  32. package/dist/handler.js.map +1 -1
  33. package/dist/index.d.ts +5 -0
  34. package/dist/types.d.ts +30 -1
  35. package/package.json +2 -2
  36. package/src/backup/api.ts +543 -0
  37. package/src/backup/catalog.ts +381 -0
  38. package/src/backup/dump.ts +1103 -0
  39. package/src/backup/format.ts +114 -0
  40. package/src/backup/pg-tools.ts +186 -0
  41. package/src/backup/restore.ts +271 -0
  42. package/src/backup/split.ts +300 -0
  43. package/src/backup/staging.ts +143 -0
  44. package/src/browser.ts +5 -0
  45. package/src/drivers/pglite.ts +55 -0
  46. package/src/drivers/postgres.ts +46 -0
  47. package/src/handler.ts +56 -1
  48. package/src/index.ts +6 -0
  49. package/src/types.ts +29 -1
@@ -0,0 +1,300 @@
1
+ /**
2
+ * PostgreSQL's SQL cut into statements as it streams in, the way psql reads a file: a semicolon
3
+ * ends a statement unless it's inside a string ('…', E'…', $tag$…$tag$), a quoted name ("…") or a
4
+ * comment (-- … and nested /* … *\/), inside parentheses, or inside a function's BEGIN ATOMIC …
5
+ * END body. Text may arrive cut anywhere, even inside a string or a dollar quote's tag. A
6
+ * statement keeps the comments inside and before it; comments with nothing after them are
7
+ * dropped.
8
+ *
9
+ * standard_conforming_strings is taken as on, PostgreSQL's default since 9.1: a backslash is
10
+ * literal in '…' and escapes only in E'…'.
11
+ */
12
+ export class StatementSplitter {
13
+ #text = ''
14
+ /** Where the statement being read starts in #text. */
15
+ #start = 0
16
+ /** How far #text has been read. */
17
+ #at = 0
18
+ #state: State = 'code'
19
+ /** Block comments nest in PostgreSQL. */
20
+ #depth = 0
21
+ /** The dollar quote's closing delimiter, such as `$body$`. */
22
+ #close = ''
23
+ /** Whether the statement so far has anything but comments and spaces. */
24
+ #code = false
25
+ /** Parentheses open, and BEGIN … END blocks open in a function's body: psql's heuristic. */
26
+ #parens = 0
27
+ #begins = 0
28
+ /** Words read in the statement, and the first letters of the first four that matter. */
29
+ #words = 0
30
+ #head = ''
31
+
32
+ /** Reads `text` and returns the statements it completes, without their semicolons. */
33
+ push(text: string): string[] {
34
+ // Drop what earlier statements took, once per push rather than once per statement.
35
+ if (this.#start > 0) {
36
+ this.#text = this.#text.slice(this.#start)
37
+ this.#at -= this.#start
38
+ this.#start = 0
39
+ }
40
+ this.#text += text
41
+ return this.#read(false)
42
+ }
43
+
44
+ /** The statement left at the end, if any: the last one may have no semicolon. */
45
+ end(): string[] {
46
+ const done = this.#read(true)
47
+ if (this.#state !== 'code' && this.#state !== 'line-comment') {
48
+ throw new Error(`The SQL ends inside ${UNFINISHED[this.#state]}.`)
49
+ }
50
+ const last = this.#code ? this.#text.slice(this.#start).trim() : ''
51
+ this.#text = ''
52
+ this.#start = 0
53
+ this.#at = 0
54
+ this.#code = false
55
+ this.#state = 'code'
56
+ this.#restart()
57
+ return last ? [...done, last] : done
58
+ }
59
+
60
+ #restart(): void {
61
+ this.#parens = 0
62
+ this.#begins = 0
63
+ this.#words = 0
64
+ this.#head = ''
65
+ }
66
+
67
+ /**
68
+ * psql's way to find a SQL-standard function body (BEGIN ATOMIC … END), whose semicolons don't
69
+ * end the statement: in CREATE [OR REPLACE] FUNCTION or PROCEDURE, outside parentheses, BEGIN
70
+ * opens a block and END closes one, as CASE, which also ends with END, does inside one.
71
+ */
72
+ #word(word: string): void {
73
+ const lower = word.toLowerCase()
74
+ if (this.#words < 4) this.#head += TRACKED.has(lower) ? lower[0] : ' '
75
+ this.#words += 1
76
+ const h = this.#head
77
+ const routine =
78
+ h[0] === 'c' &&
79
+ (h[1] === 'f' ||
80
+ h[1] === 'p' ||
81
+ (h[1] === 'o' && h[2] === 'r' && (h[3] === 'f' || h[3] === 'p')))
82
+ if (!routine || this.#parens !== 0) return
83
+ if (lower === 'begin') this.#begins += 1
84
+ else if (lower === 'case' && this.#begins >= 1) this.#begins += 1
85
+ else if (lower === 'end' && this.#begins > 0) this.#begins -= 1
86
+ }
87
+
88
+ /** Reads as far as the text allows; `final` when no more is coming. */
89
+ #read(final: boolean): string[] {
90
+ const done: string[] = []
91
+ const s = this.#text
92
+ const n = s.length
93
+ /** Whether the character at `i` hasn't arrived yet, though more text may. */
94
+ const waiting = (i: number) => !final && i >= n
95
+ let at = this.#at
96
+ read: while (at < n) {
97
+ switch (this.#state) {
98
+ case 'code': {
99
+ const c = s.charCodeAt(at)
100
+ if (c === SEMICOLON && this.#parens === 0 && this.#begins === 0) {
101
+ const statement = s.slice(this.#start, at).trim()
102
+ if (this.#code && statement) done.push(statement)
103
+ this.#start = at + 1
104
+ this.#code = false
105
+ this.#restart()
106
+ at += 1
107
+ } else if (
108
+ wordStart(c) &&
109
+ !identifierChar(at > this.#start ? s.charCodeAt(at - 1) : NaN)
110
+ ) {
111
+ let end = at + 1
112
+ while (end < n && identifierChar(s.charCodeAt(end))) end += 1
113
+ // The word may go on in the text still to come.
114
+ if (waiting(end)) break read
115
+ this.#code = true
116
+ this.#word(s.slice(at, end))
117
+ at = end
118
+ } else if (c === OPEN || c === CLOSE) {
119
+ this.#code = true
120
+ if (c === OPEN) this.#parens += 1
121
+ else if (this.#parens > 0) this.#parens -= 1
122
+ at += 1
123
+ } else if (c === QUOTE) {
124
+ this.#code = true
125
+ this.#state = escapeStringStarts(s, at, this.#start) ? 'escape-string' : 'string'
126
+ at += 1
127
+ } else if (c === DOUBLE_QUOTE) {
128
+ this.#code = true
129
+ this.#state = 'name'
130
+ at += 1
131
+ } else if ((c === DASH || c === SLASH) && waiting(at + 1)) {
132
+ break read
133
+ } else if (c === DASH && s.charCodeAt(at + 1) === DASH) {
134
+ this.#state = 'line-comment'
135
+ at += 2
136
+ } else if (c === SLASH && s.charCodeAt(at + 1) === STAR) {
137
+ this.#state = 'block-comment'
138
+ this.#depth = 1
139
+ at += 2
140
+ } else if (
141
+ c === DOLLAR &&
142
+ !identifierChar(at > this.#start ? s.charCodeAt(at - 1) : NaN)
143
+ ) {
144
+ const tag = dollarTag(s, at, final)
145
+ if (tag === undefined) break read
146
+ this.#code = true
147
+ if (tag === null) at += 1
148
+ else {
149
+ this.#state = 'dollar'
150
+ this.#close = tag
151
+ at += tag.length
152
+ }
153
+ } else {
154
+ if (!whitespace(c)) this.#code = true
155
+ at += 1
156
+ }
157
+ break
158
+ }
159
+ case 'string':
160
+ case 'name': {
161
+ const quote = this.#state === 'string' ? "'" : '"'
162
+ const end = s.indexOf(quote, at)
163
+ if (end === -1) {
164
+ at = n
165
+ break read
166
+ }
167
+ // A doubled quote is a quote inside: wait to see the next character.
168
+ if (waiting(end + 1)) {
169
+ at = end
170
+ break read
171
+ }
172
+ if (s[end + 1] === quote) at = end + 2
173
+ else {
174
+ this.#state = 'code'
175
+ at = end + 1
176
+ }
177
+ break
178
+ }
179
+ case 'escape-string': {
180
+ const c = s.charCodeAt(at)
181
+ if ((c === BACKSLASH || c === QUOTE) && waiting(at + 1)) break read
182
+ if (c === BACKSLASH) at += 2
183
+ else if (c === QUOTE && s.charCodeAt(at + 1) === QUOTE) at += 2
184
+ else if (c === QUOTE) {
185
+ this.#state = 'code'
186
+ at += 1
187
+ } else at += 1
188
+ break
189
+ }
190
+ case 'line-comment': {
191
+ const end = s.indexOf('\n', at)
192
+ if (end === -1) {
193
+ at = n
194
+ break read
195
+ }
196
+ this.#state = 'code'
197
+ at = end + 1
198
+ break
199
+ }
200
+ case 'block-comment': {
201
+ const c = s.charCodeAt(at)
202
+ if ((c === STAR || c === SLASH) && waiting(at + 1)) break read
203
+ if (c === STAR && s.charCodeAt(at + 1) === SLASH) {
204
+ this.#depth -= 1
205
+ if (this.#depth === 0) this.#state = 'code'
206
+ at += 2
207
+ } else if (c === SLASH && s.charCodeAt(at + 1) === STAR) {
208
+ this.#depth += 1
209
+ at += 2
210
+ } else at += 1
211
+ break
212
+ }
213
+ case 'dollar': {
214
+ const end = s.indexOf(this.#close, at)
215
+ if (end === -1) {
216
+ // The closing tag may have begun at the very end: look again from there.
217
+ at = Math.max(at, n - this.#close.length + 1)
218
+ break read
219
+ }
220
+ this.#state = 'code'
221
+ at = end + this.#close.length
222
+ break
223
+ }
224
+ }
225
+ }
226
+ this.#at = at
227
+ return done
228
+ }
229
+ }
230
+
231
+ type State =
232
+ 'code' | 'string' | 'escape-string' | 'name' | 'line-comment' | 'block-comment' | 'dollar'
233
+
234
+ const SEMICOLON = 59
235
+ const QUOTE = 39
236
+ const DOUBLE_QUOTE = 34
237
+ const DASH = 45
238
+ const SLASH = 47
239
+ const STAR = 42
240
+ const DOLLAR = 36
241
+ const BACKSLASH = 92
242
+ const OPEN = 40
243
+ const CLOSE = 41
244
+
245
+ /** The words psql looks at to tell CREATE [OR REPLACE] FUNCTION or PROCEDURE. */
246
+ const TRACKED = new Set(['create', 'or', 'replace', 'function', 'procedure'])
247
+
248
+ const UNFINISHED: Record<State, string> = {
249
+ code: 'a statement',
250
+ string: 'a string',
251
+ 'escape-string': 'a string',
252
+ name: 'a quoted name',
253
+ 'line-comment': 'a comment',
254
+ 'block-comment': 'a comment',
255
+ dollar: 'a dollar-quoted string',
256
+ }
257
+
258
+ function whitespace(c: number): boolean {
259
+ return c === 32 || (c >= 9 && c <= 13)
260
+ }
261
+
262
+ /** Letters, digits, `_` and `$`, and anything past ASCII, which PostgreSQL takes as letters. */
263
+ function identifierChar(c: number): boolean {
264
+ return (
265
+ (c >= 48 && c <= 57) ||
266
+ (c >= 65 && c <= 90) ||
267
+ (c >= 97 && c <= 122) ||
268
+ c === 95 ||
269
+ c === DOLLAR ||
270
+ c >= 128
271
+ )
272
+ }
273
+
274
+ /** A letter, `_`, or anything past ASCII: what a word (a keyword, a name) starts with. */
275
+ function wordStart(c: number): boolean {
276
+ return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c >= 128
277
+ }
278
+
279
+ /** Whether the quote at `at` opens an E'…' string: an E or e that starts a word, just before. */
280
+ function escapeStringStarts(s: string, at: number, start: number): boolean {
281
+ if (at - 1 < start) return false
282
+ const e = s.charCodeAt(at - 1)
283
+ if (e !== 69 && e !== 101) return false
284
+ return at - 2 < start || !identifierChar(s.charCodeAt(at - 2))
285
+ }
286
+
287
+ /**
288
+ * The dollar quote opening at `at` (`$$` or `$tag$`); null when it's not one ($1, a stray $);
289
+ * undefined when the text stops before it can tell.
290
+ */
291
+ function dollarTag(s: string, at: number, final: boolean): string | null | undefined {
292
+ // A tag is an identifier, at most 63 bytes, that doesn't start with a digit.
293
+ for (let end = at + 1; end <= at + 65; end += 1) {
294
+ if (end >= s.length) return final ? null : undefined
295
+ const c = s.charCodeAt(end)
296
+ if (c === DOLLAR) return s.slice(at, end + 1)
297
+ if (!identifierChar(c) || (end === at + 1 && c >= 48 && c <= 57)) return null
298
+ }
299
+ return null
300
+ }
@@ -0,0 +1,143 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { DbAdminError } from '../errors.ts'
3
+ import { quote } from '../drivers/postgres-catalog.ts'
4
+ import type { Session } from '../types.ts'
5
+ import { STAGING_SCHEMA } from './format.ts'
6
+
7
+ /*
8
+ * A restore's upload, kept in the database it restores until it runs. A host such as Vercel takes
9
+ * at most 4.5 MB a request, so the browser sends a backup in pieces; serverless instances share
10
+ * nothing but the database, so that's where the pieces wait. The restore reads them back inside
11
+ * its own transaction, and the schema goes once nothing waits in it.
12
+ */
13
+
14
+ /** A piece's most bytes: under Vercel's 4.5 MB a request. */
15
+ export const CHUNK_BYTES = 4 * 1024 * 1024
16
+
17
+ export type UploadKind = 'sql' | 'pg_dump'
18
+
19
+ export interface Upload {
20
+ id: string
21
+ kind: UploadKind
22
+ size: number
23
+ /** The pieces received, and their bytes. */
24
+ chunks: number
25
+ received: number
26
+ }
27
+
28
+ const SCHEMA = quote(STAGING_SCHEMA)
29
+
30
+ /** Makes the tables if need be, drops uploads a day old, and starts one. */
31
+ export async function startUpload(
32
+ session: Session,
33
+ upload: { viewer: string; kind: UploadKind; size: number; name: string },
34
+ ): Promise<string> {
35
+ await session.query(`CREATE SCHEMA IF NOT EXISTS ${SCHEMA}`)
36
+ await session.query(`CREATE TABLE IF NOT EXISTS ${SCHEMA}.uploads (
37
+ id uuid PRIMARY KEY, viewer text NOT NULL, kind text NOT NULL, size bigint NOT NULL,
38
+ name text NOT NULL, created timestamptz NOT NULL DEFAULT now())`)
39
+ await session.query(`CREATE TABLE IF NOT EXISTS ${SCHEMA}.chunks (
40
+ upload uuid NOT NULL REFERENCES ${SCHEMA}.uploads (id) ON DELETE CASCADE,
41
+ seq integer NOT NULL, data bytea NOT NULL, PRIMARY KEY (upload, seq))`)
42
+ await session.query(`DELETE FROM ${SCHEMA}.uploads WHERE created < now() - interval '1 day'`)
43
+ const id = randomUUID()
44
+ await session.query(
45
+ `INSERT INTO ${SCHEMA}.uploads (id, viewer, kind, size, name) VALUES ($1, $2, $3, $4, $5)`,
46
+ [id, upload.viewer, upload.kind, upload.size, upload.name.slice(0, 200)],
47
+ )
48
+ return id
49
+ }
50
+
51
+ /** The upload `id`, if `viewer` started it. */
52
+ export async function findUpload(session: Session, id: string, viewer: string): Promise<Upload> {
53
+ const missing = () =>
54
+ new DbAdminError('That upload is gone: start the restore again.', 404, 'unknown-upload')
55
+ if (!UUID.test(id)) throw missing()
56
+ const exists = await session.query(`SELECT 1 FROM pg_namespace WHERE nspname = $1`, [
57
+ STAGING_SCHEMA,
58
+ ])
59
+ if (!exists.rows.length) throw missing()
60
+ const { rows } = await session.query(
61
+ `SELECT u.kind, u.size, count(c.seq), coalesce(sum(length(c.data)), 0)
62
+ FROM ${SCHEMA}.uploads u LEFT JOIN ${SCHEMA}.chunks c ON c.upload = u.id
63
+ WHERE u.id = $1 AND u.viewer = $2 GROUP BY u.id`,
64
+ [id, viewer],
65
+ )
66
+ const row = rows[0]
67
+ if (!row) throw missing()
68
+ return {
69
+ id,
70
+ kind: row[0] as UploadKind,
71
+ size: Number(row[1]),
72
+ chunks: Number(row[2]),
73
+ received: Number(row[3]),
74
+ }
75
+ }
76
+
77
+ /** Stores piece `seq`; sending a piece again replaces it, so a retry is safe. */
78
+ export async function putChunk(
79
+ session: Session,
80
+ upload: Upload,
81
+ seq: number,
82
+ data: Uint8Array,
83
+ ): Promise<void> {
84
+ // Every piece holds a byte at least, so there are never more pieces than bytes.
85
+ if (!Number.isInteger(seq) || seq < 0 || seq >= Math.max(1, upload.size)) {
86
+ throw new DbAdminError('That piece of the upload is out of order.', 400, 'bad-chunk')
87
+ }
88
+ await session.query(
89
+ `INSERT INTO ${SCHEMA}.chunks (upload, seq, data) VALUES ($1, $2, $3)
90
+ ON CONFLICT (upload, seq) DO UPDATE SET data = EXCLUDED.data`,
91
+ [upload.id, seq, data],
92
+ )
93
+ const { rows } = await session.query(
94
+ `SELECT coalesce(sum(length(data)), 0) FROM ${SCHEMA}.chunks WHERE upload = $1`,
95
+ [upload.id],
96
+ )
97
+ if (Number(rows[0]![0]) > upload.size) {
98
+ throw new DbAdminError('The upload is bigger than it said it would be.', 400, 'bad-chunk')
99
+ }
100
+ }
101
+
102
+ /** Refuses an upload with pieces missing. */
103
+ export function complete(upload: Upload): void {
104
+ if (upload.received !== upload.size) {
105
+ throw new DbAdminError(
106
+ `The upload isn't complete: ${upload.received.toLocaleString('en')} of ${upload.size.toLocaleString('en')} bytes arrived. Start the restore again.`,
107
+ 400,
108
+ 'incomplete-upload',
109
+ )
110
+ }
111
+ }
112
+
113
+ /** The pieces in order, one at a time, so a big backup never sits in memory whole. */
114
+ export async function* chunks(session: Session, upload: Upload): AsyncGenerator<Uint8Array> {
115
+ for (let seq = 0; seq < upload.chunks; seq += 1) {
116
+ const { rows } = await session.query(
117
+ `SELECT data FROM ${SCHEMA}.chunks WHERE upload = $1 AND seq = $2`,
118
+ [upload.id, seq],
119
+ )
120
+ const hex = rows[0]?.[0]
121
+ if (hex === undefined || hex === null) {
122
+ throw new DbAdminError(`Piece ${seq + 1} of the upload is missing.`, 400, 'incomplete-upload')
123
+ }
124
+ // bytea comes back as \x and hex, its text form.
125
+ yield Buffer.from(hex.slice(2), 'hex')
126
+ }
127
+ }
128
+
129
+ /** Drops the upload, and the schema once nothing else waits in it. */
130
+ export async function discard(session: Session, id: string): Promise<void> {
131
+ const exists = await session.query(`SELECT 1 FROM pg_namespace WHERE nspname = $1`, [
132
+ STAGING_SCHEMA,
133
+ ])
134
+ if (!exists.rows.length) return
135
+ await session.query(
136
+ `DELETE FROM ${SCHEMA}.uploads WHERE id = $1 OR created < now() - interval '1 day'`,
137
+ [id],
138
+ )
139
+ const left = await session.query(`SELECT 1 FROM ${SCHEMA}.uploads LIMIT 1`)
140
+ if (!left.rows.length) await session.query(`DROP SCHEMA ${SCHEMA} CASCADE`)
141
+ }
142
+
143
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
package/src/browser.ts CHANGED
@@ -4,3 +4,8 @@
4
4
  */
5
5
  export type * from './types.ts'
6
6
  export type { UiConfig } from './ui.ts'
7
+ export type { BackupOptions } from './backup/api.ts'
8
+ export type { SchemaChoice } from './backup/dump.ts'
9
+ export type { BackupHeader, BackupSummary } from './backup/format.ts'
10
+ export type { PgTool } from './backup/pg-tools.ts'
11
+ export type { RestorePlan, RestoreResult } from './backup/restore.ts'
@@ -9,6 +9,7 @@ import type {
9
9
  ResultSet,
10
10
  RowsRequest,
11
11
  ServerInfo,
12
+ Session,
12
13
  TableDetail,
13
14
  TableSummary,
14
15
  } from '../types.ts'
@@ -282,6 +283,60 @@ class PGliteDriver implements Driver {
282
283
  }
283
284
  }
284
285
 
286
+ /**
287
+ * PGlite's exclusive transaction, held open until `end`: the host's queries wait meanwhile, so
288
+ * whoever opens it must end it, and soon.
289
+ */
290
+ session(mode: 'snapshot' | 'write'): Promise<Session> {
291
+ const client = this.#client
292
+ const parsers = () => this.#text
293
+ return new Promise<Session>((resolve, reject) => {
294
+ let opened = false
295
+ const done = client.transaction(async (tx) => {
296
+ if (mode === 'snapshot') {
297
+ await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY')
298
+ }
299
+ let decide!: (commit: boolean) => void
300
+ const decided = new Promise<boolean>((r) => (decide = r))
301
+ let ended = false
302
+ opened = true
303
+ resolve({
304
+ exclusive: true,
305
+ async query(sql, values) {
306
+ try {
307
+ const result = await tx.query(sql, values, { rowMode: 'array', parsers: parsers() })
308
+ return { rows: result.rows as (string | null)[][] }
309
+ } catch (error) {
310
+ throw toError(error)
311
+ }
312
+ },
313
+ async end(commit) {
314
+ if (ended) return
315
+ ended = true
316
+ decide(commit)
317
+ try {
318
+ await done
319
+ } catch (error) {
320
+ throw toError(error)
321
+ } finally {
322
+ // As after every write: nothing the session set (SET, locks) stays on the connection
323
+ // the host shares.
324
+ await client
325
+ .exec(mode === 'write' ? 'DISCARD ALL' : 'SELECT pg_advisory_unlock_all()')
326
+ .catch((error: unknown) =>
327
+ console.error('otw-db: could not reset the PGlite session', error),
328
+ )
329
+ }
330
+ },
331
+ })
332
+ if (!(await decided)) await tx.rollback()
333
+ })
334
+ done.catch((error: unknown) => {
335
+ if (!opened) reject(toError(error))
336
+ })
337
+ })
338
+ }
339
+
285
340
  /** The host owns the instance: nothing to close here. */
286
341
  async close(): Promise<void> {}
287
342
  }
@@ -29,6 +29,7 @@ import type {
29
29
  ResultSet,
30
30
  RowsRequest,
31
31
  ServerInfo,
32
+ Session,
32
33
  TableDetail,
33
34
  TableSummary,
34
35
  } from '../types.ts'
@@ -153,6 +154,7 @@ class PostgresDriver implements Driver {
153
154
  readonly kind = 'postgres'
154
155
  readonly capabilities: Capabilities = { schemas: true, transactionalDdl: true, cancel: true }
155
156
  readonly sql = { identifier: quote, literal }
157
+ readonly pgUrl: string
156
158
  readonly #url: string
157
159
  readonly #config: PoolConfig
158
160
  readonly #modules: PostgresModules | undefined
@@ -162,6 +164,7 @@ class PostgresDriver implements Driver {
162
164
 
163
165
  constructor(url: string, modules: PostgresModules | undefined) {
164
166
  this.#url = url
167
+ this.pgUrl = url
165
168
  this.#modules = modules
166
169
  this.#config = {
167
170
  connectionString: url,
@@ -420,6 +423,49 @@ class PostgresDriver implements Driver {
420
423
  }))
421
424
  }
422
425
 
426
+ /** A transaction on a connection of its own, closed after: a restore's SETs leave with it. */
427
+ async session(mode: 'snapshot' | 'write'): Promise<Session> {
428
+ const { client } = await this.#connect()
429
+ try {
430
+ await client.query(
431
+ mode === 'snapshot' ? 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY' : 'BEGIN',
432
+ )
433
+ } catch (error) {
434
+ client.release(true)
435
+ throw toError(error)
436
+ }
437
+ let ended = false
438
+ return {
439
+ exclusive: false,
440
+ async query(text, values) {
441
+ try {
442
+ const result = await client.query({
443
+ text,
444
+ values: values?.map((v) =>
445
+ v instanceof Uint8Array ? Buffer.from(v.buffer, v.byteOffset, v.byteLength) : v,
446
+ ),
447
+ rowMode: 'array',
448
+ types: AS_TEXT,
449
+ })
450
+ return { rows: result.rows as (string | null)[][] }
451
+ } catch (error) {
452
+ throw toError(error)
453
+ }
454
+ },
455
+ async end(commit) {
456
+ if (ended) return
457
+ ended = true
458
+ try {
459
+ await client.query(commit ? 'COMMIT' : 'ROLLBACK')
460
+ } catch (error) {
461
+ throw toError(error)
462
+ } finally {
463
+ client.release(true)
464
+ }
465
+ },
466
+ }
467
+ }
468
+
423
469
  async close(): Promise<void> {
424
470
  const opened = this.#pool
425
471
  this.#pool = undefined
package/src/handler.ts CHANGED
@@ -16,6 +16,7 @@ import type {
16
16
  Viewer,
17
17
  } from './types.ts'
18
18
  import { ROUTES } from './routes.ts'
19
+ import type * as BackupApi from './backup/api.ts'
19
20
  import { renderAsset, renderIndex, type UiAssets } from './ui.ts'
20
21
 
21
22
  /** What `createDbAdmin` needs: who may use the tool, the databases it may open, its limits. */
@@ -47,6 +48,11 @@ export interface DbAdminOptions {
47
48
  ui?: (() => Promise<UiAssets>) | false
48
49
  /** Where the app sends a browser the API turns away (401): the host's sign-in page. */
49
50
  signInUrl?: string
51
+ /** Backups and restores (PostgreSQL). A restore's upload waits in the database it restores. */
52
+ backups?: {
53
+ /** The biggest backup a restore takes, in bytes. Defaults to 1 GiB. */
54
+ maxRestoreBytes?: number
55
+ }
50
56
  }
51
57
 
52
58
  /**
@@ -137,6 +143,17 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
137
143
  const open = options.driver ?? openDriver
138
144
  const loadUi = options.ui === false ? undefined : (options.ui ?? defaultUi)
139
145
  let ui: Promise<UiAssets> | undefined
146
+ // Loaded on the first backup or restore: a host that never makes one never loads it.
147
+ let backupApi: Promise<typeof BackupApi> | undefined
148
+ const backups = () => (backupApi ??= import('./backup/api.ts'))
149
+ const maxRestoreBytes = options.backups?.maxRestoreBytes ?? 1_073_741_824
150
+ /** What a backup endpoint needs to know, from the connection it reached. */
151
+ const backupContext = (target: ReturnType<typeof reach>, viewer: Viewer) => ({
152
+ ...target,
153
+ viewer,
154
+ record,
155
+ maxRestoreBytes,
156
+ })
140
157
 
141
158
  function driver(connection: ConnectionConfig): Driver {
142
159
  let found = drivers.get(connection.name)
@@ -223,9 +240,11 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
223
240
  // A kind without a driver yet is listed, but can't be opened.
224
241
  let capabilities: Driver['capabilities'] | null = null
225
242
  try {
243
+ const opened = driver(connection)
226
244
  capabilities = {
227
- ...driver(connection).capabilities,
245
+ ...opened.capabilities,
228
246
  databases: opensOthers(connection),
247
+ backup: typeof opened.session === 'function',
229
248
  }
230
249
  } catch (error) {
231
250
  if (!(error instanceof DbAdminError)) throw error
@@ -515,6 +534,42 @@ export function createDbAdmin(options: DbAdminOptions): DbAdmin {
515
534
  })
516
535
  },
517
536
  },
537
+ {
538
+ method: 'GET',
539
+ path: '/api/backup-options',
540
+ async run(request, viewer) {
541
+ const params = new URL(request.url).searchParams
542
+ const target = reach(viewer, params.get('connection'), params.get('database'))
543
+ return (await backups()).options(backupContext(target, viewer))
544
+ },
545
+ },
546
+ ...(
547
+ [
548
+ ['/api/backup', 'download'],
549
+ ['/api/restore-plan', 'plan'],
550
+ ['/api/restore-start', 'start'],
551
+ ['/api/restore-run', 'run'],
552
+ ['/api/restore-discard', 'discard'],
553
+ ] as const
554
+ ).map(([path, action]) => ({
555
+ method: 'POST' as const,
556
+ path,
557
+ async run(request: Request, viewer: Viewer) {
558
+ const body = await json(request)
559
+ const target = reach(viewer, body.connection, body.database)
560
+ return (await backups())[action](backupContext(target, viewer), body)
561
+ },
562
+ })),
563
+ {
564
+ method: 'POST',
565
+ path: '/api/restore-chunk',
566
+ async run(request, viewer) {
567
+ // The body is the piece itself; the rest comes in the address.
568
+ const params = new URL(request.url).searchParams
569
+ const target = reach(viewer, params.get('connection'), params.get('database'))
570
+ return (await backups()).chunk(backupContext(target, viewer), request)
571
+ },
572
+ },
518
573
  {
519
574
  method: 'POST',
520
575
  path: '/api/cancel',
package/src/index.ts CHANGED
@@ -18,3 +18,9 @@ export {
18
18
  export { ROUTES } from './routes.ts'
19
19
  export { renderAsset, renderIndex, type UiAssets, type UiConfig } from './ui.ts'
20
20
  export type * from './types.ts'
21
+ // Types only: the backup code itself loads on the first backup or restore.
22
+ export type { BackupOptions } from './backup/api.ts'
23
+ export type { SchemaChoice } from './backup/dump.ts'
24
+ export type { BackupHeader, BackupSummary } from './backup/format.ts'
25
+ export type { PgTool } from './backup/pg-tools.ts'
26
+ export type { RestorePlan, RestoreResult } from './backup/restore.ts'