@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,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'
@@ -15,9 +15,10 @@ const SCHEMES: Record<string, DriverKind> = {
15
15
 
16
16
  /**
17
17
  * Connections from the environment: `DB_ADMIN_<NAME>_URL`, with `DB_ADMIN_<NAME>_ACCESS`
18
- * (`read`, the default, or `write`), `DB_ADMIN_<NAME>_LABEL` and `DB_ADMIN_<NAME>_TAG` (`local`,
19
- * `development`, `testing`, `staging` or `production`). `DB_ADMIN_SHOP_DATA_URL` becomes the
20
- * connection `shop-data`. Sorted by name; an empty URL is skipped.
18
+ * (`read`, the default, or `write`), `DB_ADMIN_<NAME>_LABEL`, `DB_ADMIN_<NAME>_TAG` (`local`,
19
+ * `development`, `testing`, `staging` or `production`) and `DB_ADMIN_<NAME>_DATABASES` (`all`, the
20
+ * default, or `one`: the URL's database only). `DB_ADMIN_SHOP_DATA_URL` becomes the connection
21
+ * `shop-data`. Sorted by name; an empty URL is skipped.
21
22
  */
22
23
  export function connectionsFromEnv(env: Env = process.env): ConnectionConfig[] {
23
24
  const connections: ConnectionConfig[] = []
@@ -29,12 +30,14 @@ export function connectionsFromEnv(env: Env = process.env): ConnectionConfig[] {
29
30
  driverKind(url, variable)
30
31
  const label = env[`${prefix}_LABEL`]?.trim()
31
32
  const tag = tagOf(env, `${prefix}_TAG`)
33
+ const databases = databasesOf(env, `${prefix}_DATABASES`)
32
34
  connections.push({
33
35
  name: match[1]!.toLowerCase().replaceAll('_', '-'),
34
36
  url,
35
37
  access: access(env, `${prefix}_ACCESS`),
36
38
  ...(label ? { label } : {}),
37
39
  ...(tag ? { tag } : {}),
40
+ ...(databases ? { databases } : {}),
38
41
  })
39
42
  }
40
43
  return connections.sort((a, b) => a.name.localeCompare(b.name))
@@ -46,6 +49,13 @@ function access(env: Env, variable: string): Access {
46
49
  throw new Error(`${variable} must be "read" or "write", not "${env[variable]}".`)
47
50
  }
48
51
 
52
+ function databasesOf(env: Env, variable: string): 'all' | 'one' | undefined {
53
+ const value = env[variable]?.trim()
54
+ if (!value) return undefined
55
+ if (value === 'all' || value === 'one') return value
56
+ throw new Error(`${variable} must be "all" or "one", not "${env[variable]}".`)
57
+ }
58
+
49
59
  function tagOf(env: Env, variable: string): ConnectionTag | undefined {
50
60
  const value = env[variable]?.trim()
51
61
  if (!value) return undefined
@@ -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
  }
@@ -79,6 +79,17 @@ export const TABLE_SQL = `SELECT n.nspname AS schema, c.relname AS name, c.relki
79
79
  export const INFO_SQL = `SELECT current_setting('server_version') AS version, current_database() AS database,
80
80
  current_user AS user`
81
81
 
82
+ /**
83
+ * The databases the login may connect to, the current one always among them: no templates, none
84
+ * that refuse connections, none a failed DROP DATABASE left invalid (a connection limit of -2).
85
+ */
86
+ export const DATABASES_SQL = `SELECT datname AS name, datname = current_database() AS current
87
+ FROM pg_database
88
+ WHERE datname = current_database()
89
+ OR (datallowconn AND NOT datistemplate AND datconnlimit <> -2
90
+ AND has_database_privilege(oid, 'CONNECT'))
91
+ ORDER BY lower(datname), datname`
92
+
82
93
  /** Names for type OIDs: $1 an array of them. */
83
94
  export const TYPE_NAMES_SQL =
84
95
  'SELECT oid::text AS oid, format_type(oid, NULL) AS name FROM pg_type WHERE oid = ANY($1::oid[])'