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