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