@otwdesign/db-core 1.3.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/backup/api.js +67 -9
  2. package/dist/backup/api.js.map +1 -1
  3. package/dist/backup/catalog.d.ts +9 -2
  4. package/dist/backup/catalog.js +42 -18
  5. package/dist/backup/catalog.js.map +1 -1
  6. package/dist/backup/dump.d.ts +6 -2
  7. package/dist/backup/dump.js +188 -20
  8. package/dist/backup/dump.js.map +1 -1
  9. package/dist/backup/restore.d.ts +9 -1
  10. package/dist/backup/restore.js +131 -11
  11. package/dist/backup/restore.js.map +1 -1
  12. package/dist/backup/split.d.ts +7 -2
  13. package/dist/backup/split.js +38 -6
  14. package/dist/backup/split.js.map +1 -1
  15. package/dist/backup/staging.d.ts +6 -1
  16. package/dist/backup/staging.js +38 -10
  17. package/dist/backup/staging.js.map +1 -1
  18. package/dist/drivers/mysql.d.ts +6 -0
  19. package/dist/drivers/mysql.js +142 -18
  20. package/dist/drivers/mysql.js.map +1 -1
  21. package/dist/drivers/pglite.d.ts +18 -3
  22. package/dist/drivers/pglite.js +357 -55
  23. package/dist/drivers/pglite.js.map +1 -1
  24. package/dist/drivers/postgres-catalog.d.ts +16 -1
  25. package/dist/drivers/postgres-catalog.js +34 -0
  26. package/dist/drivers/postgres-catalog.js.map +1 -1
  27. package/dist/drivers/postgres.d.ts +10 -0
  28. package/dist/drivers/postgres.js +203 -29
  29. package/dist/drivers/postgres.js.map +1 -1
  30. package/dist/drivers/read-only.d.ts +4 -0
  31. package/dist/drivers/read-only.js +156 -0
  32. package/dist/drivers/read-only.js.map +1 -0
  33. package/dist/drivers/sql.d.ts +51 -4
  34. package/dist/drivers/sql.js +112 -35
  35. package/dist/drivers/sql.js.map +1 -1
  36. package/dist/drivers/sqlite.d.ts +33 -1
  37. package/dist/drivers/sqlite.js +645 -69
  38. package/dist/drivers/sqlite.js.map +1 -1
  39. package/dist/export.d.ts +4 -5
  40. package/dist/export.js +21 -3
  41. package/dist/export.js.map +1 -1
  42. package/dist/format.js +7 -1
  43. package/dist/format.js.map +1 -1
  44. package/dist/handler.js +37 -15
  45. package/dist/handler.js.map +1 -1
  46. package/dist/index.d.ts +2 -2
  47. package/dist/index.js +1 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/types.d.ts +37 -3
  50. package/dist/words.d.ts +19 -0
  51. package/dist/words.js +76 -0
  52. package/dist/words.js.map +1 -0
  53. package/package.json +8 -7
  54. package/src/backup/api.ts +82 -14
  55. package/src/backup/catalog.ts +43 -18
  56. package/src/backup/dump.ts +208 -21
  57. package/src/backup/restore.ts +152 -12
  58. package/src/backup/split.ts +38 -6
  59. package/src/backup/staging.ts +51 -10
  60. package/src/drivers/mysql.ts +171 -21
  61. package/src/drivers/pglite.ts +419 -56
  62. package/src/drivers/postgres-catalog.ts +51 -1
  63. package/src/drivers/postgres.ts +241 -33
  64. package/src/drivers/read-only.ts +174 -0
  65. package/src/drivers/sql.ts +170 -37
  66. package/src/drivers/sqlite.ts +739 -98
  67. package/src/export.ts +26 -6
  68. package/src/format.ts +9 -1
  69. package/src/handler.ts +55 -19
  70. package/src/index.ts +7 -2
  71. package/src/types.ts +38 -1
  72. package/src/words.ts +67 -0
@@ -1,17 +1,30 @@
1
+ import { spawn } 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';
4
5
  import { ConnectionError, DbAdminError, QueryError } from "../errors.js";
5
- import { changeStatement, doubleQuote, orderBy, Parameters, where, whole, } from "./sql.js";
6
+ import { changeStatement, doubleQuote, EXPORT_IDLE_MS, orderBy, Parameters, refuseChanged, stalledExport, where, whole, } from "./sql.js";
6
7
  /** A value as a SQLite literal, for statements shown to people and SQL exports. */
7
8
  export function sqliteLiteral(value) {
8
9
  if (value === null)
9
10
  return 'NULL';
10
11
  return `'${value.replaceAll("'", "''")}'`;
11
12
  }
13
+ /**
14
+ * Bytes as the grid shows them, `X'1F'`, as the literal that is those bytes; null for anything
15
+ * else. SQLite never finds a blob equal to text, so a blob key compared with those letters
16
+ * matches no row.
17
+ */
18
+ export function sqliteBytes(shown) {
19
+ const hex = /^X'((?:[0-9A-Fa-f]{2})*)'$/.exec(shown)?.[1];
20
+ return hex === undefined ? null : `X'${hex.toUpperCase()}'`;
21
+ }
12
22
  const dialect = {
13
23
  identifier: doubleQuote,
14
24
  literal: sqliteLiteral,
25
+ bytes: sqliteBytes,
26
+ // A write transaction here holds the whole file.
27
+ forUpdate: '',
15
28
  placeholder: () => '?',
16
29
  text: (expression) => `CAST(${expression} AS TEXT)`,
17
30
  // SQLite's LIKE ignores case for ASCII letters, and has no escape until told.
@@ -71,10 +84,107 @@ function hasMoreStatements(sql) {
71
84
  }
72
85
  return false;
73
86
  }
