@otwdesign/db-core 1.3.1 → 1.4.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 (72) hide show
  1. package/dist/backup/api.js +67 -9
  2. package/dist/backup/api.js.map +1 -1
  3. package/dist/backup/catalog.d.ts +9 -2
  4. package/dist/backup/catalog.js +42 -18
  5. package/dist/backup/catalog.js.map +1 -1
  6. package/dist/backup/dump.d.ts +6 -2
  7. package/dist/backup/dump.js +188 -20
  8. package/dist/backup/dump.js.map +1 -1
  9. package/dist/backup/restore.d.ts +9 -1
  10. package/dist/backup/restore.js +131 -11
  11. package/dist/backup/restore.js.map +1 -1
  12. package/dist/backup/split.d.ts +7 -2
  13. package/dist/backup/split.js +38 -6
  14. package/dist/backup/split.js.map +1 -1
  15. package/dist/backup/staging.d.ts +6 -1
  16. package/dist/backup/staging.js +38 -10
  17. package/dist/backup/staging.js.map +1 -1
  18. package/dist/drivers/mysql.d.ts +6 -0
  19. package/dist/drivers/mysql.js +142 -18
  20. package/dist/drivers/mysql.js.map +1 -1
  21. package/dist/drivers/pglite.d.ts +18 -3
  22. package/dist/drivers/pglite.js +357 -55
  23. package/dist/drivers/pglite.js.map +1 -1
  24. package/dist/drivers/postgres-catalog.d.ts +16 -1
  25. package/dist/drivers/postgres-catalog.js +34 -0
  26. package/dist/drivers/postgres-catalog.js.map +1 -1
  27. package/dist/drivers/postgres.d.ts +10 -0
  28. package/dist/drivers/postgres.js +203 -29
  29. package/dist/drivers/postgres.js.map +1 -1
  30. package/dist/drivers/read-only.d.ts +4 -0
  31. package/dist/drivers/read-only.js +156 -0
  32. package/dist/drivers/read-only.js.map +1 -0
  33. package/dist/drivers/sql.d.ts +51 -4
  34. package/dist/drivers/sql.js +112 -35
  35. package/dist/drivers/sql.js.map +1 -1
  36. package/dist/drivers/sqlite.d.ts +33 -1
  37. package/dist/drivers/sqlite.js +645 -69
  38. package/dist/drivers/sqlite.js.map +1 -1
  39. package/dist/export.d.ts +4 -5
  40. package/dist/export.js +21 -3
  41. package/dist/export.js.map +1 -1
  42. package/dist/format.js +7 -1
  43. package/dist/format.js.map +1 -1
  44. package/dist/handler.js +37 -15
  45. package/dist/handler.js.map +1 -1
  46. package/dist/index.d.ts +2 -2
  47. package/dist/index.js +1 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/types.d.ts +37 -3
  50. package/dist/words.d.ts +19 -0
  51. package/dist/words.js +76 -0
  52. package/dist/words.js.map +1 -0
  53. package/package.json +8 -7
  54. package/src/backup/api.ts +82 -14
  55. package/src/backup/catalog.ts +43 -18
  56. package/src/backup/dump.ts +208 -21
  57. package/src/backup/restore.ts +152 -12
  58. package/src/backup/split.ts +38 -6
  59. package/src/backup/staging.ts +51 -10
  60. package/src/drivers/mysql.ts +171 -21
  61. package/src/drivers/pglite.ts +419 -56
  62. package/src/drivers/postgres-catalog.ts +51 -1
  63. package/src/drivers/postgres.ts +241 -33
  64. package/src/drivers/read-only.ts +174 -0
  65. package/src/drivers/sql.ts +170 -37
  66. package/src/drivers/sqlite.ts +739 -98
  67. package/src/export.ts +26 -6
  68. package/src/format.ts +9 -1
  69. package/src/handler.ts +55 -19
  70. package/src/index.ts +7 -2
  71. package/src/types.ts +38 -1
  72. package/src/words.ts +67 -0
@@ -1,9 +1,12 @@
1
1
  import { DbAdminError, QueryError } from '../errors.ts'
