@otwdesign/db-core 1.3.2 → 1.4.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 (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 +678 -107
  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 +750 -104
  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,3 +1,4 @@
1
+ import { spawn, type ChildProcess } from 'node:child_process'
1
2
  import { existsSync } from 'node:fs'
2
3
  import { basename, resolve } from 'node:path'
3
4
  import { Worker } from 'node:worker_threads'
@@ -6,6 +7,7 @@ import type {
6
7
  ApplyResult,
7
8
  Capabilities,
8
9
  Change,
10
+ ExportColumn,
9
11
  Column,
10
12
  Driver,
11
13
  QueryOptions,
@@ -19,8 +21,11 @@ import type {
19
21
  import {
20
22
  changeStatement,
21
23
  doubleQuote,
24
+ EXPORT_IDLE_MS,
22
25
  orderBy,
23
26
  Parameters,
27
+ refuseChanged,
28
+ stalledExport,
24
29
  where,
25
30
  whole,
26
31
  type Dialect,
@@ -32,9 +37,22 @@ export function sqliteLiteral(value: string | null): string {
32
37
  return `'${value.replaceAll("'", "''")}'`
33
38
  }
34
39
 
40
+ /**
41
+ * Bytes as the grid shows them, `X'1F'`, as the literal that is those bytes; null for anything
42
+ * else. SQLite never finds a blob equal to text, so a blob key compared with those letters
43
+ * matches no row.
44
+ */
45
+ export function sqliteBytes(shown: string): string | null {
46
+ const hex = /^X'((?:[0-9A-Fa-f]{2})*)'$/.exec(shown)?.[1]
47
+ return hex === undefined ? null : `X'${hex.toUpperCase()}'`
48
+ }
49
+
35
50
  const dialect: Dialect = {
36
51
  identifier: doubleQuote,
37
52
  literal: sqliteLiteral,
53
+ bytes: sqliteBytes,
54
+ // A write transaction here holds the whole file.
55
+ forUpdate: '',
38
56
  placeholder: () => '?',
39
57
  text: (expression) => `CAST(${expression} AS TEXT)`,
40
58
  // SQLite's LIKE ignores case for ASCII letters, and has no escape until told.
@@ -50,10 +68,14 @@ const EXPORT_BATCH = 1_000
50
68
 
51
69
  /**
52
70
  * Where `sql`'s first statement ends, and whether anything but space and comments follows it.
53
- * SQLite prepares the first statement and ignores the rest, so the rest is refused here instead.
54
- * Self-contained: it's also copied into the worker.
71
+ * SQLite prepares the first statement and ignores the rest, so the rest is refused instead.
72
+ *
73
+ * The worker's own, and so written as its text. Taken from a function here with `toString()`,
74
+ * it was whatever the app's build had made of that function: Next.js left it without its name,
75
+ * and no SQLite file could be opened from a built app.
55
76
  */
56
- function hasMoreStatements(sql: string): boolean {
77
+ const HAS_MORE_STATEMENTS = String.raw`
78
+ function hasMoreStatements(sql) {
57
79
  let i = 0
58
80
  const n = sql.length
59
81
  let first = true
@@ -65,7 +87,7 @@ function hasMoreStatements(sql: string): boolean {
65
87
  } else if (c === '/' && sql[i + 1] === '*') {
66
88
  const end = sql.indexOf('*/', i + 2)
67
89
  i = end === -1 ? n : end + 2
68
- } else if (c === "'" || c === '"' || c === '`' || c === '[') {
90
+ } else if (c === "'" || c === '"' || c === '\x60' || c === '[') {
69
91
  const close = c === '[' ? ']' : c
70
92
  let j = i + 1
71
93
  while (j < n) {
@@ -78,7 +100,7 @@ function hasMoreStatements(sql: string): boolean {
78
100
  } else if (c === ';') {
79
101
  first = false
80
102
  i++
81
- } else if (/\s/.test(c!)) {
103
+ } else if (/\s/.test(c)) {
82
104
  i++
83
105
  } else {
84
106
  if (!first) return true
@@ -87,12 +109,101 @@ function hasMoreStatements(sql: string): boolean {
87
109
  }
88
110
  return false
89
111
  }
112
+ `
90
113
 
91
- /** The worker's code: runs on its own thread, so a long statement never blocks the host. */
92
- const WORKER = `
93
- const { parentPort, workerData } = require('node:worker_threads')
94
- const { DatabaseSync } = require('node:sqlite')
95
- ${hasMoreStatements.toString()}
114
+ /**
115
+ * PRAGMAs that set something for the whole process, not for the connection they're run on: with
116
+ * `hard_heap_limit = 1`, no SQLite handle in the process can read a row again, the host's own
117
+ * included, until it restarts.
118
+ */
119
+ const PROCESS_WIDE = [
120
+ 'hard_heap_limit',
121
+ 'soft_heap_limit',
122
+ 'temp_store_directory',
123
+ 'data_store_directory',
124
+ // Not the process's, but another file's: where Apple's SQLite keeps a lock, made if missing.
125
+ 'lock_proxy_file',
126
+ ]
127
+
128
+ /** A statement's first word in capitals, past spaces and comments, read a character at a time. */
129
+ function sqliteFirstWord(sql: string): string {
130
+ let at = 0
131
+ for (;;) {
132
+ while (at < sql.length && /\s/.test(sql[at]!)) at++
133
+ if (sql.startsWith('--', at)) {
134
+ const end = sql.indexOf('\n', at)
135
+ at = end === -1 ? sql.length : end + 1
136
+ } else if (sql.startsWith('/*', at)) {
137
+ const end = sql.indexOf('*/', at + 2)
138
+ at = end === -1 ? sql.length : end + 2
139
+ } else break
140
+ }
141
+ return (/^\w+/.exec(sql.slice(at, at + 64))?.[0] ?? '').toUpperCase()
142
+ }
143
+
144
+ /**
145
+ * The one of those a statement would set, by its tokens: past comments, EXPLAIN [QUERY PLAN] (a
146
+ * PRAGMA acts when it's prepared, explained or not) and a schema's name, however the name is
147
+ * quoted. Null for any other statement, and for a PRAGMA that only reads. Self-contained.
148
+ */
149
+ export function processWidePragma(sql: string): string | null {
150
+ let at = 0
151
+ const skip = () => {
152
+ for (;;) {
153
+ while (at < sql.length && /\s/.test(sql[at]!)) at++
154
+ if (sql.startsWith('--', at)) {
155
+ const end = sql.indexOf('\n', at)
156
+ at = end === -1 ? sql.length : end + 1
157
+ } else if (sql.startsWith('/*', at)) {
158
+ const end = sql.indexOf('*/', at + 2)
159
+ at = end === -1 ? sql.length : end + 2
160
+ } else return
161
+ }
162
+ }
163
+ const name = (): string | null => {
164
+ skip()
165
+ const open = sql[at]
166
+ const close = open === '[' ? ']' : open === '"' || open === '`' || open === "'" ? open : null
167
+ if (close) {
168
+ const end = sql.indexOf(close, at + 1)
169
+ if (end === -1) return null
170
+ const quoted = sql.slice(at + 1, end)
171
+ at = end + 1
172
+ return quoted.toLowerCase()
173
+ }
174
+ const word = /^[A-Za-z_][\w$]*/.exec(sql.slice(at, at + 64))?.[0]
175
+ if (!word) return null
176
+ at += word.length
177
+ return word.toLowerCase()
178
+ }
179
+ let word = name()
180
+ if (word === 'explain') {
181
+ word = name()
182
+ if (word === 'query') {
183
+ name()
184
+ word = name()
185
+ }
186
+ }
187
+ if (word !== 'pragma') return null
188
+ let pragma = name()
189
+ skip()
190
+ if (sql[at] === '.') {
191
+ at++
192
+ pragma = name()
193
+ skip()
194
+ }
195
+ if (!pragma || !PROCESS_WIDE.includes(pragma)) return null
196
+ return sql[at] === '=' || sql[at] === '(' ? pragma : null
197
+ }
198
+
199
+ /**
200
+ * The worker's code, for a thread or a process of its own: `parentPort` and `workerData` are
201
+ * given by whichever of the two openings below it runs after.
202
+ */
203
+ const WORKER_BODY = `
204
+ const { DatabaseSync, constants } = require('node:sqlite')
205
+ const PROCESS_WIDE = ${JSON.stringify(PROCESS_WIDE)}
206
+ ${HAS_MORE_STATEMENTS}
96
207
  let reader, writer
97
208
  const cursors = new Map()
98
209
  let nextCursor = 1
@@ -127,8 +238,28 @@ function row(statement, columns, value) {
127
238
  return Array.isArray(value) ? value.map(text) : columns.map((c) => text(value[c.name]))
128
239
  }
129
240
 
130
- function run({ sql, params, maxRows, write, transaction }) {
131
- const database = db(write)
241
+ // Someone's own SQL runs on a handle of its own, closed after it: what the statement sets up (a
242
+ // TEMP view named as a table is, a PRAGMA, a transaction left open) ends with it, and never
243
+ // reaches the next person's statement, the grid's reads and edits, or the host's file.
244
+ function run(message) {
245
+ if (!message.own) return runOn(db(message.write), message)
246
+ const database = new DatabaseSync(workerData.path, { readOnly: !message.write })
247
+ // Behind the driver's reading of the statement, where this Node has it: SQLite itself says
248
+ // which PRAGMA a statement sets, whatever its text.
249
+ if (database.setAuthorizer && constants && constants.SQLITE_PRAGMA !== undefined) {
250
+ database.setAuthorizer((action, name, value) =>
251
+ action === constants.SQLITE_PRAGMA && value != null && PROCESS_WIDE.includes(String(name).toLowerCase())
252
+ ? constants.SQLITE_DENY
253
+ : constants.SQLITE_OK)
254
+ }
255
+ try {
256
+ return runOn(database, message)
257
+ } finally {
258
+ database.close()
259
+ }
260
+ }
261
+
262
+ function runOn(database, { sql, params, maxRows, transaction }) {
132
263
  const statement = prepare(database, sql)
133
264
  const columns = columnsOf(statement)
134
265
  if (!columns.length) {
@@ -136,9 +267,15 @@ function run({ sql, params, maxRows, write, transaction }) {
136
267
  try {
137
268
  const { changes } = statement.run(...params)
138
269
  if (transaction) database.exec('COMMIT')
270
+ else if (database.isTransaction) {
271
+ // BEGIN or SAVEPOINT, run alone: nothing after it would ever commit.
272
+ const error = new Error('a transaction left open')
273
+ error.leftOpen = true
274
+ throw error
275
+ }
139
276
  return { columns, rows: [], truncated: false, changes: Number(changes) }
140
277
  } catch (error) {
141
- if (transaction && database.isTransaction) database.exec('ROLLBACK')
278
+ if (database.isTransaction) database.exec('ROLLBACK')
142
279
  throw error
143
280
  }
144
281
  }
@@ -158,7 +295,22 @@ function apply({ statements }) {
158
295
  const database = db(true)
159
296
  database.exec('BEGIN IMMEDIATE')
160
297
  try {
161
- for (const { sql, params, oneRow, shown } of statements) {
298
+ for (const [index, { sql, params, oneRow, shown, check }] of statements.entries()) {
299
+ if (check) {
300
+ // The cells as the grid read them, for the driver to compare with what they held.
301
+ const reader = prepare(database, check.sql)
302
+ const columns = columnsOf(reader)
303
+ let current = null
304
+ for (const value of reader.iterate(...check.params)) {
305
+ current = row(reader, columns, value)
306
+ break
307
+ }
308
+ if (!current || check.original.some((was, i) => was !== current[i])) {
309
+ const error = new Error('a cell was changed meanwhile')
310
+ error.changed = { index, current }
311
+ throw error
312
+ }
313
+ }
162
314
  const { changes } = prepare(database, sql).run(...params)
163
315
  if (oneRow && Number(changes) !== 1) {
164
316
  const error = new Error(Number(changes) === 0 ? 'its row is gone or its key changed' : 'its key matched ' + changes + ' rows')
@@ -204,10 +356,35 @@ function close({ cursor }) {
204
356
  return {}
205
357
  }
206
358
 
207
- const handlers = { run, apply, open, next, close }
359
+ // A write killed part-way (its process, at its time limit) can leave its journal beside the
360
+ // file: the next handle that may write undoes it, and one that may only read can't, and fails.
361
+ function recover() {
362
+ db(true).prepare('SELECT count(*) FROM sqlite_master').get()
363
+ return true
364
+ }
365
+
366
+ const handlers = { run, apply, open, next, close, recover }
367
+ // A read that finds a journal left by a writer that was killed (this driver's own, at a time
368
+ // limit; the server itself, stopped mid-write) can't undo it, and fails. The journal is undone
369
+ // by a handle that may write, and the read is asked again.
370
+ function handle(message) {
371
+ try {
372
+ return handlers[message.type](message)
373
+ } catch (error) {
374
+ const hot = /attempt to write a readonly database/i.test(String(error && error.message))
375
+ if (!hot || message.write || message.type === 'apply' || message.type === 'recover') throw error
376
+ try {
377
+ recover()
378
+ } catch {
379
+ throw error
380
+ }
381
+ return handlers[message.type](message)
382
+ }
383
+ }
384
+
208
385
  parentPort.on('message', (message) => {
209
386
  try {
210
- parentPort.postMessage({ id: message.id, result: handlers[message.type](message) })
387
+ parentPort.postMessage({ id: message.id, result: handle(message) })
211
388
  } catch (error) {
212
389
  parentPort.postMessage({
213
390
  id: message.id,
@@ -217,18 +394,77 @@ parentPort.on('message', (message) => {
217
394
  errcode: error.errcode,
218
395
  conflict: error.conflict,
219
396
  oneStatement: error.oneStatement === true,
397
+ leftOpen: error.leftOpen === true,
398
+ changed: error.changed,
220
399
  },
221
400
  })
222
401
  }
223
402
  })
224
403
  `
225
404
 
405
+ /** On a thread: a long statement never blocks the host. */
406
+ const THREAD_WORKER = `
407
+ const { parentPort, workerData } = require('node:worker_threads')
408
+ ${WORKER_BODY}`
409
+
410
+ /**
411
+ * In a process: for someone's own SQL. A statement can stay inside SQLite for as long as it
412
+ * likes (a recursive query with no end), where nothing stops a thread: stopping the thread stops
413
+ * its JavaScript, and there is none running. A process can be killed, and what it held on the
414
+ * file goes with it.
415
+ *
416
+ * The statement runs on a thread of that process, so its first thread is never inside SQLite:
417
+ * it always hears that the server has gone (stopped, crashed, killed), and ends the process,
418
+ * statement and all. Left to one thread, a statement with no end would outlive the server that
419
+ * asked for it, and keep a processor for itself. Exported for its test.
420
+ */
421
+ export const SQLITE_PROCESS_WORKER = `
422
+ const { Worker } = require('node:worker_threads')
423
+ // Not asked to stop, which waits for the thread: killed, as the server would have.
424
+ const die = () => process.kill(process.pid, 'SIGKILL')
425
+ process.on('disconnect', die)
426
+ const worker = new Worker(${JSON.stringify(THREAD_WORKER)}, {
427
+ eval: true,
428
+ workerData: JSON.parse(process.env.OTW_DB_SQLITE_WORKER),
429
+ })
430
+ worker.on('message', (message) => {
431
+ try {
432
+ process.send(message)
433
+ } catch {
434
+ die()
435
+ }
436
+ })
437
+ worker.on('error', die)
438
+ worker.on('exit', die)
439
+ process.on('message', (message) => worker.postMessage(message))
440
+ // Said once the thread is up: a process that never says it can't be waited on for answers.
441
+ worker.once('online', () => process.send({ ready: true }))
442
+ `
443
+
444
+ /** What the process is given of the server's environment: where programs and temporary files are. */
445
+ const PROCESS_ENV = [
446
+ 'PATH',
447
+ 'SystemRoot',
448
+ 'TMPDIR',
449
+ 'TEMP',
450
+ 'TMP',
451
+ 'SQLITE_TMPDIR',
452
+ 'HOME',
453
+ 'USERPROFILE',
454
+ ]
455
+
456
+ /** How long a process with nothing to run is kept before it's let go of. */
457
+ const PROCESS_IDLE_MS = 60_000
458
+
226
459
  interface WorkerError {
227
460
  message: string
228
461
  code?: string
229
462
  errcode?: number
230
463
  conflict?: string
231
464
  oneStatement?: boolean
465
+ leftOpen?: boolean
466
+ /** An update's check found its row changed or gone: which statement, and the row now. */
467
+ changed?: { index: number; current: (string | null)[] | null }
232
468
  }
233
469
 
234
470
  /** The file a `sqlite:` or `file:` address names. */
@@ -252,83 +488,246 @@ export function sqlitePath(url: string): string {
252
488
  * time on a worker thread: a long one never blocks the host, and stopping the worker stops it.
253
489
  * Read access opens the file read-only.
254
490
  */
255
- export function sqliteDriver(url: string): Driver {
256
- return new SqliteDriver(sqlitePath(url))
491
+ export function sqliteDriver(url: string, options: SqliteOptions = {}): Driver {
492
+ return new SqliteDriver(sqlitePath(url), options)
257
493
  }
258
494
 
259
- class SqliteDriver implements Driver {
260
- readonly kind = 'sqlite'
261
- readonly capabilities: Capabilities = { schemas: false, transactionalDdl: true, cancel: true }
262
- readonly sql = { identifier: doubleQuote, literal: sqliteLiteral }
495
+ /** How the SQLite driver behaves, where the defaults don't suit. */
496
+ export interface SqliteOptions {
497
+ /**
498
+ * How long an export may sit between two batches, its rows unread, before it's ended and lets
499
+ * go of the file. Defaults to 5 minutes.
500
+ */
501
+ exportIdleMs?: number
502
+ }
503
+
504
+ /** A worker as a lane holds it, thread or process: told what to run, and stopped. */
505
+ interface Running {
506
+ /** Sends it a request, which is its own to answer or to fail. */
507
+ post(message: Record<string, unknown> & { id: number }): void
508
+ /** Stops it now, whatever it's doing; done once it's gone. */
509
+ stop(): Promise<void>
510
+ }
511
+
512
+ /** What a worker sends back: a request's result, or why it has none. */
513
+ interface Answer {
514
+ id: number
515
+ result?: unknown
516
+ error?: WorkerError
517
+ /** A process's first word: its thread is up. */
518
+ ready?: true
519
+ }
520
+
521
+ /** How long a process has to say it's up before the lane does without one. */
522
+ const PROCESS_START_MS = 5_000
523
+
524
+ /** This server can't start a process: the lane goes on a thread instead, as it did before. */
525
+ class NoProcess extends Error {}
526
+
527
+ /**
528
+ * A worker of its own with the file open on it, and the requests waiting for it. The driver has
529
+ * one for its statements; each export has another, so stopping a statement (which stops its
530
+ * worker) never ends an export under way, and an export nobody reads can be let go of by
531
+ * stopping its own. Those are threads. Someone's own SQL has a third, a process: see
532
+ * SQLITE_PROCESS_WORKER.
533
+ */
534
+ class Lane {
263
535
  readonly #path: string
264
- #worker: Worker | null = null
536
+ #kind: 'thread' | 'process'
537
+ #worker: Running | null = null
265
538
  #pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>()
266
539
  #next = 1
267
540
  /** One request at a time: the worker's connection is single-threaded. */
268
541
  #queue: Promise<unknown> = Promise.resolve()
542
+ #idle: ReturnType<typeof setTimeout> | undefined
543
+ /** The last worker stopped, on its way out. */
544
+ #going: Promise<void> = Promise.resolve()
269
545
 
270
- constructor(path: string) {
546
+ constructor(path: string, kind: 'thread' | 'process' = 'thread') {
271
547
  this.#path = path
548
+ this.#kind = kind
272
549
  }
273
550
 
274
- #spawn(): Worker {
551
+ #spawn(): Running {
275
552
  if (this.#worker) return this.#worker
276
553
  if (!existsSync(this.#path))
277
554
  throw new ConnectionError(`There's no SQLite database at ${this.#path}.`)
278
- const worker = new Worker(WORKER, { eval: true, workerData: { path: this.#path } })
279
- worker.on(
280
- 'message',
281
- ({ id, result, error }: { id: number; result?: unknown; error?: WorkerError }) => {
282
- const waiting = this.#pending.get(id)
283
- this.#pending.delete(id)
284
- if (!waiting) return
285
- if (error) waiting.reject(fromWorker(error))
286
- else waiting.resolve(result)
287
- },
288
- )
555
+ // The requests this worker was sent: when it goes, those fail, and no others. A worker
556
+ // stopped at a time limit is still on its way out when the next request has a new one.
557
+ const mine = new Set<number>()
558
+ const answer = ({ id, result, error }: Answer) => {
559
+ mine.delete(id)
560
+ const waiting = this.#pending.get(id)
561
+ this.#pending.delete(id)
562
+ if (!waiting) return
563
+ if (error) waiting.reject(fromWorker(error))
564
+ else waiting.resolve(result)
565
+ }
289
566
  const fail = (error: Error) => {
290
- for (const waiting of this.#pending.values()) waiting.reject(error)
291
- this.#pending.clear()
292
- if (this.#worker === worker) this.#worker = null
567
+ for (const id of mine) {
568
+ this.#pending.get(id)?.reject(error)
569
+ this.#pending.delete(id)
570
+ }
571
+ mine.clear()
572
+ if (this.#worker === running) this.#worker = null
293
573
  }
574
+ const sent = (id: number) => void mine.add(id)
575
+ const running: Running =
576
+ this.#kind === 'thread' ? this.#thread(answer, fail, sent) : this.#process(answer, fail, sent)
577
+ this.#worker = running
578
+ return running
579
+ }
580
+
581
+ #thread(
582
+ answer: (message: Answer) => void,
583
+ fail: (error: Error) => void,
584
+ sent: (id: number) => void,
585
+ ): Running {
586
+ const worker = new Worker(THREAD_WORKER, { eval: true, workerData: { path: this.#path } })
587
+ worker.on('message', answer)
294
588
  worker.on('error', (error) =>
295
589
  fail(new ConnectionError(`The SQLite worker failed: ${error.message}`)),
296
590
  )
297
591
  worker.on('exit', () => fail(new ConnectionError('The SQLite worker stopped.')))
298
- this.#worker = worker
299
- return worker
592
+ return {
593
+ post: (message) => {
594
+ sent(message.id)
595
+ worker.postMessage(message)
596
+ },
597
+ stop: async () => void (await worker.terminate()),
598
+ }
599
+ }
600
+
601
+ #process(
602
+ answer: (message: Answer) => void,
603
+ fail: (error: Error) => void,
604
+ sent: (id: number) => void,
605
+ ): Running {
606
+ const env: Record<string, string> = {
607
+ OTW_DB_SQLITE_WORKER: JSON.stringify({ path: this.#path }),
608
+ }
609
+ for (const name of PROCESS_ENV)
610
+ if (process.env[name] !== undefined) env[name] = process.env[name]
611
+ let child: ChildProcess
612
+ try {
613
+ child = spawn(
614
+ process.execPath,
615
+ ['--disable-warning=ExperimentalWarning', '-e', SQLITE_PROCESS_WORKER],
616
+ // Nothing to read or write but what it's sent: its errors go where the server's do.
617
+ {
618
+ stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
619
+ serialization: 'advanced',
620
+ // An app's own types may ask more of an environment (Next's wants NODE_ENV): this one is
621
+ // the process's whole environment, by design.
622
+ env: env as NodeJS.ProcessEnv,
623
+ windowsHide: true,
624
+ },
625
+ )
626
+ } catch (error) {
627
+ throw new NoProcess((error as Error).message)
628
+ }
629
+ const gone = () => child.exitCode !== null || child.signalCode !== null
630
+ // Nothing is sent until the process has said it's up. One that starts and stops at once (a
631
+ // Node that can't run it), or starts and never speaks, is no process to wait on: the lane
632
+ // goes on a thread, as where none starts, and since nothing was sent, nothing runs twice.
633
+ let ready = false
634
+ let deliberate = false
635
+ const unsent: (Record<string, unknown> & { id: number })[] = []
636
+ const starting = setTimeout(() => {
637
+ // Decided after what has already arrived is read: a server too busy to read its messages
638
+ // for a while finds this timer due before the process's first word, which is waiting.
639
+ setImmediate(() => {
640
+ if (!ready && !gone()) child.kill('SIGKILL')
641
+ })
642
+ }, PROCESS_START_MS)
643
+ starting.unref()
644
+ const stopped = () =>
645
+ deliberate || ready
646
+ ? new ConnectionError('The SQLite worker stopped.')
647
+ : new NoProcess('it stopped before it was up')
648
+ child.on('message', (message: Answer) => {
649
+ if (!message.ready) return answer(message)
650
+ ready = true
651
+ clearTimeout(starting)
652
+ for (const waiting of unsent.splice(0)) child.send(waiting)
653
+ })
654
+ child.on('error', (error) => {
655
+ clearTimeout(starting)
656
+ fail(
657
+ child.pid === undefined
658
+ ? new NoProcess(error.message)
659
+ : ready
660
+ ? new ConnectionError(`The SQLite worker failed: ${error.message}`)
661
+ : stopped(),
662
+ )
663
+ })
664
+ child.on('exit', () => {
665
+ clearTimeout(starting)
666
+ fail(stopped())
667
+ })
668
+ return {
669
+ post: (message) => {
670
+ sent(message.id)
671
+ if (!ready) unsent.push(message)
672
+ else if (child.connected) child.send(message)
673
+ },
674
+ stop: () =>
675
+ new Promise<void>((resolve) => {
676
+ // Stopped on purpose is stopped: not a process that couldn't start, to try again without.
677
+ deliberate = true
678
+ clearTimeout(starting)
679
+ if (child.pid === undefined || gone()) return resolve()
680
+ child.once('exit', () => resolve())
681
+ // Not asked: killed. SQLite, mid-statement, hears nothing else.
682
+ child.kill('SIGKILL')
683
+ }),
684
+ }
685
+ }
686
+
687
+ /** Runs `work` when the requests before it are done, and holds those after it until it is. */
688
+ after<T>(work: () => Promise<T>): Promise<T> {
689
+ const result = this.#queue.then(work, work)
690
+ this.#queue = result.catch(() => {})
691
+ return result
300
692
  }
301
693
 
302
694
  /**
303
695
  * Sends a request when the ones before it are done. The timer and the signal stop the worker,
304
696
  * which stops the statement; the next request starts a fresh one.
305
697
  */
306
- #send<T>(
698
+ send<T>(
307
699
  message: Record<string, unknown>,
308
- options: { timeoutMs?: number; signal?: AbortSignal } = {},
700
+ /** `now`: without waiting its turn, for whoever is already having theirs (`after`). */
701
+ options: { timeoutMs?: number; signal?: AbortSignal; now?: boolean } = {},
309
702
  ): Promise<T> {
310
703
  const run = async (): Promise<T> => {
311
704
  if (options.signal?.aborted)
312
705
  throw new DbAdminError('The query was canceled.', 409, 'canceled')
706
+ clearTimeout(this.#idle)
313
707
  const worker = this.#spawn()
314
708
  const id = this.#next++
315
709
  return new Promise<T>((resolve, reject) => {
316
710
  let stopped: Error | null = null
711
+ let answered = false
317
712
  const stop = (error: Error) => {
318
- if (stopped) return
713
+ if (stopped || answered) return
319
714
  stopped = error
320
715
  this.#pending.delete(id)
321
716
  this.#worker = null
322
- void worker.terminate()
717
+ this.#going = worker.stop().catch(() => {})
323
718
  reject(error)
324
719
  }
325
720
  const timer = options.timeoutMs
326
721
  ? setTimeout(
327
722
  () =>
328
- stop(
329
- new QueryError(
330
- `The statement ran past its ${options.timeoutMs} ms limit and was stopped.`,
331
- 'SQLITE_INTERRUPT',
723
+ // After what has already arrived is read: a statement that finished while the
724
+ // server was too busy to hear it isn't stopped, and said to have been.
725
+ setImmediate(() =>
726
+ stop(
727
+ new QueryError(
728
+ `The statement ran past its ${options.timeoutMs} ms limit and was stopped.`,
729
+ 'SQLITE_INTERRUPT',
730
+ ),
332
731
  ),
333
732
  ),
334
733
  options.timeoutMs,
@@ -337,6 +736,7 @@ class SqliteDriver implements Driver {
337
736
  const abort = () => stop(new DbAdminError('The query was canceled.', 409, 'canceled'))
338
737
  options.signal?.addEventListener('abort', abort, { once: true })
339
738
  const done = () => {
739
+ answered = true
340
740
  clearTimeout(timer)
341
741
  options.signal?.removeEventListener('abort', abort)
342
742
  }
@@ -350,12 +750,94 @@ class SqliteDriver implements Driver {
350
750
  reject(error)
351
751
  },
352
752
  })
353
- worker.postMessage({ ...message, id })
753
+ worker.post({ ...message, id })
354
754
  })
355
755
  }
356
- const result = this.#queue.then(run, run)
357
- this.#queue = result.catch(() => {})
358
- return result
756
+ const attempt = async () => {
757
+ try {
758
+ return await run()
759
+ } catch (error) {
760
+ if (!(error instanceof NoProcess)) throw error
761
+ this.#kind = 'thread'
762
+ return await run()
763
+ } finally {
764
+ this.#rest()
765
+ }
766
+ }
767
+ return options.now ? attempt() : this.after(attempt)
768
+ }
769
+
770
+ /** Done once a worker stopped at its limit, or canceled, has really gone. */
771
+ gone(): Promise<void> {
772
+ return this.#going
773
+ }
774
+
775
+ /** A process with nothing to run is let go of after a while: it's a whole Node, kept for one file. */
776
+ #rest(): void {
777
+ if (this.#kind !== 'process') return
778
+ clearTimeout(this.#idle)
779
+ this.#idle = setTimeout(() => {
780
+ if (this.#pending.size === 0) this.stop()
781
+ }, PROCESS_IDLE_MS)
782
+ this.#idle.unref()
783
+ }
784
+
785
+ /** Stops the worker once the requests before this are done: what it held on the file goes. */
786
+ async close(): Promise<void> {
787
+ await this.#queue
788
+ clearTimeout(this.#idle)
789
+ const worker = this.#worker
790
+ this.#worker = null
791
+ await worker?.stop()
792
+ }
793
+
794
+ /** Stops the worker now, whatever it's doing: the requests it had fail. */
795
+ stop(): void {
796
+ clearTimeout(this.#idle)
797
+ const worker = this.#worker
798
+ this.#worker = null
799
+ if (worker) this.#going = worker.stop().catch(() => {})
800
+ }
801
+ }
802
+
803
+ /** Whether a statement was stopped while it ran: at its time limit, or canceled. */
804
+ function stoppedPartWay(error: unknown): boolean {
805
+ return (
806
+ (error instanceof QueryError && error.sqlState === 'SQLITE_INTERRUPT') ||
807
+ (error instanceof DbAdminError && error.code === 'canceled')
808
+ )
809
+ }
810
+
811
+ class SqliteDriver implements Driver {
812
+ readonly kind = 'sqlite'
813
+ readonly capabilities: Capabilities = { schemas: false, transactionalDdl: true, cancel: true }
814
+ readonly sql = { identifier: doubleQuote, literal: sqliteLiteral, bytes: sqliteBytes }
815
+ readonly #path: string
816
+ readonly #exportIdleMs: number
817
+ /** The driver's own statements, one at a time. */
818
+ readonly #lane: Lane
819
+ /** Someone's own SQL: in a process, which a time limit can really stop. */
820
+ readonly #own: Lane
821
+ /** Their writes under way, and whether the driver was closed: no statement starts after that. */
822
+ #writing = 0
823
+ #closed = false
824
+
825
+ constructor(path: string, options: SqliteOptions) {
826
+ this.#path = path
827
+ this.#exportIdleMs = options.exportIdleMs ?? EXPORT_IDLE_MS
828
+ this.#lane = new Lane(path)
829
+ this.#own = new Lane(path, 'process')
830
+ }
831
+
832
+ #send<T>(
833
+ message: Record<string, unknown>,
834
+ options: { timeoutMs?: number; signal?: AbortSignal } = {},
835
+ ): Promise<T> {
836
+ // Closed is closed for every way in: a request after it would start a worker nobody stops.
837
+ if (this.#closed) {
838
+ return Promise.reject(new ConnectionError('The SQLite connection was closed.'))
839
+ }
840
+ return this.#lane.send<T>(message, options)
359
841
  }
360
842
 
361
843
  #run(
@@ -367,24 +849,54 @@ class SqliteDriver implements Driver {
367
849
  timeoutMs: number
368
850
  signal?: AbortSignal
369
851
  transaction?: boolean
852
+ /** Someone's own SQL, not the driver's: it runs on a handle of its own, closed after. */
853
+ own?: boolean
370
854
  },
371
855
  ) {
372
- return this.#send<{
856
+ const message = {
857
+ type: 'run',
858
+ sql,
859
+ params,
860
+ maxRows: options.maxRows,
861
+ write: options.write,
862
+ transaction: options.transaction ?? false,
863
+ own: options.own ?? false,
864
+ }
865
+ type Ran = {
373
866
  columns: { name: string; type: string }[]
374
867
  rows: (string | null)[][]
375
868
  truncated: boolean
376
869
  changes: number | null
377
- }>(
378
- {
379
- type: 'run',
380
- sql,
381
- params,
382
- maxRows: options.maxRows,
383
- write: options.write,
384
- transaction: options.transaction ?? false,
385
- },
386
- options,
387
- )
870
+ }
871
+ // In its turn among the driver's statements, as when one worker ran both: two writers on
872
+ // the file at once would have one of them find it locked.
873
+ if (options.own) {
874
+ return this.#lane.after(async () => {
875
+ if (this.#closed) throw new ConnectionError('The SQLite connection was closed.')
876
+ if (options.write) this.#writing += 1
877
+ try {
878
+ return await this.#own.send<Ran>(message, options)
879
+ } catch (error) {
880
+ // A write stopped part-way may have left its journal: undone here, by the driver's
881
+ // own handle, before the grid's next read finds it and can't.
882
+ if (options.write && stoppedPartWay(error)) {
883
+ await this.#own.gone()
884
+ await this.#lane
885
+ .send({ type: 'recover' }, { timeoutMs: 30_000, now: true })
886
+ .catch((failed: unknown) =>
887
+ console.error(
888
+ 'otw-db: could not recover the SQLite file after a stopped write',
889
+ failed,
890
+ ),
891
+ )
892
+ }
893
+ throw error
894
+ } finally {
895
+ if (options.write) this.#writing -= 1
896
+ }
897
+ })
898
+ }
899
+ return this.#send<Ran>(message, options)
388
900
  }
389
901
 
390
902
  #catalog(sql: string, params: unknown[] = []) {
@@ -488,11 +1000,40 @@ class SqliteDriver implements Driver {
488
1000
  }
489
1001
  }
490
1002
 
1003
+ /**
1004
+ * What a statement must know of the table's columns that their values don't say: which hold
1005
+ * bytes, and which SQLite computes itself. A column holds bytes when it's declared BLOB, or
1006
+ * with no type at all: SQLite lets any column hold a blob, but those are where they're kept.
1007
+ */
1008
+ async #columns(schema: string, table: string): Promise<Map<string, ExportColumn>> {
1009
+ // table_xinfo: cid, name, type, notnull, dflt_value, pk, hidden (2 virtual, 3 stored).
1010
+ const rows = await this.#catalog(
1011
+ `PRAGMA ${doubleQuote(schema)}.table_xinfo(${doubleQuote(table)})`,
1012
+ )
1013
+ return new Map(
1014
+ rows.map(([, name, type, , , , hidden]) => [
1015
+ name!,
1016
+ {
1017
+ name: name!,
1018
+ ...(!type || /blob/i.test(type) ? { bytes: true } : {}),
1019
+ ...(hidden === '2' || hidden === '3' ? { generated: true } : {}),
1020
+ },
1021
+ ]),
1022
+ )
1023
+ }
1024
+
1025
+ /** The table's columns that hold bytes; not looked up where nothing is compared with a column. */
1026
+ async #bytes(schema: string, table: string, needed = true): Promise<ReadonlySet<string>> {
1027
+ if (!needed) return new Set()
1028
+ const columns = await this.#columns(schema, table)
1029
+ return new Set([...columns.values()].filter((c) => c.bytes).map((c) => c.name))
1030
+ }
1031
+
491
1032
  async rows(
492
1033
  { schema, table, limit, offset, order = [], filters = [] }: RowsRequest,
493
1034
  options: Omit<QueryOptions, 'access' | 'maxRows'>,
494
1035
  ): Promise<ResultSet> {
495
- const parameters = new Parameters(dialect)
1036
+ const parameters = new Parameters(dialect, await this.#bytes(schema, table, filters.length > 0))
496
1037
  const sql = `SELECT * FROM ${doubleQuote(schema)}.${doubleQuote(table)}${where(dialect, filters, parameters)}${orderBy(dialect, order)} LIMIT ${whole(limit) + 1} OFFSET ${whole(offset)}`
497
1038
  const started = performance.now()
498
1039
  const result = await this.#run(sql, parameters.values, {
@@ -512,7 +1053,7 @@ class SqliteDriver implements Driver {
512
1053
  { schema, table, filters = [] }: Pick<RowsRequest, 'schema' | 'table' | 'filters'>,
513
1054
  options: Omit<QueryOptions, 'access' | 'maxRows'>,
514
1055
  ): Promise<number> {
515
- const parameters = new Parameters(dialect)
1056
+ const parameters = new Parameters(dialect, await this.#bytes(schema, table, filters.length > 0))
516
1057
  const sql = `SELECT count(*) FROM ${doubleQuote(schema)}.${doubleQuote(table)}${where(dialect, filters, parameters)}`
517
1058
  const { rows } = await this.#run(sql, parameters.values, {
518
1059
  ...options,
@@ -528,23 +1069,41 @@ class SqliteDriver implements Driver {
528
1069
  }
529
1070
 
530
1071
  /**
531
- * One statement: read access on a read-only handle to the file, write access in a transaction,
532
- * or alone where SQLite refuses one (VACUUM).
1072
+ * One statement, on a handle of its own that's closed after it: read access opens the file
1073
+ * read-only, write access runs in a transaction, or alone where SQLite refuses one (VACUUM).
1074
+ * Nothing a statement sets up outlasts it.
533
1075
  */
534
1076
  async query(sql: string, options: QueryOptions): Promise<QueryResult> {
535
1077
  const started = performance.now()
536
1078
  const write = options.access === 'write'
537
- const run = (transaction: boolean) => this.#run(sql, [], { ...options, write, transaction })
1079
+ const command = sqliteFirstWord(sql)
1080
+ this.#refuseOtherFiles(command, sql)
1081
+ const pragma = processWidePragma(sql)
1082
+ if (pragma) {
1083
+ throw new DbAdminError(
1084
+ `PRAGMA ${pragma} reaches past this database: it sets something for every SQLite database this server has open, or names another file. It isn’t set from here.`,
1085
+ 403,
1086
+ 'not-allowed',
1087
+ )
1088
+ }
1089
+ const run = (transaction: boolean) =>
1090
+ this.#run(sql, [], { ...options, write, transaction, own: true })
538
1091
  let result
539
1092
  try {
540
- result = await run(write)
1093
+ try {
1094
+ result = await run(write)
1095
+ } catch (error) {
1096
+ if (!write || !/within a transaction/i.test((error as Error).message)) throw error
1097
+ result = await run(false)
1098
+ }
541
1099
  } catch (error) {
542
- if (!write || !/within a transaction/i.test((error as Error).message)) throw error
543
- result = await run(false)
1100
+ if (!(error instanceof LeftOpen)) throw error
1101
+ throw new DbAdminError(
1102
+ `A transaction can’t stay open here: each statement is committed as it finishes, and ${command} would leave one open.`,
1103
+ 400,
1104
+ 'no-transactions',
1105
+ )
544
1106
  }
545
- const command = (
546
- /^\s*(?:--[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*(\w+)/.exec(sql)?.[1] ?? ''
547
- ).toUpperCase()
548
1107
  return {
549
1108
  columns: result.columns,
550
1109
  rows: result.rows,
@@ -555,27 +1114,68 @@ class SqliteDriver implements Driver {
555
1114
  }
556
1115
  }
557
1116
 
1117
+ /**
1118
+ * SQLite has no roles: a connection's one boundary is the file it opens. ATTACH opens any other
1119
+ * file the process can read, and VACUUM INTO writes one anywhere it can write, even from a
1120
+ * read-only handle. Both are statements of their own, never part of another, so their first
1121
+ * word tells.
1122
+ */
1123
+ #refuseOtherFiles(command: string, sql: string): void {
1124
+ const file = basename(this.#path)
1125
+ if (command === 'ATTACH') {
1126
+ throw new DbAdminError(
1127
+ `This connection opens ${file} only: ATTACH would open another file on the server.`,
1128
+ 403,
1129
+ 'not-allowed',
1130
+ )
1131
+ }
1132
+ if (command === 'DETACH') {
1133
+ throw new DbAdminError(
1134
+ `This connection opens ${file} only: DETACH has nothing to let go of.`,
1135
+ 403,
1136
+ 'not-allowed',
1137
+ )
1138
+ }
1139
+ if (command === 'VACUUM' && /\binto\b/i.test(sql)) {
1140
+ throw new DbAdminError(
1141
+ 'VACUUM INTO writes a copy of the database to a file on the server, which this tool doesn’t do. Export the tables instead.',
1142
+ 403,
1143
+ 'not-allowed',
1144
+ )
1145
+ }
1146
+ }
1147
+
558
1148
  async apply(
559
1149
  { schema, table }: { schema: string; table: string },
560
1150
  changes: readonly Change[],
561
1151
  { timeoutMs, dryRun = false }: { timeoutMs: number; dryRun?: boolean },
562
1152
  ): Promise<ApplyResult> {
563
1153
  const target = `${doubleQuote(schema)}.${doubleQuote(table)}`
564
- const statements = changes.map((change) => changeStatement(dialect, target, change))
1154
+ const bytes = await this.#bytes(schema, table)
1155
+ const statements = changes.map((change) => changeStatement(dialect, target, change, bytes))
565
1156
  const shown = statements.map((s) => s.shown)
566
1157
  if (dryRun) return { statements: shown, applied: false }
567
- await this.#send(
568
- {
569
- type: 'apply',
570
- statements: statements.map((s) => ({
571
- sql: s.text,
572
- params: s.values,
573
- oneRow: s.oneRow,
574
- shown: s.shown,
575
- })),
576
- },
577
- { timeoutMs },
578
- )
1158
+ try {
1159
+ await this.#send(
1160
+ {
1161
+ type: 'apply',
1162
+ statements: statements.map((s) => ({
1163
+ sql: s.text,
1164
+ params: s.values,
1165
+ oneRow: s.oneRow,
1166
+ shown: s.shown,
1167
+ ...(s.check
1168
+ ? { check: { sql: s.check.text, params: s.check.values, original: s.check.original } }
1169
+ : {}),
1170
+ })),
1171
+ },
1172
+ { timeoutMs },
1173
+ )
1174
+ } catch (error) {
1175
+ // The worker rolled back; which cell, and from what to what, is said here as for the others.
1176
+ if (error instanceof Changed) refuseChanged(dialect, statements[error.index]!, error.current)
1177
+ throw error
1178
+ }
579
1179
  return { statements: shown, applied: true }
580
1180
  }
581
1181
 
@@ -587,38 +1187,84 @@ class SqliteDriver implements Driver {
587
1187
  order = [],
588
1188
  }: Pick<RowsRequest, 'schema' | 'table' | 'filters' | 'order'>,
589
1189
  { timeoutMs }: { timeoutMs: number },
590
- ): AsyncGenerator<{ columns: { name: string }[]; rows: (string | null)[][] }> {
591
- const parameters = new Parameters(dialect)
1190
+ ): AsyncGenerator<{ columns: ExportColumn[]; rows: (string | null)[][] }> {
1191
+ const known = await this.#columns(schema, table)
1192
+ const bytes = new Set([...known.values()].filter((c) => c.bytes).map((c) => c.name))
1193
+ const parameters = new Parameters(dialect, bytes)
592
1194
  const sql = `SELECT * FROM ${doubleQuote(schema)}.${doubleQuote(table)}${where(dialect, filters, parameters)}${orderBy(dialect, order)}`
593
- const { cursor, columns } = await this.#send<{ cursor: number; columns: { name: string }[] }>(
594
- { type: 'open', sql, params: parameters.values },
595
- { timeoutMs },
596
- )
597
- let done = false
1195
+ // A worker of its own: a statement of someone else's stopped at its time limit takes the
1196
+ // driver's worker with it, and would take every export being read from that worker too.
1197
+ const lane = new Lane(this.#path)
1198
+ // Mid-read, the export holds the file (in a rollback journal, no write of the host's can
1199
+ // commit meanwhile): nobody reading, it would hold it for as long as the browser stays away.
1200
+ let stalled = false
1201
+ const stall = () => {
1202
+ stalled = true
1203
+ lane.stop()
1204
+ }
598
1205
  try {
599
- for (let first = true; !done; first = false) {
600
- const batch = await this.#send<{ rows: (string | null)[][]; done: boolean }>(
1206
+ const opened = await lane.send<{ cursor: number; columns: { name: string }[] }>(
1207
+ { type: 'open', sql, params: parameters.values },
1208
+ { timeoutMs },
1209
+ )
1210
+ const cursor = opened.cursor
1211
+ const columns = opened.columns.map((c) => known.get(c.name) ?? { name: c.name })
1212
+ for (let first = true, done = false; !done; first = false) {
1213
+ const batch = await lane.send<{ rows: (string | null)[][]; done: boolean }>(
601
1214
  { type: 'next', cursor, count: EXPORT_BATCH },
602
1215
  { timeoutMs },
603
1216
  )
604
1217
  done = batch.done
605
- if (batch.rows.length || first) yield { columns, rows: batch.rows }
1218
+ if (batch.rows.length || first) {
1219
+ const waiting = setTimeout(stall, this.#exportIdleMs)
1220
+ waiting.unref()
1221
+ try {
1222
+ yield { columns, rows: batch.rows }
1223
+ } finally {
1224
+ clearTimeout(waiting)
1225
+ }
1226
+ if (stalled) throw stalledExport(this.#exportIdleMs)
1227
+ }
606
1228
  }
607
1229
  } finally {
608
- if (!done) await this.#send({ type: 'close', cursor }).catch(() => {})
1230
+ // The worker goes, and with it the cursor and its hold on the file, read to the end or not.
1231
+ await lane.close()
609
1232
  }
610
1233
  }
611
1234
 
612
1235
  async close(): Promise<void> {
613
- const worker = this.#worker
614
- this.#worker = null
615
- await this.#queue
616
- await worker?.terminate()
1236
+ // Someone's statement still running is stopped, not waited for, and those behind it don't
1237
+ // start: none has an end it must reach. A write stopped part-way is undone before the file
1238
+ // is let go of, as at a time limit.
1239
+ this.#closed = true
1240
+ const writing = this.#writing > 0
1241
+ this.#own.stop()
1242
+ if (writing) {
1243
+ await this.#own.gone()
1244
+ await this.#lane.send({ type: 'recover' }, { timeoutMs: 30_000 }).catch(() => {})
1245
+ }
1246
+ await this.#lane.close()
1247
+ await this.#own.close()
1248
+ }
1249
+ }
1250
+
1251
+ /** A statement that left a transaction open on its handle: BEGIN or SAVEPOINT, run alone. */
1252
+ class LeftOpen extends Error {}
1253
+
1254
+ /** An update's check found its cells changed, or its row gone (`current` undefined). */
1255
+ class Changed extends Error {
1256
+ constructor(
1257
+ readonly index: number,
1258
+ readonly current: (string | null)[] | undefined,
1259
+ ) {
1260
+ super('A cell was changed meanwhile.')
617
1261
  }
618
1262
  }
619
1263
 
620
1264
  /** The worker's errors as the API's. */
621
1265
  function fromWorker(error: WorkerError): Error {
1266
+ if (error.leftOpen) return new LeftOpen(error.message)
1267
+ if (error.changed) return new Changed(error.changed.index, error.changed.current ?? undefined)
622
1268
  if (error.conflict)
623
1269
  return new DbAdminError(
624
1270
  `Nothing was saved: ${error.message}.\n${error.conflict}`,