74
- /** The worker's code: runs on its own thread, so a long statement never blocks the host. */
75
- const WORKER = `
76
- const { parentPort, workerData } = require('node:worker_threads')
77
- const { DatabaseSync } = require('node:sqlite')
87
+ /**
88
+ * PRAGMAs that set something for the whole process, not for the connection they're run on: with
89
+ * `hard_heap_limit = 1`, no SQLite handle in the process can read a row again, the host's own
90
+ * included, until it restarts.
91
+ */
92
+ const PROCESS_WIDE = [
93
+ 'hard_heap_limit',
94
+ 'soft_heap_limit',
95
+ 'temp_store_directory',
96
+ 'data_store_directory',
97
+ // Not the process's, but another file's: where Apple's SQLite keeps a lock, made if missing.
98
+ 'lock_proxy_file',
99
+ ];
100
+ /** A statement's first word in capitals, past spaces and comments, read a character at a time. */
101
+ function sqliteFirstWord(sql) {
102
+ let at = 0;
103
+ for (;;) {
104
+ while (at < sql.length && /\s/.test(sql[at]))
105
+ at++;
106
+ if (sql.startsWith('--', at)) {
107
+ const end = sql.indexOf('\n', at);
108
+ at = end === -1 ? sql.length : end + 1;
109
+ }
110
+ else if (sql.startsWith('/*', at)) {
111
+ const end = sql.indexOf('*/', at + 2);
112
+ at = end === -1 ? sql.length : end + 2;
113
+ }
114
+ else
115
+ break;
116
+ }
117
+ return (/^\w+/.exec(sql.slice(at, at + 64))?.[0] ?? '').toUpperCase();
118
+ }
119
+ /**
120
+ * The one of those a statement would set, by its tokens: past comments, EXPLAIN [QUERY PLAN] (a
121
+ * PRAGMA acts when it's prepared, explained or not) and a schema's name, however the name is
122
+ * quoted. Null for any other statement, and for a PRAGMA that only reads. Self-contained.
123
+ */
124
+ export function processWidePragma(sql) {
125
+ let at = 0;
126
+ const skip = () => {
127
+ for (;;) {
128
+ while (at < sql.length && /\s/.test(sql[at]))
129
+ at++;
130
+ if (sql.startsWith('--', at)) {
131
+ const end = sql.indexOf('\n', at);
132
+ at = end === -1 ? sql.length : end + 1;
133
+ }
134
+ else if (sql.startsWith('/*', at)) {
135
+ const end = sql.indexOf('*/', at + 2);
136
+ at = end === -1 ? sql.length : end + 2;
137
+ }
138
+ else
139
+ return;
140
+ }
141
+ };
142
+ const name = () => {
143
+ skip();
144
+ const open = sql[at];
145
+ const close = open === '[' ? ']' : open === '"' || open === '`' || open === "'" ? open : null;
146
+ if (close) {
147
+ const end = sql.indexOf(close, at + 1);
148
+ if (end === -1)
149
+ return null;
150
+ const quoted = sql.slice(at + 1, end);
151
+ at = end + 1;
152
+ return quoted.toLowerCase();
153
+ }
154
+ const word = /^[A-Za-z_][\w$]*/.exec(sql.slice(at, at + 64))?.[0];
155
+ if (!word)
156
+ return null;
157
+ at += word.length;
158
+ return word.toLowerCase();
159
+ };
160
+ let word = name();
161
+ if (word === 'explain') {
162
+ word = name();
163
+ if (word === 'query') {
164
+ name();
165
+ word = name();
166
+ }
167
+ }
168
+ if (word !== 'pragma')
169
+ return null;
170
+ let pragma = name();
171
+ skip();
172
+ if (sql[at] === '.') {
173
+ at++;
174
+ pragma = name();
175
+ skip();
176
+ }
177
+ if (!pragma || !PROCESS_WIDE.includes(pragma))
178
+ return null;
179
+ return sql[at] === '=' || sql[at] === '(' ? pragma : null;
180
+ }
181
+ /**
182
+ * The worker's code, for a thread or a process of its own: `parentPort` and `workerData` are
183
+ * given by whichever of the two openings below it runs after.
184
+ */
185
+ const WORKER_BODY = `
186
+ const { DatabaseSync, constants } = require('node:sqlite')
187
+ const PROCESS_WIDE = ${JSON.stringify(PROCESS_WIDE)}
78
188
  ${hasMoreStatements.toString()}
79
189
  let reader, writer
80
190
  const cursors = new Map()
@@ -110,8 +220,28 @@ function row(statement, columns, value) {
110
220
  return Array.isArray(value) ? value.map(text) : columns.map((c) => text(value[c.name]))
111
221
  }
112
222
 
113
- function run({ sql, params, maxRows, write, transaction }) {
114
- const database = db(write)
223
+ // Someone's own SQL runs on a handle of its own, closed after it: what the statement sets up (a
224
+ // TEMP view named as a table is, a PRAGMA, a transaction left open) ends with it, and never
225
+ // reaches the next person's statement, the grid's reads and edits, or the host's file.
226
+ function run(message) {
227
+ if (!message.own) return runOn(db(message.write), message)
228
+ const database = new DatabaseSync(workerData.path, { readOnly: !message.write })
229
+ // Behind the driver's reading of the statement, where this Node has it: SQLite itself says
230
+ // which PRAGMA a statement sets, whatever its text.
231
+ if (database.setAuthorizer && constants && constants.SQLITE_PRAGMA !== undefined) {
232
+ database.setAuthorizer((action, name, value) =>
233
+ action === constants.SQLITE_PRAGMA && value != null && PROCESS_WIDE.includes(String(name).toLowerCase())
234
+ ? constants.SQLITE_DENY
235
+ : constants.SQLITE_OK)
236
+ }
237
+ try {
238
+ return runOn(database, message)
239
+ } finally {
240
+ database.close()
241
+ }
242
+ }
243
+
244
+ function runOn(database, { sql, params, maxRows, transaction }) {
115
245
  const statement = prepare(database, sql)
116
246
  const columns = columnsOf(statement)
117
247
  if (!columns.length) {
@@ -119,9 +249,15 @@ function run({ sql, params, maxRows, write, transaction }) {
119
249
  try {
120
250
  const { changes } = statement.run(...params)
121
251
  if (transaction) database.exec('COMMIT')
252
+ else if (database.isTransaction) {
253
+ // BEGIN or SAVEPOINT, run alone: nothing after it would ever commit.
254
+ const error = new Error('a transaction left open')
255
+ error.leftOpen = true
256
+ throw error
257
+ }
122
258
  return { columns, rows: [], truncated: false, changes: Number(changes) }
123
259
  } catch (error) {
124
- if (transaction && database.isTransaction) database.exec('ROLLBACK')
260
+ if (database.isTransaction) database.exec('ROLLBACK')
125
261
  throw error
126
262
  }
127
263
  }
@@ -141,7 +277,22 @@ function apply({ statements }) {
141
277
  const database = db(true)
142
278
  database.exec('BEGIN IMMEDIATE')
143
279
  try {
144
- for (const { sql, params, oneRow, shown } of statements) {
280
+ for (const [index, { sql, params, oneRow, shown, check }] of statements.entries()) {
281
+ if (check) {
282
+ // The cells as the grid read them, for the driver to compare with what they held.
283
+ const reader = prepare(database, check.sql)
284
+ const columns = columnsOf(reader)
285
+ let current = null
286
+ for (const value of reader.iterate(...check.params)) {
287
+ current = row(reader, columns, value)
288
+ break
289
+ }
290
+ if (!current || check.original.some((was, i) => was !== current[i])) {
291
+ const error = new Error('a cell was changed meanwhile')
292
+ error.changed = { index, current }
293
+ throw error
294
+ }
295
+ }
145
296
  const { changes } = prepare(database, sql).run(...params)
146
297
  if (oneRow && Number(changes) !== 1) {
147
298
  const error = new Error(Number(changes) === 0 ? 'its row is gone or its key changed' : 'its key matched ' + changes + ' rows')
@@ -187,10 +338,35 @@ function close({ cursor }) {
187
338
  return {}
188
339
  }
189
340
 
190
- const handlers = { run, apply, open, next, close }
341
+ // A write killed part-way (its process, at its time limit) can leave its journal beside the
342
+ // file: the next handle that may write undoes it, and one that may only read can't, and fails.
343
+ function recover() {
344
+ db(true).prepare('SELECT count(*) FROM sqlite_master').get()
345
+ return true
346
+ }
347
+
348
+ const handlers = { run, apply, open, next, close, recover }
349
+ // A read that finds a journal left by a writer that was killed (this driver's own, at a time
350
+ // limit; the server itself, stopped mid-write) can't undo it, and fails. The journal is undone
351
+ // by a handle that may write, and the read is asked again.
352
+ function handle(message) {
353
+ try {
354
+ return handlers[message.type](message)
355
+ } catch (error) {
356
+ const hot = /attempt to write a readonly database/i.test(String(error && error.message))
357
+ if (!hot || message.write || message.type === 'apply' || message.type === 'recover') throw error
358
+ try {
359
+ recover()
360
+ } catch {
361
+ throw error
362
+ }
363
+ return handlers[message.type](message)
364
+ }
365
+ }
366
+
191
367
  parentPort.on('message', (message) => {
192
368
  try {
193
- parentPort.postMessage({ id: message.id, result: handlers[message.type](message) })
369
+ parentPort.postMessage({ id: message.id, result: handle(message) })
194
370
  } catch (error) {
195
371
  parentPort.postMessage({
196
372
  id: message.id,
@@ -200,11 +376,63 @@ parentPort.on('message', (message) => {
200
376
  errcode: error.errcode,
201
377
  conflict: error.conflict,
202
378
  oneStatement: error.oneStatement === true,
379
+ leftOpen: error.leftOpen === true,
380
+ changed: error.changed,
203
381
  },
204
382
  })
205
383
  }
206
384
  })
207
385
  `;