2
+ import { leadingWord } from '../words.ts'
3
+ import { refuseBeyondReadingPostgres } from './read-only.ts'
2
4
  import type {
3
5
  ApplyResult,
4
6
  Capabilities,
5
7
  Change,
6
8
  Driver,
9
+ ExportColumn,
7
10
  QueryOptions,
8
11
  QueryResult,
9
12
  ResultSet,
@@ -16,9 +19,11 @@ import type {
16
19
  import {
17
20
  detail,
18
21
  dialect,
22
+ EXPORT_COLUMNS_SQL,
23
+ exportColumns,
19
24
  INFO_SQL,
20
- literal,
21
25
  quote,
26
+ sqlDialect,
22
27
  summary,
23
28
  TABLE_SQL,
24
29
  TABLES_SQL,
@@ -27,7 +32,16 @@ import {
27
32
  type CatalogDetail,
28
33
  type CatalogTable,
29
34
  } from './postgres-catalog.ts'
30
- import { changeStatement, orderBy, Parameters, where, whole } from './sql.ts'
35
+ import {
36
+ changeStatement,
37
+ EXPORT_IDLE_MS,
38
+ orderBy,
39
+ Parameters,
40
+ refuseChanged,
41
+ stalledExport,
42
+ where,
43
+ whole,
44
+ } from './sql.ts'
31
45
 
32
46
  /** What this driver uses of a PGlite instance: shapes only, so the core needs no PGlite. */
33
47
  export interface PGliteQueryable {
@@ -37,6 +51,7 @@ export interface PGliteQueryable {
37
51
  options?: {
38
52
  rowMode?: 'array' | 'object'
39
53
  parsers?: Record<number, (value: string) => unknown>
54
+ serializers?: Record<number, (value: unknown) => string>
40
55
  },
41
56
  ): Promise<{
42
57
  rows: unknown[]
@@ -50,41 +65,252 @@ export interface PGliteQueryable {
50
65
  export interface PGliteLike extends PGliteQueryable {
51
66
  /** Its parsers by type OID: the types it would turn into JavaScript values. */
52
67
  parsers: Record<number, unknown>
68
+ /** How it writes a JavaScript value of each type for the server, by type OID. */
69
+ serializers?: Record<number | string, (value: never) => string>
53
70
  /** Runs alone: the host's own queries wait until it's done. */
54
71
  transaction<T>(
55
72
  callback: (tx: PGliteQueryable & { rollback(): Promise<void> }) => Promise<T>,
56
73
  ): Promise<T>
74
+ /** Whether a transaction is open, as the server last said. Not every version has it. */
75
+ isInTransaction?(): boolean
57
76
  }
58
77
 
59
78
  const asIs = (value: string) => value
60
79
 
61
80
  const NOT_IN_TRANSACTION = '25001'
62
81
  const EXPORT_BATCH = 1_000
82
+ const CURSOR = 'otw_db_cursor'
83
+ const FIX = 'otw_db_fix'
84
+
85
+ /** The statements a cursor can read from, past the comments and brackets before them. */
86
+ const READS_ROWS = new Set(['SELECT', 'WITH', 'VALUES', 'TABLE'])
87
+
88
+ /**
89
+ * What a statement can leave on a session past its own transaction. The host shares the one
90
+ * connection, so all of it is the host's to find again as it left it: its settings (search_path,
91
+ * a role), its temporary tables, prepared statements, cursors, LISTENs and advisory locks.
92
+ */
93
+ interface SessionState {
94
+ /** The settings SET for the session, by name, and always `role` and `session_authorization`. */
95
+ settings: Record<string, string>
96
+ temp: { oid: number; drop: string }[]
97
+ prepared: string[]
98
+ cursors: string[]
99
+ channels: string[]
100
+ /** Advisory locks as pg_locks has them: classid, objid, objsubid, mode. */
101
+ locks: [number, number, number, string][]
102
+ /**
103
+ * Settings no catalog lists, a plugin's or an app's own (`app.tenant`), by the names a
104
+ * statement's text gives; null for one that was never set.
105
+ */
106
+ custom?: Record<string, string | null> | null
107
+ }
108
+
109
+ /** What a session holds, with a place (CUSTOM) for one more thing to ask. */
110
+ const STATE_SQL = `SELECT json_build_object(
111
+ 'settings', (SELECT json_object_agg(s.name, s.setting) FROM (
112
+ SELECT name, setting FROM pg_catalog.pg_settings WHERE source = 'session'
113
+ -- Who the session runs as: pg_settings leaves these two out.
114
+ UNION ALL SELECT 'role', current_setting('role')
115
+ UNION ALL SELECT 'session_authorization', session_user::text) s),
116
+ 'temp', (SELECT coalesce(json_agg(json_build_object('oid', c.oid::bigint, 'drop',
117
+ format('DROP %s IF EXISTS pg_temp.%I CASCADE', CASE c.relkind WHEN 'v' THEN 'VIEW'
118
+ WHEN 'm' THEN 'MATERIALIZED VIEW' WHEN 'S' THEN 'SEQUENCE' WHEN 'f' THEN 'FOREIGN TABLE'
119
+ ELSE 'TABLE' END, c.relname))), '[]')
120
+ FROM pg_catalog.pg_class c
121
+ WHERE c.relnamespace = pg_catalog.pg_my_temp_schema() AND c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')),
122
+ 'prepared', (SELECT coalesce(json_agg(name), '[]') FROM pg_catalog.pg_prepared_statements),
123
+ 'cursors', (SELECT coalesce(json_agg(name), '[]') FROM pg_catalog.pg_cursors),
124
+ 'channels', (SELECT coalesce(json_agg(c), '[]') FROM pg_catalog.pg_listening_channels() c),
125
+ 'locks', (SELECT coalesce(json_agg(json_build_array(classid::bigint, objid::bigint, objsubid, mode)), '[]')
126
+ FROM pg_catalog.pg_locks
127
+ WHERE locktype = 'advisory' AND pid = pg_catalog.pg_backend_pid() AND granted)CUSTOM)::text`
128
+
129
+ /** The same, with the settings named in $1 beside it: asked only of a statement that names some. */
130
+ const STATE_AND_CUSTOM_SQL = STATE_SQL.replace(
131
+ 'CUSTOM',
132
+ `, 'custom', (SELECT json_object_agg(n, pg_catalog.current_setting(n, true)) FROM unnest($1::text[]) n)`,
133
+ )
134
+ const STATE_ONLY_SQL = STATE_SQL.replace('CUSTOM', '')
135
+
136
+ /** A setting's name, as RESET takes it: `search_path`, or an extension's `app.tenant`. */
137
+ const SETTING = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_$]*)*$/
138
+
139
+ async function sessionState(
140
+ on: PGliteQueryable,
141
+ custom: readonly string[] = [],
142
+ ): Promise<SessionState> {
143
+ const { rows } = custom.length
144
+ ? await on.query(STATE_AND_CUSTOM_SQL, [custom], { rowMode: 'array', parsers: {} })
145
+ : await on.query(STATE_ONLY_SQL, [], { rowMode: 'array', parsers: {} })
146
+ return JSON.parse((rows as [string][])[0]![0]) as SessionState
147
+ }
148
+
149
+ /**
150
+ * The names in a statement that could be settings of a plugin's or an app's own: words with a
151
+ * dot between them, as `app.tenant` is, and as `public.users` is too, which costs nothing to ask
152
+ * after. pg_settings has none of them, so what a statement set can only be found by name.
153
+ */
154
+ function customSettings(sql: string): string[] {
155
+ const names = new Set<string>()
156
+ // From a word's first letter only: tried from every letter of a word of megabytes, a
157
+ // pattern that then finds no dot would read the rest of the word each time.
158
+ for (const [name] of sql.matchAll(
159
+ /(?<![A-Za-z0-9_$])[A-Za-z_][A-Za-z0-9_]*(?:"?\s*\.\s*"?[A-Za-z_][A-Za-z0-9_$]*)+/g,
160
+ )) {
161
+ const plain = name.replace(/["\s]/g, '').toLowerCase()
162
+ if (SETTING.test(plain)) names.add(plain)
163
+ if (names.size === 64) break
164
+ }
165
+ return [...names]
166
+ }
167
+
168
+ /** One statement that puts something of a session back. */
169
+ interface Fix {
170
+ sql: string
171
+ values?: unknown[]
172
+ /** It undoes what a rollback doesn't: a prepared statement, a session's lock. */
173
+ outlasts?: boolean
174
+ }
175
+
176
+ /**
177
+ * The statements that put a session back as `before` has it, from how it is `now`. `listens`:
178
+ * inside a transaction about to commit, where a LISTEN it ran doesn't show yet.
179
+ */
180
+ function repairs(before: SessionState, now: SessionState, listens: boolean): Fix[] {
181
+ const fixes: Fix[] = []
182
+ // Who the session runs as comes first: the rest may need the host's own privileges.
183
+ const first = ['session_authorization', 'role']
184
+ const names = [...new Set([...Object.keys(before.settings), ...Object.keys(now.settings)])].sort(
185
+ (a, b) => first.indexOf(b) - first.indexOf(a),
186
+ )
187
+ for (const name of names) {
188
+ const was = before.settings[name]
189
+ if (was === now.settings[name]) continue
190
+ if (was !== undefined)
191
+ fixes.push({ sql: 'SELECT set_config($1, $2, false)', values: [name, was] })
192
+ else if (SETTING.test(name)) fixes.push({ sql: `RESET ${name}` })
193
+ }
194
+ for (const [name, was] of Object.entries(before.custom ?? {})) {
195
+ if (was === (now.custom ?? {})[name]) continue
196
+ if (was !== null) fixes.push({ sql: 'SELECT set_config($1, $2, false)', values: [name, was] })
197
+ else if (SETTING.test(name)) fixes.push({ sql: `RESET ${name}` })
198
+ }
199
+ const had = new Set(before.temp.map((t) => t.oid))
200
+ for (const made of now.temp) if (!had.has(made.oid)) fixes.push({ sql: made.drop })
201
+ const added = (list: (s: SessionState) => string[]) =>
202
+ list(now).filter((name) => !list(before).includes(name))
203
+ for (const name of added((s) => s.cursors)) fixes.push({ sql: `CLOSE ${quote(name)}` })
204
+ for (const name of added((s) => s.prepared))
205
+ fixes.push({ sql: `DEALLOCATE ${quote(name)}`, outlasts: true })
206
+ if (listens) {
207
+ // What the transaction listened to isn't listed until it commits: all of it goes, and the
208
+ // host's own channels are listened to again, in the same commit.
209
+ fixes.push({ sql: 'UNLISTEN *' })
210
+ for (const name of before.channels) fixes.push({ sql: `LISTEN ${quote(name)}` })
211
+ } else {
212
+ for (const name of added((s) => s.channels)) fixes.push({ sql: `UNLISTEN ${quote(name)}` })
213
+ // And those it stopped listening to (UNLISTEN, DISCARD ALL) are listened to again.
214
+ for (const name of before.channels) {
215
+ if (!now.channels.includes(name)) fixes.push({ sql: `LISTEN ${quote(name)}` })
216
+ }
217
+ }
218
+ const held = new Set(before.locks.map((l) => l.join(' ')))
219
+ const taken = now.locks.filter((l) => !held.has(l.join(' ')))
220
+ if (taken.length && !before.locks.length)
221
+ fixes.push({ sql: 'SELECT pg_advisory_unlock_all()', outlasts: true })
222
+ else {
223
+ for (const [classid, objid, objsubid, mode] of taken) {
224
+ const shared = mode === 'ShareLock' ? '_shared' : ''
225
+ // One key of 64 bits (objsubid 1), or two of 32: as pg_locks splits them.
226
+ const key =
227
+ objsubid === 1
228
+ ? '($1::bigint << 32) | $2::bigint'
229
+ : '$1::bigint::oid::int4, $2::bigint::oid::int4'
230
+ // Taken more than once, it's let go as often: until PostgreSQL says it wasn't held.
231
+ fixes.push({
232
+ sql: `SELECT count(*) FROM generate_series(1, 1000) WHERE pg_advisory_unlock${shared}(${key})`,
233
+ values: [classid, objid],
234
+ outlasts: true,
235
+ })
236
+ }
237
+ }
238
+ return fixes
239
+ }
240
+
241
+ /**
242
+ * Puts the session back as `before` has it. Always while the host's queries are still waiting
243
+ * for the statement's transaction: what they set the moment it ends is theirs, and seen from
244
+ * after it, nothing would tell it from what the statement left. Inside a transaction
245
+ * (`savepoints`), each fix is on its own savepoint, so one that fails doesn't take the
246
+ * transaction's work with it.
247
+ */
248
+ async function restoreSession(
249
+ on: PGliteQueryable,
250
+ before: SessionState,
251
+ savepoints: boolean,
252
+ /** `listens`: see repairs. `outlasting`: only what the rollback about to come won't undo. */
253
+ { listens = false, outlasting = false }: { listens?: boolean; outlasting?: boolean } = {},
254
+ ): Promise<void> {
255
+ const now = await sessionState(on, Object.keys(before.custom ?? {}))
256
+ for (const fix of repairs(before, now, listens)) {
257
+ if (outlasting && !fix.outlasts) continue
258
+ try {
259
+ if (savepoints) await on.query(`SAVEPOINT ${FIX}`)
260
+ await on.query(fix.sql, fix.values)
261
+ if (savepoints) await on.query(`RELEASE SAVEPOINT ${FIX}`)
262
+ } catch (error) {
263
+ console.error(`otw-db: could not reset the PGlite session (${fix.sql})`, error)
264
+ if (savepoints) await on.query(`ROLLBACK TO SAVEPOINT ${FIX}`)
265
+ }
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Rolls back the transaction `tx` is in and leaves it usable, outside any transaction but still
271
+ * PGlite's exclusive one: nothing of the host's runs until its callback returns.
272
+ */
273
+ async function undo(tx: PGliteQueryable): Promise<void> {
274
+ await tx.query('ROLLBACK')
275
+ }
63
276
 
64
277
  /**
65
278
  * A driver for a PGlite database a host already has open, such as an OTW CMS site's embedded one:
66
279
  * PGlite takes one process, so the tool uses the host's instance rather than opening the files.
67
280
  * Each statement runs in PGlite's exclusive transaction, so it never interleaves with the host's
68
- * queries; reads roll back; a write is followed by DISCARD ALL, so nothing it set (SET, SET ROLE,
69
- * temporary tables, session locks) stays on the connection the host shares.
281
+ * queries; reads roll back. The connection is the host's own, so after someone's statement the
282
+ * session is put back as the host had it: what the statement set (SET, SET ROLE, temporary
283
+ * tables, LISTEN, session locks) is undone before the host's next query, and what the host set
284
+ * is left alone.
70
285
  *
71
286
  * PGlite runs on the host's own thread and can't be interrupted: a heavy statement holds the host
72
287
  * until it finishes. Tell people so where they choose this connection.
73
288
  */
74
- export function pgliteDriver(client: PGliteLike): Driver {
75
- return new PGliteDriver(client)
289
+ export function pgliteDriver(client: PGliteLike, options: PGliteOptions = {}): Driver {
290
+ return new PGliteDriver(client, options)
291
+ }
292
+
293
+ /** How the PGlite driver behaves, where the defaults don't suit. */
294
+ export interface PGliteOptions {
295
+ /**
296
+ * How long an export may sit between two batches, its rows unread, before it's ended and the
297
+ * rows the database kept for it are let go. Defaults to 5 minutes.
298
+ */
299
+ exportIdleMs?: number
76
300
  }
77
301
 
78
302
  class PGliteDriver implements Driver {
79
303
  readonly kind = 'postgres'
80
304
  readonly capabilities: Capabilities = { schemas: true, transactionalDdl: true, cancel: false }
81
- readonly sql = { identifier: quote, literal }
305
+ readonly sql = sqlDialect
82
306
  readonly #client: PGliteLike
307
+ readonly #exportIdleMs: number
83
308
  readonly #typeNames = new Map<number, string>()
84
309
  #asText: Record<number, (value: string) => unknown> = {}
85
310
 
86
- constructor(client: PGliteLike) {
311
+ constructor(client: PGliteLike, options: PGliteOptions) {
87
312
  this.#client = client
313
+ this.#exportIdleMs = options.exportIdleMs ?? EXPORT_IDLE_MS
88
314
  }
89
315
 
90
316
  /**
@@ -99,7 +325,25 @@ class PGliteDriver implements Driver {
99
325
  return this.#asText
100
326
  }
101
327
 
102
- /** One statement in a read-only transaction that rolls back. */
328
+ /**
329
+ * How a parameter is written for the server. PGlite's own way wants a JavaScript value of the
330
+ * parameter's type: a Uint8Array for bytea, and it refuses text. The grid has every value as
331
+ * the server's own text, which the server reads as any type: so text goes as it is, a list of
332
+ * text (a filter's IN) as an array of it, and anything else as PGlite would write it.
333
+ */
334
+ readonly #asGiven = new Proxy({} as Record<number, (value: unknown) => string>, {
335
+ get: (_, oid) => (value: unknown) => {
336
+ if (typeof value === 'string') return value
337
+ if (Array.isArray(value) && value.every((v) => typeof v === 'string')) {
338
+ return `{${value.map((v: string) => `"${v.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`).join(',')}}`
339
+ }
340
+ const own = this.#client.serializers?.[oid as string] as
341
+ ((value: unknown) => string) | undefined
342
+ return own ? own(value) : String(value)
343
+ },
344
+ })
345
+
346
+ /** One of the driver's own statements, in a read-only transaction that rolls back. */
103
347
  async #read(
104
348
  sql: string,
105
349
  params: unknown[] = [],
@@ -107,21 +351,43 @@ class PGliteDriver implements Driver {
107
351
  timeoutMs = 30_000,
108
352
  ) {
109
353
  try {
110
- const result = await this.#client.transaction(async (tx) => {
354
+ return await this.#client.transaction(async (tx) => {
111
355
  await tx.query('SET TRANSACTION READ ONLY')
112
356
  await tx.query(`SET LOCAL statement_timeout = ${whole(timeoutMs)}`)
113
- const answer = await tx.query(sql, params, { rowMode, parsers: this.#text })
357
+ const answer = await tx.query(sql, params, {
358
+ rowMode,
359
+ parsers: this.#text,
360
+ serializers: this.#asGiven,
361
+ })
114
362
  await tx.rollback()
115
363
  return answer
116
364
  })
117
- // Session advisory locks outlast a rollback.
118
- await this.#client.query('SELECT pg_advisory_unlock_all()')
119
- return result
120
365
  } catch (error) {
121
366
  throw toError(error)
122
367
  }
123
368
  }
124
369
 
370
+ /**
371
+ * Someone's statement, read through a cursor where it's one a cursor takes, so only the rows
372
+ * that will be shown (and one more, to say there are more) are built in the host's memory.
373
+ * PGlite hands a query's whole result over at once, in the host's process: a million rows asked
374
+ * for are a million rows held. What a cursor can't read (SHOW, EXPLAIN, INSERT … RETURNING)
375
+ * runs as it is, and so does a statement PostgreSQL refuses, so its error says where in the
376
+ * person's own SQL it is.
377
+ */
378
+ async #limited(tx: PGliteQueryable, sql: string, maxRows: number) {
379
+ const options = { rowMode: 'array' as const, parsers: this.#text }
380
+ if (!READS_ROWS.has(leadingWord(sql))) return tx.query(sql, [], options)
381
+ await tx.query(`SAVEPOINT ${CURSOR}`)
382
+ try {
383
+ await tx.query(`DECLARE ${CURSOR} NO SCROLL CURSOR FOR ${sql}`)
384
+ } catch {
385
+ await tx.query(`ROLLBACK TO SAVEPOINT ${CURSOR}`)
386
+ return tx.query(sql, [], options)
387
+ }
388
+ return tx.query(`FETCH ${whole(maxRows) + 1} FROM ${CURSOR}`, [], options)
389
+ }
390
+
125
391
  async #named(fields: { name: string; dataTypeID: number }[]) {
126
392
  const unknown = [...new Set(fields.map((f) => f.dataTypeID))].filter(
127
393
  (oid) => !this.#typeNames.has(oid),
@@ -182,34 +448,61 @@ class PGliteDriver implements Driver {
182
448
 
183
449
  /**
184
450
  * One statement. Reads in a read-only transaction that rolls back; writes in one that commits,
185
- * or alone where PostgreSQL refuses one (VACUUM), then DISCARD ALL.
451
+ * or alone where PostgreSQL refuses one (VACUUM). Either way the session is then as the host
452
+ * had it.
186
453
  */
187
454
  async query(sql: string, options: QueryOptions): Promise<QueryResult> {
188
455
  if (options.signal?.aborted) throw new DbAdminError('The query was canceled.', 409, 'canceled')
189
456
  const started = performance.now()
457
+ const write = options.access !== 'read'
458
+ if (!write) refuseBeyondReadingPostgres(sql)
190
459
  let result
191
- if (options.access === 'read') {
192
- result = await this.#read(sql, [], 'array', options.timeoutMs)
193
- } else {
194
- try {
195
- result = await this.#client.transaction(async (tx) => {
196
- await tx.query(`SET LOCAL statement_timeout = ${whole(options.timeoutMs)}`)
197
- return tx.query(sql, [], { rowMode: 'array', parsers: this.#text })
198
- })
199
- } catch (error) {
200
- if ((error as { code?: string }).code !== NOT_IN_TRANSACTION) throw toError(error)
201
- result = await this.#client
202
- .query(sql, [], { rowMode: 'array', parsers: this.#text })
203
- .catch((e: unknown) => {
204
- throw toError(e)
205
- })
206
- } finally {
207
- await this.#client
208
- .exec('DISCARD ALL')
209
- .catch((error: unknown) =>
460
+ try {
461
+ result = await this.#client.transaction(async (tx) => {
462
+ // Before anything is set: SET LOCAL would read as the session's own.
463
+ const before = await sessionState(tx, customSettings(sql))
464
+ if (!write) await tx.query('SET TRANSACTION READ ONLY')
465
+ await tx.query(`SET LOCAL statement_timeout = ${whole(options.timeoutMs)}`)
466
+ let answer
467
+ let failure: unknown
468
+ try {
469
+ answer = await this.#limited(tx, sql, options.maxRows)
470
+ } catch (error) {
471
+ failure = error
472
+ }
473
+ if (failure === undefined) {
474
+ if (write) {
475
+ // Committed with the statement, so the host's next query already finds its own.
476
+ await restoreSession(tx, before, true, { listens: /listen/i.test(sql) })
477
+ } else {
478
+ // A read is rolled back, which undoes all but a prepared statement and a session's
479
+ // lock: those go first, in here, while the host's queries still wait.
480
+ await restoreSession(tx, before, true, { outlasting: true })
481
+ await tx.rollback()
482
+ }
483
+ return answer!
484
+ }
485
+ // A statement that failed leaves a transaction that takes no more: undone here by
486
+ // hand, and then what that doesn't undo is put back, still in the host's way. PGlite
487
+ // rolls back after this, and finds nothing to: that's all.
488
+ const repair = () =>
489
+ restoreSession(tx, before, false).catch((error: unknown) =>
210
490
  console.error('otw-db: could not reset the PGlite session', error),
211
491
  )
212
- }
492
+ await undo(tx)
493
+ await repair()
494
+ if (!write || (failure as { code?: string }).code !== NOT_IN_TRANSACTION) throw failure
495
+ // What refuses a transaction (VACUUM, DISCARD ALL) runs alone, here, where no
496
+ // transaction is open any more and the host still waits: DISCARD ALL resets what the
497
+ // host set, which is then put back before its next query.
498
+ try {
499
+ return await tx.query(sql, [], { rowMode: 'array', parsers: this.#text })
500
+ } finally {
501
+ await repair()
502
+ }
503
+ })
504
+ } catch (error) {
505
+ throw toError(error)
213
506
  }
214
507
  const rows = result.rows as (string | null)[][]
215
508
  const truncated = rows.length > options.maxRows
@@ -217,9 +510,7 @@ class PGliteDriver implements Driver {
217
510
  columns: await this.#named(result.fields),
218
511
  rows: truncated ? rows.slice(0, options.maxRows) : rows,
219
512
  truncated,
220
- command: (
221
- /^\s*(?:--[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*(\w+)/.exec(sql)?.[1] ?? ''
222
- ).toUpperCase(),
513
+ command: leadingWord(sql),
223
514
  affectedRows: result.fields.length
224
515
  ? truncated
225
516
  ? null
@@ -243,7 +534,18 @@ class PGliteDriver implements Driver {
243
534
  await this.#client.transaction(async (tx) => {
244
535
  await tx.query(`SET LOCAL statement_timeout = ${whole(timeoutMs)}`)
245
536
  for (const statement of statements) {
246
- const { affectedRows } = await tx.query(statement.text, statement.values)
537
+ if (statement.check) {
538
+ // As the grid read them: every value the server's own text.
539
+ const { rows } = await tx.query(statement.check.text, statement.check.values, {
540
+ rowMode: 'array',
541
+ parsers: this.#text,
542
+ serializers: this.#asGiven,
543
+ })
544
+ refuseChanged(dialect, statement, rows[0] as (string | null)[] | undefined)
545
+ }
546
+ const { affectedRows } = await tx.query(statement.text, statement.values, {
547
+ serializers: this.#asGiven,
548
+ })
247
549
  if (statement.oneRow && affectedRows !== 1) {
248
550
  const why =
249
551
  affectedRows === 0
@@ -271,15 +573,68 @@ class PGliteDriver implements Driver {
271
573
  order = [],
272
574
  }: Pick<RowsRequest, 'schema' | 'table' | 'filters' | 'order'>,
273
575
  { timeoutMs }: { timeoutMs: number },
274
- ): AsyncGenerator<{ columns: { name: string }[]; rows: (string | null)[][] }> {
576
+ ): AsyncGenerator<{ columns: ExportColumn[]; rows: (string | null)[][] }> {
275
577
  const parameters = new Parameters(dialect)
276
578
  const sql = `SELECT * FROM ${quote(schema)}.${quote(table)}${where(dialect, filters, parameters)}${orderBy(dialect, order)}`
277
- // PGlite has no cursor to read from bit by bit: the rows come at once, then go out in batches.
278
- const { rows, fields } = await this.#read(sql, parameters.values, 'array', timeoutMs)
279
- const columns = fields.map((f) => ({ name: f.name }))
280
- const list = rows as (string | null)[][]
281
- for (let at = 0; at === 0 || at < list.length; at += EXPORT_BATCH) {
282
- yield { columns, rows: list.slice(at, at + EXPORT_BATCH) }
579
+ const catalog = await this.#read(EXPORT_COLUMNS_SQL, [schema, table], 'array', timeoutMs)
580
+ // A cursor WITH HOLD, declared in a read-only transaction that ends at once: the database
581
+ // keeps the rows as they were at that moment, on its own side, and hands them over a batch
582
+ // at a time. Asked for whole, they would all be built in the host's memory at once; read
583
+ // through a cursor inside one transaction, they would hold the host's queries for as long
584
+ // as the file takes to download.
585
+ const cursor = `otw_db_export_${crypto.randomUUID().replaceAll('-', '')}`
586
+ const close = () => this.#client.query(`CLOSE ${cursor}`).catch(() => {})
587
+ try {
588
+ await this.#client.transaction(async (tx) => {
589
+ await tx.query('SET TRANSACTION READ ONLY')
590
+ await tx.query(`SET LOCAL statement_timeout = ${whole(timeoutMs)}`)
591
+ await tx.query(
592
+ `DECLARE ${cursor} NO SCROLL CURSOR WITH HOLD FOR ${sql}`,
593
+ parameters.values,
594
+ {
595
+ serializers: this.#asGiven,
596
+ },
597
+ )
598
+ })
599
+ } catch (error) {
600
+ throw toError(error)
601
+ }
602
+ // Nobody reading, the rows kept for the export would stay in the host's database for good.
603
+ let stalled = false
604
+ const stall = () => {
605
+ stalled = true
606
+ void close()
607
+ }
608
+ try {
609
+ for (let first = true; ; first = false) {
610
+ const { rows, fields } = await this.#client.query(
611
+ `FETCH ${EXPORT_BATCH} FROM ${cursor}`,
612
+ [],
613
+ {
614
+ rowMode: 'array',
615
+ parsers: this.#text,
616
+ },
617
+ )
618
+ if (rows.length || first) {
619
+ const columns = exportColumns(
620
+ fields.map((f) => f.name),
621
+ catalog.rows as (string | null)[][],
622
+ )
623
+ const waiting = setTimeout(stall, this.#exportIdleMs)
624
+ waiting.unref?.()
625
+ try {
626
+ yield { columns, rows: rows as (string | null)[][] }
627
+ } finally {
628
+ clearTimeout(waiting)
629
+ }
630
+ if (stalled) throw stalledExport(this.#exportIdleMs)
631
+ }
632
+ if (rows.length < EXPORT_BATCH) break
633
+ }
634
+ } catch (error) {
635
+ throw toError(error)
636
+ } finally {
637
+ await close()
283
638
  }
284
639
  }
285
640
 
@@ -292,16 +647,19 @@ class PGliteDriver implements Driver {
292
647
  const parsers = () => this.#text
293
648
  return new Promise<Session>((resolve, reject) => {
294
649
  let opened = false
650
+ let before: SessionState | undefined
295
651
  const done = client.transaction(async (tx) => {
296
652
  if (mode === 'snapshot') {
297
653
  await tx.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY')
298
- }
654
+ } else before = await sessionState(tx)
299
655
  let decide!: (commit: boolean) => void
300
656
  const decided = new Promise<boolean>((r) => (decide = r))
301
657
  let ended = false
302
658
  opened = true
303
659
  resolve({
304
660
  exclusive: true,
661
+ // PGlite keeps what the server says after each query, as its own transactions need.
662
+ ...(client.isInTransaction ? { inTransaction: () => client.isInTransaction!() } : {}),
305
663
  async query(sql, values) {
306
664
  try {
307
665
  const result = await tx.query(sql, values, { rowMode: 'array', parsers: parsers() })
@@ -318,18 +676,23 @@ class PGliteDriver implements Driver {
318
676
  await done
319
677
  } catch (error) {
320
678
  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
679
  }
330
680
  },
331
681
  })
332
- if (!(await decided)) await tx.rollback()
682
+ if (!(await decided)) {
683
+ // Rolled back by hand, and then what a rollback leaves (prepared statements, session
684
+ // locks) is put back while the host's queries still wait: see restoreSession.
685
+ await undo(tx)
686
+ if (before) {
687
+ await restoreSession(tx, before, false).catch((error: unknown) =>
688
+ console.error('otw-db: could not reset the PGlite session', error),
689
+ )
690
+ }
691
+ return
692
+ }
693
+ // As after every write: what the session set (a restore's SETs, its locks, a LISTEN) is
694
+ // undone inside the transaction, so the host's queries waiting for it find their own.
695
+ if (before) await restoreSession(tx, before, true, { listens: true })
333
696
  })
334
697
  done.catch((error: unknown) => {
335
698
  if (!opened) reject(toError(error))