@otwdesign/db-core 1.3.2 → 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,4 +1,12 @@
1
- import type { Column, Definition, TableDetail, TableKind, TableSummary } from '../types.ts'
1
+ import type {
2
+ Column,
3
+ Definition,
4
+ ExportColumn,
5
+ SqlDialect,
6
+ TableDetail,
7
+ TableKind,
8
+ TableSummary,
9
+ } from '../types.ts'
2
10
  import { doubleQuote, type Dialect } from './sql.ts'
3
11
 
4
12
  /*
@@ -36,6 +44,48 @@ export const dialect: Dialect = {
36
44
  // One array parameter, read as the column's type's array.
37
45
  inList: (expression, values, parameter) => `${expression} = ANY(${parameter(values)})`,
38
46
  insertDefaults: 'DEFAULT VALUES',
47
+ forUpdate: ' FOR UPDATE',
48
+ }
49
+
50
+ /**
51
+ * A value as a literal that reads the same whatever standard_conforming_strings is, as
52
+ * quote_literal() writes them: a value with a backslash goes in an E'…' string, where a
53
+ * backslash always escapes. In a plain '…' string a session with the setting off would read
54
+ * `\'` as a quote, and the value could end its string there and run as SQL. A SET at the top of
55
+ * the file wouldn't do: a client that sends the whole file at once has it parsed before the SET
56
+ * runs.
57
+ */
58
+ export function portableLiteral(value: string | null): string {
59
+ if (value === null) return 'NULL'
60
+ const quoted = value.replaceAll("'", "''")
61
+ return value.includes('\\') ? `E'${quoted.replaceAll('\\', '\\\\')}'` : `'${quoted}'`
62
+ }
63
+
64
+ /** How PostgreSQL's SQL is written for exports: files run later, in sessions set up anyhow. */
65
+ export const sqlDialect: SqlDialect = {
66
+ identifier: quote,
67
+ literal: portableLiteral,
68
+ overriding: ' OVERRIDING SYSTEM VALUE',
69
+ }
70
+
71
+ /** A table's columns an INSERT can't simply fill: generated ones, and identities numbered always. */
72
+ export const EXPORT_COLUMNS_SQL = `SELECT a.attname, a.attgenerated <> '', a.attidentity = 'a'
73
+ FROM pg_catalog.pg_attribute a
74
+ WHERE a.attrelid = to_regclass(format('%I.%I', $1::text, $2::text)) AND a.attnum > 0 AND NOT a.attisdropped`
75
+
76
+ /** An export's columns, by the names its rows came with, from EXPORT_COLUMNS_SQL's rows. */
77
+ export function exportColumns(
78
+ names: readonly string[],
79
+ catalog: readonly (readonly (string | null)[])[],
80
+ ): ExportColumn[] {
81
+ const flags = new Map(
82
+ catalog.map(([name, generated, identity]) => [name, { generated, identity }]),
83
+ )
84
+ return names.map((name) => ({
85
+ name,
86
+ ...(flags.get(name)?.generated === 't' ? { generated: true } : {}),
87
+ ...(flags.get(name)?.identity === 't' ? { identity: true } : {}),
88
+ }))
39
89
  }
40
90
 
41
91
  /** Every table and view, but the system's. */
@@ -1,14 +1,17 @@
1
1
  import type CursorClass from 'pg-cursor'
2
2
  import { connect } from 'node:net'
3
- import type { FieldDef, Pool, PoolClient, PoolConfig } from 'pg'
3
+ import type { FieldDef, Pool, PoolClient, PoolConfig, QueryArrayConfig } from 'pg'
4
4
  import { ConnectionError, DbAdminError, QueryError } from '../errors.ts'