386
+ /** On a thread: a long statement never blocks the host. */
387
+ const THREAD_WORKER = `
388
+ const { parentPort, workerData } = require('node:worker_threads')
389
+ ${WORKER_BODY}`;
390
+ /**
391
+ * In a process: for someone's own SQL. A statement can stay inside SQLite for as long as it
392
+ * likes (a recursive query with no end), where nothing stops a thread: stopping the thread stops
393
+ * its JavaScript, and there is none running. A process can be killed, and what it held on the
394
+ * file goes with it.
395
+ *
396
+ * The statement runs on a thread of that process, so its first thread is never inside SQLite:
397
+ * it always hears that the server has gone (stopped, crashed, killed), and ends the process,
398
+ * statement and all. Left to one thread, a statement with no end would outlive the server that
399
+ * asked for it, and keep a processor for itself. Exported for its test.
400
+ */
401
+ export const SQLITE_PROCESS_WORKER = `
402
+ const { Worker } = require('node:worker_threads')
403
+ // Not asked to stop, which waits for the thread: killed, as the server would have.
404
+ const die = () => process.kill(process.pid, 'SIGKILL')
405
+ process.on('disconnect', die)
406
+ const worker = new Worker(${JSON.stringify(THREAD_WORKER)}, {
407
+ eval: true,
408
+ workerData: JSON.parse(process.env.OTW_DB_SQLITE_WORKER),
409
+ })
410
+ worker.on('message', (message) => {
411
+ try {
412
+ process.send(message)
413
+ } catch {
414
+ die()
415
+ }
416
+ })
417
+ worker.on('error', die)
418
+ worker.on('exit', die)
419
+ process.on('message', (message) => worker.postMessage(message))
420
+ // Said once the thread is up: a process that never says it can't be waited on for answers.
421
+ worker.once('online', () => process.send({ ready: true }))
422
+ `;
423
+ /** What the process is given of the server's environment: where programs and temporary files are. */
424
+ const PROCESS_ENV = [
425
+ 'PATH',
426
+ 'SystemRoot',
427
+ 'TMPDIR',
428
+ 'TEMP',
429
+ 'TMP',
430
+ 'SQLITE_TMPDIR',
431
+ 'HOME',
432
+ 'USERPROFILE',
433
+ ];
434
+ /** How long a process with nothing to run is kept before it's let go of. */
435
+ const PROCESS_IDLE_MS = 60_000;
208
436
  /** The file a `sqlite:` or `file:` address names. */