5
+ import { refuseBeyondReadingPostgres } from './read-only.ts'
5
6
  import {
6
7
  DATABASES_SQL,
7
8
  detail,
8
9
  dialect,
10
+ EXPORT_COLUMNS_SQL,
11
+ exportColumns,
9
12
  INFO_SQL,
10
- literal,
11
13
  quote,
14
+ sqlDialect,
12
15
  summary,
13
16
  TABLE_SQL,
14
17
  TABLES_SQL,
@@ -17,13 +20,24 @@ import {
17
20
  type CatalogDetail,
18
21
  type CatalogTable,
19
22
  } from './postgres-catalog.ts'
20
- import { changeStatement, orderBy, Parameters, where, whole } from './sql.ts'
23
+ import {
24
+ changeStatement,
25
+ EXPORT_IDLE_MS,
26
+ orderBy,
27
+ Parameters,
28
+ refuseChanged,
29
+ seconds,
30
+ stalledExport,
31
+ where,
32
+ whole,
33
+ } from './sql.ts'
21
34
  import type {
22
35
  ApplyResult,
23
36
  Capabilities,
24
37
  Change,
25
38
  DatabaseList,
26
39
  Driver,
40
+ ExportColumn,
27
41
  QueryOptions,
28
42
  QueryResult,
29
43
  ResultSet,
@@ -68,8 +82,21 @@ export interface PostgresOptions {
68
82
  * from that package, which pnpm requires, since it keeps a package's dependencies beside it.
69
83
  */
70
84
  modules?: PostgresModules
85
+ /**
86
+ * How long a request waits for one of the pool's three connections, or for the server to
87
+ * answer, before it fails and says so. Defaults to 10 seconds.
88
+ */
89
+ connectTimeoutMs?: number
90
+ /**
91
+ * How long an export may sit between two batches, its rows unread, before it's ended and its
92
+ * connection is free again. Defaults to 5 minutes.
93
+ */
94
+ exportIdleMs?: number
71
95
  }
72
96
 
97
+ const CONNECT_TIMEOUT_MS = 10_000
98
+ const POOL_SIZE = 3
99
+
73
100
  // Imported where the app runs, not bundled: an app installs only the drivers it uses, and a
74
101
  // bundler (Next.js) mustn't fail on one it doesn't have.
75
102
  const fromApp: PostgresModules = () =>
@@ -147,35 +174,55 @@ export function postgresUrlAt(url: string, database: string): string {
147
174
  * connections, each closed after 10 s unused; an admin tool needs few.
148
175
  */
149
176
  export function postgresDriver(url: string, options: PostgresOptions = {}): Driver {
150
- return new PostgresDriver(url, options.modules)
177
+ return new PostgresDriver(url, options)
151
178
  }
152
179
 
153
180
  class PostgresDriver implements Driver {
154
181
  readonly kind = 'postgres'
155
182
  readonly capabilities: Capabilities = { schemas: true, transactionalDdl: true, cancel: true }
156
- readonly sql = { identifier: quote, literal }
183
+ readonly sql = sqlDialect
157
184
  readonly pgUrl: string
158
185
  readonly #url: string
159
186
  readonly #config: PoolConfig
160
187
  readonly #modules: PostgresModules | undefined
188
+ readonly #options: PostgresOptions
189
+ readonly #connectTimeoutMs: number
190
+ readonly #exportIdleMs: number
161
191
  #pool: Promise<{ pool: Pool; modules: Modules }> | undefined
162
192
  /** Type names by OID, filled as results bring new ones. */
163
193
  readonly #typeNames = new Map<number, string>()
194
+ /** Closed for good: a pool opened after that would be one nobody closes. */
195
+ #closed = false
196
+ /** The pool's clients that have their error listener: each comes back many times. */
197
+ readonly #heard = new WeakSet<PoolClient>()
164
198
 
165
- constructor(url: string, modules: PostgresModules | undefined) {
199
+ constructor(url: string, options: PostgresOptions) {
166
200
  this.#url = url
167
201
  this.pgUrl = url
168
- this.#modules = modules
202
+ this.#options = options
203
+ this.#modules = options.modules
204
+ this.#connectTimeoutMs = options.connectTimeoutMs ?? CONNECT_TIMEOUT_MS
205
+ this.#exportIdleMs = options.exportIdleMs ?? EXPORT_IDLE_MS
169
206
  this.#config = {
170
207
  connectionString: url,
171
- max: 3,
208
+ max: POOL_SIZE,
172
209
  idleTimeoutMillis: 10_000,
210
+ // Without it a request waits for good behind three connections that are held: exports
211
+ // nobody reads, a backup under way.
212
+ connectionTimeoutMillis: this.#connectTimeoutMs,
173
213
  application_name: 'otw-db',
174
214
  types: AS_TEXT,
175
215
  }
176
216
  }
177
217
 
178
218
  #open(): Promise<{ pool: Pool; modules: Modules }> {
219
+ // Whoever still holds a driver that was closed (a request under way when its database was
220
+ // the one used longest ago) is told, and asks again for one that's open.
221
+ if (this.#closed) {
222
+ return Promise.reject(
223
+ new ConnectionError('This connection to PostgreSQL was closed. Try again.'),
224
+ )
225
+ }
179
226
  this.#pool ??= loadModules(this.#modules).then(
180
227
  (modules) => {
181
228
  const pool = new modules.Pool(this.#config)
@@ -194,11 +241,27 @@ class PostgresDriver implements Driver {
194
241
 
195
242
  async #connect(): Promise<{ client: PoolClient; modules: Modules }> {
196
243
  const { pool, modules } = await this.#open()
244
+ let client: PoolClient
197
245
  try {
198
- return { client: await pool.connect(), modules }
246
+ client = await pool.connect()
199
247
  } catch (error) {
200
- throw new ConnectionError(`Could not connect to PostgreSQL: ${(error as Error).message}`)
248
+ const message = (error as Error).message
249
+ // pg-pool's one message for both: no connection came free, or none could be opened in time.
250
+ throw new ConnectionError(
251
+ /timeout exceeded when trying to connect/i.test(message)
252
+ ? `All ${POOL_SIZE} of this connection’s PostgreSQL connections are busy (an export or a backup under way, perhaps), or the server didn’t answer in ${seconds(this.#connectTimeoutMs)}. Try again in a moment.`
253
+ : `Could not connect to PostgreSQL: ${message}`,
254
+ )
201
255
  }
256
+ if (!this.#heard.has(client)) {
257
+ this.#heard.add(client)
258
+ // The pool listens for a client's errors only while the client is idle in it. The server
259
+ // dropping one that's held (between an export's batches, in a backup's session) emits an
260
+ // error too, and one nobody listens for ends the process. The statement that next finds
261
+ // the connection gone reports it.
262
+ client.on('error', () => {})
263
+ }
264
+ return { client, modules }
202
265
  }
203
266
 
204
267
  async #catalog<T>(text: string, values: unknown[] = []): Promise<T[]> {
@@ -257,7 +320,10 @@ class PostgresDriver implements Driver {
257
320
  return { product: 'PostgreSQL', ...row!, version: versionOf(row!.version) }
258
321
  }
259
322
 
260
- query(sql: string, options: QueryOptions): Promise<QueryResult> {
323
+ async query(sql: string, options: QueryOptions): Promise<QueryResult> {
324
+ // Someone's own statement, not one the driver wrote for the grid, whose table may well be
325
+ // named like something refused here. Before a connection is taken: nothing to give back.
326
+ if (options.access === 'read') refuseBeyondReadingPostgres(sql)
261
327
  return this.#run(sql, undefined, options)
262
328
  }
263
329
 
@@ -270,7 +336,7 @@ class PostgresDriver implements Driver {
270
336
  }
271
337
 
272
338
  withDatabase(name: string): Driver {
273
- return new PostgresDriver(postgresUrlAt(this.#url, name), this.#modules)
339
+ return new PostgresDriver(postgresUrlAt(this.#url, name), this.#options)
274
340
  }
275
341
 
276
342
  async apply(
@@ -287,6 +353,16 @@ class PostgresDriver implements Driver {
287
353
  try {
288
354
  await client.query(`BEGIN; SET LOCAL statement_timeout = ${whole(timeoutMs)}`)
289
355
  for (const statement of statements) {
356
+ if (statement.check) {
357
+ // As the grid read them: every value the server's own text.
358
+ const { rows } = await client.query({
359
+ text: statement.check.text,
360
+ values: statement.check.values,
361
+ rowMode: 'array',
362
+ types: AS_TEXT,
363
+ })
364
+ refuseChanged(dialect, statement, rows[0] as (string | null)[] | undefined)
365
+ }
290
366
  const { rowCount } = await client.query(statement.text, statement.values)
291
367
  if (statement.oneRow && rowCount !== 1) {
292
368
  const why =
@@ -315,31 +391,64 @@ class PostgresDriver implements Driver {
315
391
  order = [],
316
392
  }: Pick<RowsRequest, 'schema' | 'table' | 'filters' | 'order'>,
317
393
  { timeoutMs }: { timeoutMs: number },
318
- ): AsyncGenerator<{ columns: { name: string }[]; rows: (string | null)[][] }> {
394
+ ): AsyncGenerator<{ columns: ExportColumn[]; rows: (string | null)[][] }> {
319
395
  const parameters = new Parameters(dialect)
320
396
  const values = parameters.values
321
397
  const sql = `SELECT * FROM ${quote(schema)}.${quote(table)}${where(dialect, filters, parameters)}${orderBy(dialect, order)}`
322
398
  const { client, modules } = await this.#connect()
323
399
  // Until the last batch is read, the connection is mid-transaction: a stop on the way closes it.
324
400
  let finished = false
401
+ let released = false
402
+ const release = (destroy: boolean) => {
403
+ if (released) return
404
+ released = true
405
+ client.release(destroy)
406
+ }
407
+ // An export nobody reads sits between two batches with its cursor open: it would hold one of
408
+ // the pool's three connections, a snapshot and a lock on the table for as long as the browser
409
+ // stays away. No server timeout covers that wait (the session counts as active, and
410
+ // statement_timeout isn't acted on while it waits for the client), so it's ended from here.
411
+ let stalled = false
412
+ const stall = () => {
413
+ stalled = true
414
+ release(true)
415
+ }
325
416
  try {
326
417
  await client.query(`BEGIN READ ONLY; SET LOCAL statement_timeout = ${whole(timeoutMs)}`)
418
+ const catalog = await client.query({
419
+ text: EXPORT_COLUMNS_SQL,
420
+ values: [schema, table],
421
+ rowMode: 'array',
422
+ types: AS_TEXT,
423
+ })
327
424
  const cursor = client.query(
328
425
  new modules.Cursor(sql, values, { rowMode: 'array', types: AS_TEXT } as never),
329
426
  )
330
427
  // The first batch always, even empty, so a file of no rows still has its column names.
331
428
  for (let first = true; ; first = false) {
332
429
  const { rows, fields } = await readBatch(cursor, EXPORT_BATCH)
333
- if (rows.length || first) yield { columns: fields.map((f) => ({ name: f.name })), rows }
430
+ if (rows.length || first) {
431
+ const names = fields.map((f) => f.name)
432
+ const waiting = setTimeout(stall, this.#exportIdleMs)
433
+ // The wait is its reader's, not the process's: it doesn't keep a server from stopping.
434
+ waiting.unref()
435
+ try {
436
+ yield { columns: exportColumns(names, catalog.rows as (string | null)[][]), rows }
437
+ } finally {
438
+ clearTimeout(waiting)
439
+ }
440
+ if (stalled) break
441
+ }
334
442
  if (rows.length < EXPORT_BATCH) break
335
443
  }
444
+ if (stalled) throw stalledExport(this.#exportIdleMs)
336
445
  await new Promise<void>((resolve, reject) => cursor.close((e) => (e ? reject(e) : resolve())))
337
446
  await client.query(READ_CLEANUP)
338
447
  finished = true
339
448
  } catch (error) {
340
449
  throw toError(error)
341
450
  } finally {
342
- client.release(!finished)
451
+ release(!finished)
343
452
  }
344
453
  }
345
454
 
@@ -356,37 +465,76 @@ class PostgresDriver implements Driver {
356
465
  ): Promise<QueryResult> {
357
466
  const { client, modules } = await this.#connect()
358
467
  const started = performance.now()
359
- const cancel = () => sendCancel(client)
360
- options.signal?.addEventListener('abort', cancel, { once: true })
361
468
  const read = options.access === 'read'
362
469
  // A write may leave anything on its connection (SET, SET ROLE, temporary tables, session
363
470
  // locks), so the connection is closed after it rather than handed to the next query.
364
471
  let discard = !read
472
+ // Whether the connection is known to be outside a transaction: only then does it go back
473
+ // to the pool. An error in the driver's own BEGIN, COMMIT or cleanup leaves that unknown.
474
+ let outside = true
475
+ // A cancel names a connection, not a statement: one still on its way when the statement
476
+ // ends would stop whatever runs there next, the driver's own cleanup or someone else's
477
+ // query. So the request is waited for before the connection is used again: once the server
478
+ // has it, it stops the statement or, the statement over, is dropped. One that can't be
479
+ // waited for (a second at most) costs the connection instead.
480
+ let canceling: Promise<void> | undefined
481
+ const cancel = () => {
482
+ canceling = sendCancel(client)
483
+ }
484
+ const canceled = async () => {
485
+ if (!canceling) return
486
+ let timer: ReturnType<typeof setTimeout> | undefined
487
+ const late = new Promise<void>((resolve) => {
488
+ timer = setTimeout(() => {
489
+ discard = true
490
+ resolve()
491
+ }, 1_000)
492
+ })
493
+ await Promise.race([canceling, late])
494
+ clearTimeout(timer)
495
+ }
496
+ options.signal?.addEventListener('abort', cancel, { once: true })
365
497
  let result: CursorResult
366
498
  let durationMs: number
367
499
  try {
368
500
  if (options.signal?.aborted)
369
501
  throw new DbAdminError('The query was canceled.', 409, 'canceled')
502
+ outside = false
370
503
  await client.query(
371
504
  `BEGIN${read ? ' READ ONLY' : ''}; SET LOCAL statement_timeout = ${whole(options.timeoutMs)}`,
372
505
  )
373
506
  let alone = false
507
+ // Once the statement is over there is nothing left to cancel: a cancel sent from here on
508
+ // would only find the driver's cleanup, or whoever has the connection next.
509
+ const over = () => options.signal?.removeEventListener('abort', cancel)
374
510
  try {
375
511
  result = await readCursor(modules, client, sql, values, options.maxRows)
512
+ over()
376
513
  } catch (error) {
514
+ over()
377
515
  let rolledBack = true
516
+ await canceled()
378
517
  // The statement's own error is the one to report, whatever the cleanup does.
379
518
  await client.query(read ? READ_CLEANUP : 'ROLLBACK').catch(() => {
380
519
  rolledBack = false
381
520
  discard = true
382
521
  })
522
+ outside = rolledBack
383
523
  if (read || !rolledBack || sqlState(error) !== NOT_IN_TRANSACTION) throw error
384
- // VACUUM and the like: alone, on a connection closed afterwards like every write's.
524
+ // VACUUM and the like: alone, on a connection closed afterwards like every write's, so
525
+ // a cancel may be sent again, and find nobody after it.
385
526
  await client.query(`SET statement_timeout = ${whole(options.timeoutMs)}`)
527
+ // Canceled meanwhile: a listener put back on a signal that has fired never hears it.
528
+ if (options.signal?.aborted)
529
+ throw new DbAdminError('The query was canceled.', 409, 'canceled')
530
+ options.signal?.addEventListener('abort', cancel, { once: true })
386
531
  result = await readCursor(modules, client, sql, values, options.maxRows)
532
+ over()
387
533
  alone = true
388
534
  }
535
+ await canceled()
389
536
  if (!alone) await client.query(read ? READ_CLEANUP : 'COMMIT')
537
+ outside = true
390
538
  durationMs = Math.round(performance.now() - started)
391
539
  } catch (error) {
392
540
  if (!(error instanceof DbAdminError) && !(error as { severity?: string }).severity) {
@@ -395,7 +543,7 @@ class PostgresDriver implements Driver {
395
543
  throw toError(error, options.signal)
396
544
  } finally {
397
545
  options.signal?.removeEventListener('abort', cancel)
398
- client.release(discard)
546
+ client.release(discard || !outside)
399
547
  }
400
548
  // After the release: naming types may take a connection of its own.
401
549
  return {
@@ -427,6 +575,7 @@ class PostgresDriver implements Driver {
427
575
  async session(mode: 'snapshot' | 'write'): Promise<Session> {
428
576
  const { client } = await this.#connect()
429
577
  try {
578
+ if (mode === 'write') await oneStatementOnly(client)
430
579
  await client.query(
431
580
  mode === 'snapshot' ? 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY' : 'BEGIN',
432
581
  )
@@ -435,17 +584,28 @@ class PostgresDriver implements Driver {
435
584
  throw toError(error)
436
585
  }
437
586
  let ended = false
587
+ // What the server says after every query: I outside a transaction, T inside one, E inside
588
+ // one that failed. It costs nothing to hear, where asking would be a round trip a statement.
589
+ let status: string | undefined = 'T'
590
+ const connection = (client as unknown as { connection?: Heard }).connection
591
+ const heard = (message: { status?: string }) => {
592
+ status = message.status
593
+ }
594
+ connection?.on('readyForQuery', heard)
438
595
  return {
439
596
  exclusive: false,
597
+ inTransaction: () => status !== 'I',
440
598
  async query(text, values) {
441
599
  try {
442
600
  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,
601
+ ...extended(text),
602
+ ...(values
603
+ ? {
604
+ values: values.map((v) =>
605
+ v instanceof Uint8Array ? Buffer.from(v.buffer, v.byteOffset, v.byteLength) : v,
606
+ ),
607
+ }
608
+ : {}),
449
609
  })
450
610
  return { rows: result.rows as (string | null)[][] }
451
611
  } catch (error) {
@@ -460,6 +620,7 @@ class PostgresDriver implements Driver {
460
620
  } catch (error) {
461
621
  throw toError(error)
462
622
  } finally {
623
+ connection?.off('readyForQuery', heard)
463
624
  client.release(true)
464
625
  }
465
626
  },
@@ -467,6 +628,7 @@ class PostgresDriver implements Driver {
467
628
  }
468
629
 
469
630
  async close(): Promise<void> {
631
+ this.#closed = true
470
632
  const opened = this.#pool
471
633
  this.#pool = undefined
472
634
  // One that failed to open has nothing to close.
@@ -475,6 +637,44 @@ class PostgresDriver implements Driver {
475
637
  }
476
638
  }
477
639
 
640
+ /**
641
+ * A session's query, over the extended protocol: one statement a query, whatever the text holds,
642
+ * as the server refuses a second. A restore's statements come from a file, and none may carry
643
+ * another that ends its transaction. (pg's types don't list queryMode yet.)
644
+ */
645
+ function extended(text: string): QueryArrayConfig<unknown[]> & { queryMode: 'extended' } {
646
+ return { text, rowMode: 'array', types: AS_TEXT, queryMode: 'extended' }
647
+ }
648
+
649
+ /**
650
+ * Makes sure of it, on the connection a write session is about to use, before its transaction
651
+ * begins: two statements in one query must be refused. pg takes queryMode from 8.12 on; an
652
+ * older one ignores it and sends text without values over the simple protocol, which runs every
653
+ * statement in it, and nothing asked of it afterwards could undo the second. So a restore never
654
+ * starts on a connection that would have run both: it says to update pg instead. Reading, and
655
+ * so a backup, is the same on any pg.
656
+ */
657
+ async function oneStatementOnly(client: PoolClient): Promise<void> {
658
+ try {
659
+ await client.query(extended('SELECT 1; SELECT 2'))
660
+ } catch (error) {
661
+ // 42601: "cannot insert multiple commands into a prepared statement".
662
+ if ((error as { code?: string }).code === '42601') return
663
+ throw error
664
+ }
665
+ throw new DbAdminError(
666
+ 'This server’s PostgreSQL driver (pg) runs several statements sent as one, so a restore can’t be held to one transaction. Update pg to 8.12 or later.',
667
+ 500,
668
+ 'driver-unsafe',
669
+ )
670
+ }
671
+
672
+ /** pg's connection, as far as a session listens to it: the server's ReadyForQuery after a query. */
673
+ interface Heard {
674
+ on(event: 'readyForQuery', listener: (message: { status?: string }) => void): void
675
+ off(event: 'readyForQuery', listener: (message: { status?: string }) => void): void
676
+ }
677
+
478
678
  /** What pg keeps from the server's BackendKeyData, which a cancel request quotes. */
479
679
  interface Backend {
480
680
  host: string
@@ -489,20 +689,28 @@ interface Backend {
489
689
  * PgBouncer passes it on to the right server. Best effort: the statement timeout stops the query
490
690
  * when it can't get through (a proxy that takes TLS connections only, such as Neon's).
491
691
  */
492
- function sendCancel(client: PoolClient): void {
692
+ /** Sends the cancel request. Done once the server has taken it and closed, or it couldn't be sent. */
693
+ function sendCancel(client: PoolClient): Promise<void> {
493
694
  const { host, port, processID, secretKey } = client as PoolClient & Backend
494
- if (processID === null || secretKey === null) return
695
+ if (processID === null || secretKey === null) return Promise.resolve()
495
696
  const message = Buffer.alloc(16)
496
697
  message.writeInt32BE(16, 0)
497
698
  message.writeInt32BE(80877102, 4)
498
699
  message.writeInt32BE(processID, 8)
499
700
  message.writeInt32BE(secretKey, 12)
500
- const socket = host.startsWith('/')
501
- ? connect(`${host}/.s.PGSQL.${port}`)
502
- : connect({ host, port })
503
- socket.setTimeout(5_000, () => socket.destroy())
504
- socket.once('connect', () => socket.end(message))
505
- socket.once('error', (error) => console.error('otw-db: could not send the cancel request', error))
701
+ return new Promise<void>((resolve) => {
702
+ const socket = host.startsWith('/')
703
+ ? connect(`${host}/.s.PGSQL.${port}`)
704
+ : connect({ host, port })
705
+ socket.setTimeout(5_000, () => socket.destroy())
706
+ socket.once('connect', () => socket.end(message))
707
+ socket.once('error', (error) =>
708
+ console.error('otw-db: could not send the cancel request', error),
709
+ )
710
+ // The server closes its end once the request is in the statement's hands.
711
+ socket.once('close', () => resolve())
712
+ socket.resume()
713
+ })
506
714
  }
507
715
 
508
716
  const EXPORT_BATCH = 1_000