209
437
  export function sqlitePath(url) {
210
438
  let path = url.replace(/^(sqlite|file):/i, '');
@@ -222,29 +450,46 @@ export function sqlitePath(url) {
222
450
  * time on a worker thread: a long one never blocks the host, and stopping the worker stops it.
223
451
  * Read access opens the file read-only.
224
452
  */
225
- export function sqliteDriver(url) {
226
- return new SqliteDriver(sqlitePath(url));
453
+ export function sqliteDriver(url, options = {}) {
454
+ return new SqliteDriver(sqlitePath(url), options);
227
455
  }
228
- class SqliteDriver {
229
- kind = 'sqlite';
230
- capabilities = { schemas: false, transactionalDdl: true, cancel: true };
231
- sql = { identifier: doubleQuote, literal: sqliteLiteral };
456
+ /** How long a process has to say it's up before the lane does without one. */
457
+ const PROCESS_START_MS = 5_000;
458
+ /** This server can't start a process: the lane goes on a thread instead, as it did before. */
459
+ class NoProcess extends Error {
460
+ }
461
+ /**
462
+ * A worker of its own with the file open on it, and the requests waiting for it. The driver has
463
+ * one for its statements; each export has another, so stopping a statement (which stops its
464
+ * worker) never ends an export under way, and an export nobody reads can be let go of by
465
+ * stopping its own. Those are threads. Someone's own SQL has a third, a process: see
466
+ * SQLITE_PROCESS_WORKER.
467
+ */
468
+ class Lane {
232
469
  #path;
470
+ #kind;
233
471
  #worker = null;
234
472
  #pending = new Map();
235
473
  #next = 1;
236
474
  /** One request at a time: the worker's connection is single-threaded. */
237
475
  #queue = Promise.resolve();
238
- constructor(path) {
476
+ #idle;
477
+ /** The last worker stopped, on its way out. */
478
+ #going = Promise.resolve();
479
+ constructor(path, kind = 'thread') {
239
480
  this.#path = path;
481
+ this.#kind = kind;
240
482
  }
241
483
  #spawn() {
242
484
  if (this.#worker)
243
485
  return this.#worker;
244
486
  if (!existsSync(this.#path))
245
487
  throw new ConnectionError(`There's no SQLite database at ${this.#path}.`);
246
- const worker = new Worker(WORKER, { eval: true, workerData: { path: this.#path } });
247
- worker.on('message', ({ id, result, error }) => {
488
+ // The requests this worker was sent: when it goes, those fail, and no others. A worker
489
+ // stopped at a time limit is still on its way out when the next request has a new one.
490
+ const mine = new Set();
491
+ const answer = ({ id, result, error }) => {
492
+ mine.delete(id);
248
493
  const waiting = this.#pending.get(id);
249
494
  this.#pending.delete(id);
250
495
  if (!waiting)
@@ -253,46 +498,157 @@ class SqliteDriver {
253
498
  waiting.reject(fromWorker(error));
254
499
  else
255
500
  waiting.resolve(result);
256
- });
501
+ };
257
502
  const fail = (error) => {
258
- for (const waiting of this.#pending.values())
259
- waiting.reject(error);
260
- this.#pending.clear();
261
- if (this.#worker === worker)
503
+ for (const id of mine) {
504
+ this.#pending.get(id)?.reject(error);
505
+ this.#pending.delete(id);
506
+ }
507
+ mine.clear();
508
+ if (this.#worker === running)
262
509
  this.#worker = null;
263
510
  };
511
+ const sent = (id) => void mine.add(id);
512
+ const running = this.#kind === 'thread' ? this.#thread(answer, fail, sent) : this.#process(answer, fail, sent);
513
+ this.#worker = running;
514
+ return running;
515
+ }
516
+ #thread(answer, fail, sent) {
517
+ const worker = new Worker(THREAD_WORKER, { eval: true, workerData: { path: this.#path } });
518
+ worker.on('message', answer);
264
519
  worker.on('error', (error) => fail(new ConnectionError(`The SQLite worker failed: ${error.message}`)));
265
520
  worker.on('exit', () => fail(new ConnectionError('The SQLite worker stopped.')));
266
- this.#worker = worker;
267
- return worker;
521
+ return {
522
+ post: (message) => {
523
+ sent(message.id);
524
+ worker.postMessage(message);
525
+ },
526
+ stop: async () => void (await worker.terminate()),
527
+ };
528
+ }
529
+ #process(answer, fail, sent) {
530
+ const env = {
531
+ OTW_DB_SQLITE_WORKER: JSON.stringify({ path: this.#path }),
532
+ };
533
+ for (const name of PROCESS_ENV)
534
+ if (process.env[name] !== undefined)
535
+ env[name] = process.env[name];
536
+ let child;
537
+ try {
538
+ child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', '-e', SQLITE_PROCESS_WORKER],
539
+ // Nothing to read or write but what it's sent: its errors go where the server's do.
540
+ {
541
+ stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
542
+ serialization: 'advanced',
543
+ // An app's own types may ask more of an environment (Next's wants NODE_ENV): this one is
544
+ // the process's whole environment, by design.
545
+ env: env,
546
+ windowsHide: true,
547
+ });
548
+ }
549
+ catch (error) {
550
+ throw new NoProcess(error.message);
551
+ }
552
+ const gone = () => child.exitCode !== null || child.signalCode !== null;
553
+ // Nothing is sent until the process has said it's up. One that starts and stops at once (a
554
+ // Node that can't run it), or starts and never speaks, is no process to wait on: the lane
555
+ // goes on a thread, as where none starts, and since nothing was sent, nothing runs twice.
556
+ let ready = false;
557
+ let deliberate = false;
558
+ const unsent = [];
559
+ const starting = setTimeout(() => {
560
+ // Decided after what has already arrived is read: a server too busy to read its messages
561
+ // for a while finds this timer due before the process's first word, which is waiting.
562
+ setImmediate(() => {
563
+ if (!ready && !gone())
564
+ child.kill('SIGKILL');
565
+ });
566
+ }, PROCESS_START_MS);
567
+ starting.unref();
568
+ const stopped = () => deliberate || ready
569
+ ? new ConnectionError('The SQLite worker stopped.')
570
+ : new NoProcess('it stopped before it was up');
571
+ child.on('message', (message) => {
572
+ if (!message.ready)
573
+ return answer(message);
574
+ ready = true;
575
+ clearTimeout(starting);
576
+ for (const waiting of unsent.splice(0))
577
+ child.send(waiting);
578
+ });
579
+ child.on('error', (error) => {
580
+ clearTimeout(starting);
581
+ fail(child.pid === undefined
582
+ ? new NoProcess(error.message)
583
+ : ready
584
+ ? new ConnectionError(`The SQLite worker failed: ${error.message}`)
585
+ : stopped());
586
+ });
587
+ child.on('exit', () => {
588
+ clearTimeout(starting);
589
+ fail(stopped());
590
+ });
591
+ return {
592
+ post: (message) => {
593
+ sent(message.id);
594
+ if (!ready)
595
+ unsent.push(message);
596
+ else if (child.connected)
597
+ child.send(message);
598
+ },
599
+ stop: () => new Promise((resolve) => {
600
+ // Stopped on purpose is stopped: not a process that couldn't start, to try again without.
601
+ deliberate = true;
602
+ clearTimeout(starting);
603
+ if (child.pid === undefined || gone())
604
+ return resolve();
605
+ child.once('exit', () => resolve());
606
+ // Not asked: killed. SQLite, mid-statement, hears nothing else.
607
+ child.kill('SIGKILL');
608
+ }),
609
+ };
610
+ }
611
+ /** Runs `work` when the requests before it are done, and holds those after it until it is. */
612
+ after(work) {
613
+ const result = this.#queue.then(work, work);
614
+ this.#queue = result.catch(() => { });
615
+ return result;
268
616
  }
269
617
  /**
270
618
  * Sends a request when the ones before it are done. The timer and the signal stop the worker,
271
619
  * which stops the statement; the next request starts a fresh one.
272
620
  */
273
- #send(message, options = {}) {
621
+ send(message,
622
+ /** `now`: without waiting its turn, for whoever is already having theirs (`after`). */
623
+ options = {}) {
274
624
  const run = async () => {
275
625
  if (options.signal?.aborted)
276
626
  throw new DbAdminError('The query was canceled.', 409, 'canceled');
627
+ clearTimeout(this.#idle);
277
628
  const worker = this.#spawn();
278
629
  const id = this.#next++;
279
630
  return new Promise((resolve, reject) => {
280
631
  let stopped = null;
632
+ let answered = false;
281
633
  const stop = (error) => {
282
- if (stopped)
634
+ if (stopped || answered)
283
635
  return;
284
636
  stopped = error;
285
637
  this.#pending.delete(id);
286
638
  this.#worker = null;
287
- void worker.terminate();
639
+ this.#going = worker.stop().catch(() => { });
288
640
  reject(error);
289
641
  };
290
642
  const timer = options.timeoutMs
291
- ? setTimeout(() => stop(new QueryError(`The statement ran past its ${options.timeoutMs} ms limit and was stopped.`, 'SQLITE_INTERRUPT')), options.timeoutMs)
643
+ ? setTimeout(() =>
644
+ // After what has already arrived is read: a statement that finished while the
645
+ // server was too busy to hear it isn't stopped, and said to have been.
646
+ setImmediate(() => stop(new QueryError(`The statement ran past its ${options.timeoutMs} ms limit and was stopped.`, 'SQLITE_INTERRUPT'))), options.timeoutMs)
292
647
  : undefined;
293
648
  const abort = () => stop(new DbAdminError('The query was canceled.', 409, 'canceled'));
294
649
  options.signal?.addEventListener('abort', abort, { once: true });
295
650
  const done = () => {
651
+ answered = true;
296
652
  clearTimeout(timer);
297
653
  options.signal?.removeEventListener('abort', abort);
298
654
  };
@@ -306,22 +662,127 @@ class SqliteDriver {
306
662
  reject(error);
307
663
  },
308
664
  });
309
- worker.postMessage({ ...message, id });
665
+ worker.post({ ...message, id });
310
666
  });
311
667
  };
312
- const result = this.#queue.then(run, run);
313
- this.#queue = result.catch(() => { });
314
- return result;
668
+ const attempt = async () => {
669
+ try {
670
+ return await run();
671
+ }
672
+ catch (error) {
673
+ if (!(error instanceof NoProcess))
674
+ throw error;
675
+ this.#kind = 'thread';
676
+ return await run();
677
+ }
678
+ finally {
679
+ this.#rest();
680
+ }
681
+ };
682
+ return options.now ? attempt() : this.after(attempt);
683
+ }
684
+ /** Done once a worker stopped at its limit, or canceled, has really gone. */
685
+ gone() {
686
+ return this.#going;
687
+ }
688
+ /** A process with nothing to run is let go of after a while: it's a whole Node, kept for one file. */
689
+ #rest() {
690
+ if (this.#kind !== 'process')
691
+ return;
692
+ clearTimeout(this.#idle);
693
+ this.#idle = setTimeout(() => {
694
+ if (this.#pending.size === 0)
695
+ this.stop();
696
+ }, PROCESS_IDLE_MS);
697
+ this.#idle.unref();
698
+ }
699
+ /** Stops the worker once the requests before this are done: what it held on the file goes. */
700
+ async close() {
701
+ await this.#queue;
702
+ clearTimeout(this.#idle);
703
+ const worker = this.#worker;
704
+ this.#worker = null;
705
+ await worker?.stop();
706
+ }
707
+ /** Stops the worker now, whatever it's doing: the requests it had fail. */
708
+ stop() {
709
+ clearTimeout(this.#idle);
710
+ const worker = this.#worker;
711
+ this.#worker = null;
712
+ if (worker)
713
+ this.#going = worker.stop().catch(() => { });
714
+ }
715
+ }
716
+ /** Whether a statement was stopped while it ran: at its time limit, or canceled. */
717
+ function stoppedPartWay(error) {
718
+ return ((error instanceof QueryError && error.sqlState === 'SQLITE_INTERRUPT') ||
719
+ (error instanceof DbAdminError && error.code === 'canceled'));
720
+ }
721
+ class SqliteDriver {
722
+ kind = 'sqlite';
723
+ capabilities = { schemas: false, transactionalDdl: true, cancel: true };
724
+ sql = { identifier: doubleQuote, literal: sqliteLiteral, bytes: sqliteBytes };
725
+ #path;
726
+ #exportIdleMs;
727
+ /** The driver's own statements, one at a time. */
728
+ #lane;
729
+ /** Someone's own SQL: in a process, which a time limit can really stop. */
730
+ #own;
731
+ /** Their writes under way, and whether the driver was closed: no statement starts after that. */
732
+ #writing = 0;
733
+ #closed = false;
734
+ constructor(path, options) {
735
+ this.#path = path;
736
+ this.#exportIdleMs = options.exportIdleMs ?? EXPORT_IDLE_MS;
737
+ this.#lane = new Lane(path);
738
+ this.#own = new Lane(path, 'process');
739
+ }
740
+ #send(message, options = {}) {
741
+ // Closed is closed for every way in: a request after it would start a worker nobody stops.
742
+ if (this.#closed) {
743
+ return Promise.reject(new ConnectionError('The SQLite connection was closed.'));
744
+ }
745
+ return this.#lane.send(message, options);
315
746
  }
316
747
  #run(sql, params, options) {
317
- return this.#send({
748
+ const message = {
318
749
  type: 'run',
319
750
  sql,
320
751
  params,
321
752
  maxRows: options.maxRows,
322
753
  write: options.write,
323
754
  transaction: options.transaction ?? false,
324
- }, options);
755
+ own: options.own ?? false,
756
+ };
757
+ // In its turn among the driver's statements, as when one worker ran both: two writers on
758
+ // the file at once would have one of them find it locked.
759
+ if (options.own) {
760
+ return this.#lane.after(async () => {
761
+ if (this.#closed)
762
+ throw new ConnectionError('The SQLite connection was closed.');
763
+ if (options.write)
764
+ this.#writing += 1;
765
+ try {
766
+ return await this.#own.send(message, options);
767
+ }
768
+ catch (error) {
769
+ // A write stopped part-way may have left its journal: undone here, by the driver's
770
+ // own handle, before the grid's next read finds it and can't.
771
+ if (options.write && stoppedPartWay(error)) {
772
+ await this.#own.gone();
773
+ await this.#lane
774
+ .send({ type: 'recover' }, { timeoutMs: 30_000, now: true })
775
+ .catch((failed) => console.error('otw-db: could not recover the SQLite file after a stopped write', failed));
776
+ }
777
+ throw error;
778
+ }
779
+ finally {
780
+ if (options.write)
781
+ this.#writing -= 1;
782
+ }
783
+ });
784
+ }
785
+ return this.#send(message, options);
325
786
  }
326
787
  #catalog(sql, params = []) {
327
788
  return this.#run(sql, params, { maxRows: 100_000, write: false, timeoutMs: 30_000 }).then((r) => r.rows);
@@ -405,8 +866,32 @@ class SqliteDriver {
405
866
  checks: [],
406
867
  };
407
868
  }
869
+ /**
870
+ * What a statement must know of the table's columns that their values don't say: which hold
871
+ * bytes, and which SQLite computes itself. A column holds bytes when it's declared BLOB, or
872
+ * with no type at all: SQLite lets any column hold a blob, but those are where they're kept.
873
+ */
874
+ async #columns(schema, table) {
875
+ // table_xinfo: cid, name, type, notnull, dflt_value, pk, hidden (2 virtual, 3 stored).
876
+ const rows = await this.#catalog(`PRAGMA ${doubleQuote(schema)}.table_xinfo(${doubleQuote(table)})`);
877
+ return new Map(rows.map(([, name, type, , , , hidden]) => [
878
+ name,
879
+ {
880
+ name: name,
881
+ ...(!type || /blob/i.test(type) ? { bytes: true } : {}),
882
+ ...(hidden === '2' || hidden === '3' ? { generated: true } : {}),
883
+ },
884
+ ]));
885
+ }
886
+ /** The table's columns that hold bytes; not looked up where nothing is compared with a column. */
887
+ async #bytes(schema, table, needed = true) {
888
+ if (!needed)
889
+ return new Set();
890
+ const columns = await this.#columns(schema, table);
891
+ return new Set([...columns.values()].filter((c) => c.bytes).map((c) => c.name));
892
+ }
408
893
  async rows({ schema, table, limit, offset, order = [], filters = [] }, options) {
409
- const parameters = new Parameters(dialect);
894
+ const parameters = new Parameters(dialect, await this.#bytes(schema, table, filters.length > 0));
410
895
  const sql = `SELECT * FROM ${doubleQuote(schema)}.${doubleQuote(table)}${where(dialect, filters, parameters)}${orderBy(dialect, order)} LIMIT ${whole(limit) + 1} OFFSET ${whole(offset)}`;
411
896
  const started = performance.now();
412
897
  const result = await this.#run(sql, parameters.values, {
@@ -422,7 +907,7 @@ class SqliteDriver {
422
907
  };
423
908
  }
424
909
  async count({ schema, table, filters = [] }, options) {
425
- const parameters = new Parameters(dialect);
910
+ const parameters = new Parameters(dialect, await this.#bytes(schema, table, filters.length > 0));
426
911
  const sql = `SELECT count(*) FROM ${doubleQuote(schema)}.${doubleQuote(table)}${where(dialect, filters, parameters)}`;
427
912
  const { rows } = await this.#run(sql, parameters.values, {
428
913
  ...options,
@@ -436,23 +921,36 @@ class SqliteDriver {
436
921
  return { product: 'SQLite', version, database: basename(this.#path), user: '' };
437
922
  }
438
923
  /**
439
- * One statement: read access on a read-only handle to the file, write access in a transaction,
440
- * or alone where SQLite refuses one (VACUUM).
924
+ * One statement, on a handle of its own that's closed after it: read access opens the file
925
+ * read-only, write access runs in a transaction, or alone where SQLite refuses one (VACUUM).
926
+ * Nothing a statement sets up outlasts it.
441
927
  */
442
928
  async query(sql, options) {
443
929
  const started = performance.now();
444
930
  const write = options.access === 'write';
445
- const run = (transaction) => this.#run(sql, [], { ...options, write, transaction });
931
+ const command = sqliteFirstWord(sql);
932
+ this.#refuseOtherFiles(command, sql);
933
+ const pragma = processWidePragma(sql);
934
+ if (pragma) {
935
+ throw new DbAdminError(`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.`, 403, 'not-allowed');
936
+ }
937
+ const run = (transaction) => this.#run(sql, [], { ...options, write, transaction, own: true });
446
938
  let result;
447
939
  try {
448
- result = await run(write);
940
+ try {
941
+ result = await run(write);
942
+ }
943
+ catch (error) {
944
+ if (!write || !/within a transaction/i.test(error.message))
945
+ throw error;
946
+ result = await run(false);
947
+ }
449
948
  }
450
949
  catch (error) {
451
- if (!write || !/within a transaction/i.test(error.message))
950
+ if (!(error instanceof LeftOpen))
452
951
  throw error;
453
- result = await run(false);
952
+ throw new DbAdminError(`A transaction can’t stay open here: each statement is committed as it finishes, and ${command} would leave one open.`, 400, 'no-transactions');
454
953
  }
455
- const command = (/^\s*(?:--[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*(\w+)/.exec(sql)?.[1] ?? '').toUpperCase();
456
954
  return {
457
955
  columns: result.columns,
458
956
  rows: result.rows,
@@ -462,50 +960,128 @@ class SqliteDriver {
462
960
  durationMs: Math.round(performance.now() - started),
463
961
  };
464
962
  }
963
+ /**
964
+ * SQLite has no roles: a connection's one boundary is the file it opens. ATTACH opens any other
965
+ * file the process can read, and VACUUM INTO writes one anywhere it can write, even from a
966
+ * read-only handle. Both are statements of their own, never part of another, so their first
967
+ * word tells.
968
+ */
969
+ #refuseOtherFiles(command, sql) {
970
+ const file = basename(this.#path);
971
+ if (command === 'ATTACH') {
972
+ throw new DbAdminError(`This connection opens ${file} only: ATTACH would open another file on the server.`, 403, 'not-allowed');
973
+ }
974
+ if (command === 'DETACH') {
975
+ throw new DbAdminError(`This connection opens ${file} only: DETACH has nothing to let go of.`, 403, 'not-allowed');
976
+ }
977
+ if (command === 'VACUUM' && /\binto\b/i.test(sql)) {
978
+ throw new DbAdminError('VACUUM INTO writes a copy of the database to a file on the server, which this tool doesn’t do. Export the tables instead.', 403, 'not-allowed');
979
+ }
980
+ }
465
981
  async apply({ schema, table }, changes, { timeoutMs, dryRun = false }) {
466
982
  const target = `${doubleQuote(schema)}.${doubleQuote(table)}`;
467
- const statements = changes.map((change) => changeStatement(dialect, target, change));
983
+ const bytes = await this.#bytes(schema, table);
984
+ const statements = changes.map((change) => changeStatement(dialect, target, change, bytes));
468
985
  const shown = statements.map((s) => s.shown);
469
986
  if (dryRun)
470
987
  return { statements: shown, applied: false };
471
- await this.#send({
472
- type: 'apply',
473
- statements: statements.map((s) => ({
474
- sql: s.text,
475
- params: s.values,
476
- oneRow: s.oneRow,
477
- shown: s.shown,
478
- })),
479
- }, { timeoutMs });
988
+ try {
989
+ await this.#send({
990
+ type: 'apply',
991
+ statements: statements.map((s) => ({
992
+ sql: s.text,
993
+ params: s.values,
994
+ oneRow: s.oneRow,
995
+ shown: s.shown,
996
+ ...(s.check
997
+ ? { check: { sql: s.check.text, params: s.check.values, original: s.check.original } }
998
+ : {}),
999
+ })),
1000
+ }, { timeoutMs });
1001
+ }
1002
+ catch (error) {
1003
+ // The worker rolled back; which cell, and from what to what, is said here as for the others.
1004
+ if (error instanceof Changed)
1005
+ refuseChanged(dialect, statements[error.index], error.current);
1006
+ throw error;
1007
+ }
480
1008
  return { statements: shown, applied: true };
481
1009
  }
482
1010
  async *export({ schema, table, filters = [], order = [], }, { timeoutMs }) {
483
- const parameters = new Parameters(dialect);
1011
+ const known = await this.#columns(schema, table);
1012
+ const bytes = new Set([...known.values()].filter((c) => c.bytes).map((c) => c.name));
1013
+ const parameters = new Parameters(dialect, bytes);
484
1014
  const sql = `SELECT * FROM ${doubleQuote(schema)}.${doubleQuote(table)}${where(dialect, filters, parameters)}${orderBy(dialect, order)}`;
485
- const { cursor, columns } = await this.#send({ type: 'open', sql, params: parameters.values }, { timeoutMs });
486
- let done = false;
1015
+ // A worker of its own: a statement of someone else's stopped at its time limit takes the
1016
+ // driver's worker with it, and would take every export being read from that worker too.
1017
+ const lane = new Lane(this.#path);
1018
+ // Mid-read, the export holds the file (in a rollback journal, no write of the host's can
1019
+ // commit meanwhile): nobody reading, it would hold it for as long as the browser stays away.
1020
+ let stalled = false;
1021
+ const stall = () => {
1022
+ stalled = true;
1023
+ lane.stop();
1024
+ };
487
1025
  try {
488
- for (let first = true; !done; first = false) {
489
- const batch = await this.#send({ type: 'next', cursor, count: EXPORT_BATCH }, { timeoutMs });
1026
+ const opened = await lane.send({ type: 'open', sql, params: parameters.values }, { timeoutMs });
1027
+ const cursor = opened.cursor;
1028
+ const columns = opened.columns.map((c) => known.get(c.name) ?? { name: c.name });
1029
+ for (let first = true, done = false; !done; first = false) {
1030
+ const batch = await lane.send({ type: 'next', cursor, count: EXPORT_BATCH }, { timeoutMs });
490
1031
  done = batch.done;
491
- if (batch.rows.length || first)
492
- yield { columns, rows: batch.rows };
1032
+ if (batch.rows.length || first) {
1033
+ const waiting = setTimeout(stall, this.#exportIdleMs);
1034
+ waiting.unref();
1035
+ try {
1036
+ yield { columns, rows: batch.rows };
1037
+ }
1038
+ finally {
1039
+ clearTimeout(waiting);
1040
+ }
1041
+ if (stalled)
1042
+ throw stalledExport(this.#exportIdleMs);
1043
+ }
493
1044
  }
494
1045
  }
495
1046
  finally {
496
- if (!done)
497
- await this.#send({ type: 'close', cursor }).catch(() => { });
1047
+ // The worker goes, and with it the cursor and its hold on the file, read to the end or not.
1048
+ await lane.close();
498
1049
  }
499
1050
  }
500
1051
  async close() {
501
- const worker = this.#worker;
502
- this.#worker = null;
503
- await this.#queue;
504
- await worker?.terminate();
1052
+ // Someone's statement still running is stopped, not waited for, and those behind it don't
1053
+ // start: none has an end it must reach. A write stopped part-way is undone before the file
1054
+ // is let go of, as at a time limit.
1055
+ this.#closed = true;
1056
+ const writing = this.#writing > 0;
1057
+ this.#own.stop();
1058
+ if (writing) {
1059
+ await this.#own.gone();
1060
+ await this.#lane.send({ type: 'recover' }, { timeoutMs: 30_000 }).catch(() => { });
1061
+ }
1062
+ await this.#lane.close();
1063
+ await this.#own.close();
1064
+ }
1065
+ }
1066
+ /** A statement that left a transaction open on its handle: BEGIN or SAVEPOINT, run alone. */
1067
+ class LeftOpen extends Error {
1068
+ }
1069
+ /** An update's check found its cells changed, or its row gone (`current` undefined). */
1070
+ class Changed extends Error {
1071
+ index;
1072
+ current;
1073
+ constructor(index, current) {
1074
+ super('A cell was changed meanwhile.');
1075
+ this.index = index;
1076
+ this.current = current;
505
1077
  }
506
1078
  }
507
1079
  /** The worker's errors as the API's. */
508
1080
  function fromWorker(error) {
1081
+ if (error.leftOpen)
1082
+ return new LeftOpen(error.message);
1083
+ if (error.changed)
1084
+ return new Changed(error.changed.index, error.changed.current ?? undefined);
509
1085
  if (error.conflict)
510
1086
  return new DbAdminError(`Nothing was saved: ${error.message}.\n${error.conflict}`, 409, 'conflict');
511
1087
  if (error.oneStatement)