@mistriwork/engine 1.0.0-rc.10 → 1.0.0-rc.11

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 (73) hide show
  1. package/dist/adapters/adapter.d.ts +33 -0
  2. package/dist/adapters/postgres.d.ts +21 -16
  3. package/dist/adapters/postgres.js +174 -223
  4. package/dist/adapters/postgresCatalog.d.ts +12 -1
  5. package/dist/adapters/postgresCatalog.js +57 -23
  6. package/dist/adapters/postgresCatalogDigest.js +40 -34
  7. package/dist/adapters/postgresCatalogRows.d.ts +2 -0
  8. package/dist/adapters/postgresWriteAhead.d.ts +47 -0
  9. package/dist/adapters/postgresWriteAhead.js +209 -0
  10. package/dist/adapters/scoped/keyRows.js +9 -3
  11. package/dist/adapters/scoped/keyTypes.d.ts +34 -0
  12. package/dist/adapters/scoped/keyTypes.js +66 -0
  13. package/dist/adapters/scoped/postgresScopeCatalog.d.ts +18 -0
  14. package/dist/adapters/scoped/postgresScopeCatalog.js +353 -13
  15. package/dist/adapters/scoped/postgresTriggers.d.ts +137 -0
  16. package/dist/adapters/scoped/postgresTriggers.js +1545 -0
  17. package/dist/adapters/scoped/scopeTriggers.d.ts +122 -0
  18. package/dist/adapters/scoped/scopeTriggers.js +131 -0
  19. package/dist/adapters/scoped/scopedReads.d.ts +3 -1
  20. package/dist/adapters/scoped/scopedReads.js +23 -5
  21. package/dist/adapters/scoped/scopedTransaction.d.ts +76 -6
  22. package/dist/adapters/scoped/scopedTransaction.js +278 -34
  23. package/dist/adapters/scoped/sqliteScopeCatalog.d.ts +17 -1
  24. package/dist/adapters/scoped/sqliteScopeCatalog.js +197 -18
  25. package/dist/adapters/scoped/sqliteTriggerSession.d.ts +64 -0
  26. package/dist/adapters/scoped/sqliteTriggerSession.js +245 -0
  27. package/dist/adapters/scoped/sqliteTriggers.d.ts +20 -0
  28. package/dist/adapters/scoped/sqliteTriggers.js +822 -0
  29. package/dist/adapters/scoped/storedText.d.ts +45 -0
  30. package/dist/adapters/scoped/storedText.js +61 -0
  31. package/dist/adapters/scoped/triggerEffects.d.ts +98 -0
  32. package/dist/adapters/scoped/triggerEffects.js +189 -0
  33. package/dist/adapters/scoped/triggerProof.d.ts +124 -0
  34. package/dist/adapters/scoped/triggerProof.js +366 -0
  35. package/dist/adapters/snapshotRead.d.ts +8 -0
  36. package/dist/adapters/snapshotRead.js +37 -0
  37. package/dist/adapters/sqlite.d.ts +13 -2
  38. package/dist/adapters/sqlite.js +139 -16
  39. package/dist/adapters/sqliteDecimals.d.ts +2 -2
  40. package/dist/adapters/sqliteDecimals.js +2 -8
  41. package/dist/adapters/storeHost.d.ts +4 -1
  42. package/dist/adapters/writeCapture.d.ts +7 -0
  43. package/dist/server/cli/args.d.ts +6 -0
  44. package/dist/server/cli/args.js +6 -0
  45. package/dist/server/columnGrants.d.ts +3 -0
  46. package/dist/server/columnGrants.js +12 -1
  47. package/dist/server/config/profile.d.ts +123 -0
  48. package/dist/server/config/profile.js +236 -0
  49. package/dist/server/connections.d.ts +5 -0
  50. package/dist/server/connections.js +11 -1
  51. package/dist/server/hiddenColumns.js +6 -0
  52. package/dist/server/http/refusalReport.js +16 -4
  53. package/dist/server/migrate/cli.d.ts +50 -3
  54. package/dist/server/migrate/cli.js +199 -14
  55. package/dist/server/migrate/runner.js +5 -1
  56. package/dist/server/shapeonly.js +5 -0
  57. package/dist/shared/aggregate.d.ts +49 -0
  58. package/dist/shared/aggregate.js +107 -0
  59. package/dist/shared/breakdown.js +17 -4
  60. package/dist/shared/decimals.d.ts +37 -0
  61. package/dist/shared/decimals.js +148 -0
  62. package/dist/shared/displayDefaults.js +15 -1
  63. package/dist/shared/filter.d.ts +22 -1
  64. package/dist/shared/filter.js +36 -9
  65. package/dist/shared/money.d.ts +9 -0
  66. package/dist/shared/money.js +17 -0
  67. package/dist/shared/pageModel.d.ts +1 -1
  68. package/dist/shared/refusal.d.ts +16 -0
  69. package/dist/shared/refusal.js +40 -0
  70. package/dist/shared/schema.d.ts +6 -0
  71. package/dist/shared/scopeCatalog.js +4 -0
  72. package/dist/shared/servedApp.d.ts +7 -2
  73. package/package.json +5 -1
@@ -0,0 +1,822 @@
1
+ /**
2
+ * A SQLite trigger read from its `CREATE TRIGGER` text in `sqlite_schema`:
3
+ * the writes that fire it, whether it is validation-only, and what it does
4
+ * where it does more (scopeTriggers.ts).
5
+ *
6
+ * SQLite keeps no parsed form of a trigger, only the statement as written, so
7
+ * this reads that statement — and reads only a narrow grammar. A header it
8
+ * cannot follow is taken to fire on every write; a body it cannot follow is
9
+ * not validation-only and has no effects anyone can accept. Validation-only
10
+ * means every statement of the body is
11
+ *
12
+ * SELECT <expressions> [WHERE <expression>];
13
+ *
14
+ * with no FROM, and every expression (the trigger's WHEN too) is built from
15
+ * NEW.<column>, OLD.<column>, literals, the operators, CASE, CAST, BETWEEN,
16
+ * IN (a parenthesized list), LIKE and GLOB, a short list of SQLite's own pure
17
+ * functions (no app-defined function is ever registered on the writer), and
18
+ * `RAISE(ABORT, '<literal>')`. Not RAISE(ROLLBACK): it would end the
19
+ * scoped transaction from inside it, and what the handler wrote next would
20
+ * commit on its own. Not RAISE(FAIL): it keeps what the statement already
21
+ * changed, past the checks a refused write never reaches. Not RAISE(IGNORE):
22
+ * it skips the write silently. No subquery, no other table, no parameter.
23
+ *
24
+ * The tokens are SQLite's to the byte, because a word read differently is a
25
+ * name read differently: `NEW.note IN TRUE` reads a table (or view) named
26
+ * "true", since after IN a bare word is a table to SQLite, so IN takes only a
27
+ * parenthesized list here. Whitespace is exactly SQLite's six characters, not
28
+ * JavaScript's `\s`: U+00A0 is an identifier character to SQLite, so
29
+ * `IN<U+00A0>` names a table called U+00A0. And a body holding any character
30
+ * past ASCII outside a string literal is not proven at all.
31
+ *
32
+ * The keyed-effect grammar (docs/trigger-effects.md) adds, each the whole
33
+ * statement or one term of a SELECT's expression:
34
+ *
35
+ * UPDATE <table> SET <column> = <expression>, … WHERE <key> = NEW.<column> [AND …];
36
+ * INSERT INTO <table> (<column>, …) VALUES (<expression>, …);
37
+ * DELETE FROM <table> WHERE <key> = OLD.<column> [AND …];
38
+ * (SELECT <column> FROM <table> WHERE <key> = NEW.<column> [AND …])
39
+ *
40
+ * A SET's expressions may name the target row's own columns; an INSERT gives
41
+ * one row; no OR clause, upsert, RETURNING, FROM or subquery inside a write.
42
+ * The table is never qualified: SQLite refuses `main.` inside a trigger's
43
+ * writes, and a TEMP table of the same name would shadow it. Whether `<key>`
44
+ * covers a key of the table is the catalog's to judge (triggerEffects.ts).
45
+ */
46
+ import { createHash } from 'node:crypto';
47
+ import { PLAIN, plainDefinition, } from './scopeTriggers.js';
48
+ const EVERY = ['insert', 'update', 'delete'];
49
+ /** SQLite's own functions that read only their arguments and change nothing. */
50
+ const PURE = new Set([
51
+ 'ABS',
52
+ 'COALESCE',
53
+ 'IFNULL',
54
+ 'IIF',
55
+ 'NULLIF',
56
+ 'LENGTH',
57
+ 'LOWER',
58
+ 'UPPER',
59
+ 'TRIM',
60
+ 'LTRIM',
61
+ 'RTRIM',
62
+ 'SUBSTR',
63
+ 'SUBSTRING',
64
+ 'INSTR',
65
+ 'REPLACE',
66
+ 'TYPEOF',
67
+ 'ROUND',
68
+ 'SIGN',
69
+ 'MIN',
70
+ 'MAX',
71
+ 'DATE',
72
+ 'TIME',
73
+ 'DATETIME',
74
+ 'JULIANDAY',
75
+ 'UNIXEPOCH',
76
+ 'STRFTIME',
77
+ ]);
78
+ const COLLATIONS = new Set(['BINARY', 'NOCASE', 'RTRIM']);
79
+ const OPERATORS = new Set(['||', '*', '/', '%', '+', '-', '<<', '>>', '&', '|', '<', '<=', '>', '>=', '=', '==', '!=', '<>', '~']);
80
+ /** Keywords an expression may hold; the rest of the vocabulary is handled where it appears. */
81
+ const EXPRESSION_WORDS = new Set([
82
+ 'NULL',
83
+ 'TRUE',
84
+ 'FALSE',
85
+ 'CURRENT_DATE',
86
+ 'CURRENT_TIME',
87
+ 'CURRENT_TIMESTAMP',
88
+ 'AND',
89
+ 'OR',
90
+ 'NOT',
91
+ 'IS',
92
+ 'IN',
93
+ 'LIKE',
94
+ 'GLOB',
95
+ 'ESCAPE',
96
+ 'BETWEEN',
97
+ 'ISNULL',
98
+ 'NOTNULL',
99
+ 'WHEN',
100
+ 'THEN',
101
+ 'ELSE',
102
+ ]);
103
+ const WRITES = new Set(['INSERT', 'UPDATE', 'DELETE', 'REPLACE', 'UPSERT']);
104
+ class Unreadable extends Error {
105
+ }
106
+ const fail = () => {
107
+ throw new Unreadable();
108
+ };
109
+ const identifierStart = (char) => /[A-Za-z_]/.test(char) || char.charCodeAt(0) >= 0x80;
110
+ const identifierPart = (char) => /[A-Za-z0-9_$]/.test(char) || char.charCodeAt(0) >= 0x80;
111
+ /* SQLite's whitespace (sqlite3Isspace): tab, newline, vertical tab, form feed, carriage return and space. Nothing else
112
+ — every byte from 0x80 up is an identifier character to its tokenizer. */
113
+ const whitespace = (char) => char === ' ' || (char >= '\t' && char <= '\r');
114
+ /** A name past ASCII: SQLite's reading of it is not one this proof repeats, so a body holding one is not proven. */
115
+ const wide = (text) => /[\u0080-\u{10FFFF}]/u.test(text);
116
+ /** SQLite's tokens, as its tokenizer reads them; anything it would read otherwise (a parameter, a stray byte) refuses. */
117
+ function tokenize(sql) {
118
+ const tokens = [];
119
+ let i = 0;
120
+ const quoted = (close, doubled) => {
121
+ let text = '';
122
+ i += 1;
123
+ for (;;) {
124
+ if (i >= sql.length)
125
+ return fail();
126
+ const char = sql[i];
127
+ if (char === close) {
128
+ if (doubled && sql[i + 1] === close) {
129
+ text += close;
130
+ i += 2;
131
+ continue;
132
+ }
133
+ i += 1;
134
+ return text;
135
+ }
136
+ text += char;
137
+ i += 1;
138
+ }
139
+ };
140
+ while (i < sql.length) {
141
+ const char = sql[i];
142
+ if (whitespace(char)) {
143
+ i += 1;
144
+ }
145
+ else if (sql.startsWith('--', i)) {
146
+ const end = sql.indexOf('\n', i);
147
+ i = end === -1 ? sql.length : end + 1;
148
+ }
149
+ else if (sql.startsWith('/*', i)) {
150
+ const end = sql.indexOf('*/', i + 2);
151
+ // SQLite ends an unterminated comment at the end of input; a trigger's text never has one, so it refuses.
152
+ if (end === -1)
153
+ return fail();
154
+ i = end + 2;
155
+ }
156
+ else if (char === "'") {
157
+ tokens.push({ kind: 'string', text: quoted("'", true) });
158
+ }
159
+ else if ((char === 'x' || char === 'X') && sql[i + 1] === "'") {
160
+ i += 1;
161
+ tokens.push({ kind: 'literal', text: `X'${quoted("'", false)}'` });
162
+ }
163
+ else if (char === '"') {
164
+ tokens.push({ kind: 'id', text: quoted('"', true) });
165
+ }
166
+ else if (char === '`') {
167
+ tokens.push({ kind: 'id', text: quoted('`', true) });
168
+ }
169
+ else if (char === '[') {
170
+ tokens.push({ kind: 'id', text: quoted(']', false) });
171
+ }
172
+ else if (/[0-9]/.test(char) || (char === '.' && /[0-9]/.test(sql[i + 1] ?? ''))) {
173
+ const match = /^(?:0[xX][0-9A-Fa-f_]+|(?:[0-9][0-9_]*(?:\.[0-9_]*)?|\.[0-9][0-9_]*)(?:[eE][+-]?[0-9_]+)?)/.exec(sql.slice(i));
174
+ if (!match)
175
+ return fail();
176
+ i += match[0].length;
177
+ // `12abc` is one bad token to SQLite, not a number beside a word.
178
+ if (i < sql.length && identifierPart(sql[i]))
179
+ return fail();
180
+ tokens.push({ kind: 'literal', text: match[0] });
181
+ }
182
+ else if (identifierStart(char)) {
183
+ let end = i + 1;
184
+ while (end < sql.length && identifierPart(sql[end]))
185
+ end += 1;
186
+ const text = sql.slice(i, end);
187
+ tokens.push({ kind: 'word', text, upper: text.toUpperCase() });
188
+ i = end;
189
+ }
190
+ else {
191
+ const op = ['->>', '||', '<=', '>=', '==', '!=', '<>', '<<', '>>', '->'].find((candidate) => sql.startsWith(candidate, i)) ?? char;
192
+ if (!'()[],;.+-*/%<>=&|~'.includes(op[0]))
193
+ return fail();
194
+ tokens.push({ kind: 'op', text: op });
195
+ i += op.length;
196
+ }
197
+ }
198
+ return tokens;
199
+ }
200
+ class Cursor {
201
+ tokens;
202
+ at = 0;
203
+ constructor(tokens) {
204
+ this.tokens = tokens;
205
+ }
206
+ peek(offset = 0) {
207
+ return this.tokens[this.at + offset];
208
+ }
209
+ word(offset = 0) {
210
+ const token = this.peek(offset);
211
+ return token?.kind === 'word' ? token.upper : undefined;
212
+ }
213
+ op(offset = 0) {
214
+ const token = this.peek(offset);
215
+ return token?.kind === 'op' ? token.text : undefined;
216
+ }
217
+ take() {
218
+ return this.tokens[this.at++] ?? fail();
219
+ }
220
+ expectWord(word) {
221
+ if (this.word() !== word)
222
+ fail();
223
+ this.at += 1;
224
+ }
225
+ expectOp(op) {
226
+ if (this.op() !== op)
227
+ fail();
228
+ this.at += 1;
229
+ }
230
+ /** A name: a bare word or a quoted identifier. */
231
+ name() {
232
+ const token = this.take();
233
+ if (token.kind === 'word' || token.kind === 'id')
234
+ return token.text;
235
+ return fail();
236
+ }
237
+ /** `name` or `schema.name`. */
238
+ qualified() {
239
+ const first = this.name();
240
+ if (this.op() !== '.')
241
+ return first;
242
+ this.at += 1;
243
+ return this.name();
244
+ }
245
+ }
246
+ /** Words that are SQL's own, never a column of the row a write's expression names bare. */
247
+ const NOT_COLUMNS = new Set([
248
+ 'SELECT',
249
+ 'FROM',
250
+ 'EXISTS',
251
+ 'JOIN',
252
+ 'WITH',
253
+ ...WRITES,
254
+ 'WHERE',
255
+ 'SET',
256
+ 'VALUES',
257
+ 'INTO',
258
+ 'ORDER',
259
+ 'GROUP',
260
+ 'HAVING',
261
+ 'LIMIT',
262
+ 'UNION',
263
+ 'DEFAULT',
264
+ 'ON',
265
+ 'USING',
266
+ 'OVER',
267
+ 'FILTER',
268
+ 'RETURNING',
269
+ 'NEW',
270
+ 'OLD',
271
+ 'RAISE',
272
+ 'CASE',
273
+ 'END',
274
+ 'CAST',
275
+ 'AS',
276
+ 'COLLATE',
277
+ 'DISTINCT',
278
+ ]);
279
+ /**
280
+ * One expression of the grammar, from the cursor to the first token `stop`
281
+ * accepts outside every parenthesis and CASE. Throws where the expression
282
+ * leaves the grammar.
283
+ */
284
+ function expression(cursor, stop, options = {}) {
285
+ // What each open parenthesis is: a CAST's, which may hold `AS <type>`, or any other.
286
+ const parens = [];
287
+ let cases = 0;
288
+ let sawWhere = false;
289
+ let any = false;
290
+ for (;;) {
291
+ if (cursor.peek() === undefined)
292
+ fail();
293
+ if (!parens.length && !cases && any && stop(cursor))
294
+ return;
295
+ any = true;
296
+ const token = cursor.take();
297
+ if (token.kind === 'string' || token.kind === 'literal')
298
+ continue;
299
+ if (token.kind === 'id')
300
+ fail();
301
+ if (token.kind === 'op') {
302
+ if (token.text === '(') {
303
+ // A keyed read: one column of one row another table holds, found by NEW's or OLD's columns.
304
+ if (options.effects && cursor.word() === 'SELECT')
305
+ options.effects.push(keyedRead(cursor));
306
+ else
307
+ parens.push('plain');
308
+ }
309
+ else if (token.text === ')') {
310
+ if (!parens.pop())
311
+ fail();
312
+ }
313
+ else if (token.text === ',')
314
+ continue;
315
+ else if (!OPERATORS.has(token.text))
316
+ fail();
317
+ continue;
318
+ }
319
+ // A quoted name here is a column of no row, or a string SQLite falls back to: not proven.
320
+ const word = token.kind === 'word' ? token.upper : fail();
321
+ if (word === 'NEW' || word === 'OLD') {
322
+ cursor.expectOp('.');
323
+ cursor.name();
324
+ }
325
+ else if (word === 'IN') {
326
+ // After IN a bare word is a table to SQLite (`NEW.note IN TRUE` reads one named "true"): only a list is proven.
327
+ if (cursor.op() !== '(')
328
+ fail();
329
+ }
330
+ else if (word === 'CASE') {
331
+ cases += 1;
332
+ }
333
+ else if (word === 'END') {
334
+ if (!cases)
335
+ fail();
336
+ cases -= 1;
337
+ }
338
+ else if (word === 'DISTINCT') {
339
+ // Only `IS [NOT] DISTINCT FROM`.
340
+ const before = cursor.tokens[cursor.at - 2];
341
+ const twoBefore = cursor.tokens[cursor.at - 3];
342
+ const isBefore = (before?.kind === 'word' && before.upper === 'IS') ||
343
+ (before?.kind === 'word' && before.upper === 'NOT' && twoBefore?.kind === 'word' && twoBefore.upper === 'IS');
344
+ if (!isBefore)
345
+ fail();
346
+ cursor.expectWord('FROM');
347
+ }
348
+ else if (word === 'CAST') {
349
+ cursor.expectOp('(');
350
+ parens.push('cast');
351
+ }
352
+ else if (word === 'AS') {
353
+ if (parens.at(-1) !== 'cast')
354
+ fail();
355
+ // A type name: words, and at most one `(n)` or `(n, m)`.
356
+ if (cursor.peek()?.kind !== 'word')
357
+ fail();
358
+ while (cursor.peek()?.kind === 'word')
359
+ cursor.at += 1;
360
+ if (cursor.op() === '(') {
361
+ cursor.at += 1;
362
+ if (cursor.op() === '+' || cursor.op() === '-')
363
+ cursor.at += 1;
364
+ if (cursor.take().kind !== 'literal')
365
+ fail();
366
+ if (cursor.op() === ',') {
367
+ cursor.at += 1;
368
+ if (cursor.op() === '+' || cursor.op() === '-')
369
+ cursor.at += 1;
370
+ if (cursor.take().kind !== 'literal')
371
+ fail();
372
+ }
373
+ cursor.expectOp(')');
374
+ }
375
+ if (cursor.op() !== ')')
376
+ fail();
377
+ }
378
+ else if (word === 'COLLATE') {
379
+ if (!COLLATIONS.has(cursor.name().toUpperCase()))
380
+ fail();
381
+ }
382
+ else if (word === 'RAISE') {
383
+ // Only RAISE(ABORT, '<literal>'): see the module comment for the other three.
384
+ cursor.expectOp('(');
385
+ cursor.expectWord('ABORT');
386
+ cursor.expectOp(',');
387
+ if (cursor.take().kind !== 'string')
388
+ fail();
389
+ cursor.expectOp(')');
390
+ }
391
+ else if (EXPRESSION_WORDS.has(word)) {
392
+ continue;
393
+ }
394
+ else if (word === 'WHERE' && options.where && !parens.length && !cases && !sawWhere) {
395
+ sawWhere = true;
396
+ }
397
+ else if (cursor.op() === '(' && PURE.has(word)) {
398
+ cursor.at += 1;
399
+ parens.push('plain');
400
+ }
401
+ else if (options.own && !NOT_COLUMNS.has(word) && cursor.op() !== '(' && cursor.op() !== '.' && cursor.peek()?.kind !== 'id') {
402
+ // The written row's own column, bare: `posted_minor + NEW.amount`. Which columns the table has is the catalog's.
403
+ options.own.add(token.text);
404
+ }
405
+ else {
406
+ fail();
407
+ }
408
+ }
409
+ }
410
+ /** Words a body may put before a parenthesis that are not a call of a function. */
411
+ const SYNTAX = new Set([
412
+ ...EXPRESSION_WORDS,
413
+ 'SELECT',
414
+ 'WHERE',
415
+ 'CASE',
416
+ 'END',
417
+ 'CAST',
418
+ 'RAISE',
419
+ 'EXISTS',
420
+ 'DISTINCT',
421
+ 'ALL',
422
+ 'AS',
423
+ 'VALUES',
424
+ 'SET',
425
+ ]);
426
+ /** `<column> = NEW.<column>` (or the other way round, or `==`), joined by AND: the row a keyed effect reaches. */
427
+ function keyEqualities(cursor, table, end) {
428
+ const key = {};
429
+ const side = () => {
430
+ const word = cursor.word();
431
+ if (word === 'NEW' || word === 'OLD') {
432
+ cursor.at += 1;
433
+ cursor.expectOp('.');
434
+ return { row: word === 'NEW' ? 'new' : 'old', column: cursor.name() };
435
+ }
436
+ const first = cursor.name();
437
+ if (cursor.op() !== '.')
438
+ return first;
439
+ // `account.id`: the target itself, never another table.
440
+ if (first.toLowerCase() !== table.toLowerCase())
441
+ fail();
442
+ cursor.at += 1;
443
+ return cursor.name();
444
+ };
445
+ for (;;) {
446
+ const left = side();
447
+ if (cursor.op() !== '=' && cursor.op() !== '==')
448
+ fail();
449
+ cursor.at += 1;
450
+ const right = side();
451
+ const column = typeof left === 'string' ? left : typeof right === 'string' ? right : fail();
452
+ const ref = typeof left === 'string' ? right : left;
453
+ if (typeof ref === 'string' || Object.keys(key).some((known) => known.toLowerCase() === column.toLowerCase()))
454
+ fail();
455
+ key[column] = ref;
456
+ if (end(cursor))
457
+ return key;
458
+ cursor.expectWord('AND');
459
+ }
460
+ }
461
+ /** A table a keyed effect names: bare, since a qualified one inside a trigger is SQLite's error or TEMP's shadow. */
462
+ function effectTable(cursor) {
463
+ const table = cursor.name();
464
+ if (cursor.op() === '.')
465
+ fail();
466
+ return table;
467
+ }
468
+ /** `SELECT <column> FROM <table> WHERE <key> = NEW.<column> …)`, its opening parenthesis already taken. */
469
+ function keyedRead(cursor) {
470
+ cursor.expectWord('SELECT');
471
+ const column = cursor.name();
472
+ let qualifier;
473
+ let read = column;
474
+ if (cursor.op() === '.') {
475
+ cursor.at += 1;
476
+ qualifier = column;
477
+ read = cursor.name();
478
+ }
479
+ cursor.expectWord('FROM');
480
+ const table = effectTable(cursor);
481
+ if (qualifier !== undefined && qualifier.toLowerCase() !== table.toLowerCase())
482
+ fail();
483
+ cursor.expectWord('WHERE');
484
+ const key = keyEqualities(cursor, table, (at) => at.op() === ')');
485
+ cursor.expectOp(')');
486
+ return { kind: 'read', table, key, values: { [read]: { literal: null } } };
487
+ }
488
+ /** What an expression's tokens are known to be before the trigger runs: a column of NEW or OLD, a literal, or neither. */
489
+ function term(tokens) {
490
+ const [first, second, third] = tokens;
491
+ if (tokens.length === 3 && first.kind === 'word' && (first.upper === 'NEW' || first.upper === 'OLD') && second.kind === 'op')
492
+ return { row: first.upper === 'NEW' ? 'new' : 'old', column: third.text };
493
+ if (tokens.length === 1 && first.kind === 'string')
494
+ return { literal: first.text };
495
+ if (tokens.length === 1 && first.kind === 'word' && first.upper === 'NULL')
496
+ return { literal: null };
497
+ if (tokens.length === 1 && first.kind === 'literal' && /^[0-9]+$/.test(first.text) && Number.isSafeInteger(Number(first.text)))
498
+ return { literal: Number(first.text) };
499
+ return { expression: true };
500
+ }
501
+ /** `UPDATE <table> SET <column> = <expression>, … WHERE <key>;`, from UPDATE. */
502
+ function keyedUpdate(cursor) {
503
+ cursor.expectWord('UPDATE');
504
+ const table = effectTable(cursor);
505
+ cursor.expectWord('SET');
506
+ const values = {};
507
+ const own = new Set();
508
+ for (;;) {
509
+ const column = cursor.name();
510
+ if (Object.keys(values).some((set) => set.toLowerCase() === column.toLowerCase()))
511
+ fail();
512
+ cursor.expectOp('=');
513
+ const start = cursor.at;
514
+ expression(cursor, (at) => at.op() === ',' || at.word() === 'WHERE', { own });
515
+ values[column] = term(cursor.tokens.slice(start, cursor.at));
516
+ if (cursor.op() !== ',')
517
+ break;
518
+ cursor.at += 1;
519
+ }
520
+ cursor.expectWord('WHERE');
521
+ const key = keyEqualities(cursor, table, (at) => at.op() === ';');
522
+ // The bare columns it reads are the target row's own, which the proof finds in scope before the write.
523
+ return { kind: 'update', table, key, values };
524
+ }
525
+ /** `INSERT INTO <table> (<column>, …) VALUES (<expression>, …);`, from INSERT. */
526
+ function keyedInsert(cursor) {
527
+ cursor.expectWord('INSERT');
528
+ cursor.expectWord('INTO');
529
+ const table = effectTable(cursor);
530
+ cursor.expectOp('(');
531
+ const columns = [cursor.name()];
532
+ while (cursor.op() === ',') {
533
+ cursor.at += 1;
534
+ columns.push(cursor.name());
535
+ }
536
+ cursor.expectOp(')');
537
+ if (new Set(columns.map((column) => column.toLowerCase())).size !== columns.length)
538
+ fail();
539
+ cursor.expectWord('VALUES');
540
+ cursor.expectOp('(');
541
+ const values = {};
542
+ for (const [index, column] of columns.entries()) {
543
+ if (index)
544
+ cursor.expectOp(',');
545
+ const start = cursor.at;
546
+ expression(cursor, (at) => at.op() === ',' || at.op() === ')');
547
+ values[column] = term(cursor.tokens.slice(start, cursor.at));
548
+ }
549
+ cursor.expectOp(')');
550
+ // One row, and nothing after it: no second row, upsert or RETURNING.
551
+ if (cursor.op() !== ';')
552
+ fail();
553
+ return { kind: 'insert', table, values };
554
+ }
555
+ /** `DELETE FROM <table> WHERE <key>;`, from DELETE. */
556
+ function keyedDelete(cursor) {
557
+ cursor.expectWord('DELETE');
558
+ cursor.expectWord('FROM');
559
+ const table = effectTable(cursor);
560
+ cursor.expectWord('WHERE');
561
+ return { kind: 'delete', table, key: keyEqualities(cursor, table, (at) => at.op() === ';') };
562
+ }
563
+ /**
564
+ * Why a body that is not validation-only is not, from the tokens it holds outside its literals: said as exactly as
565
+ * they allow, since the owner reads it to know what to change. A subquery is not said to read a table it may not
566
+ * read, and a call of a function SQLite does not count as pure is named as one.
567
+ */
568
+ function why(tokens) {
569
+ const isOp = (token, text) => token?.kind === 'op' && token.text === text;
570
+ const isWord = (token, upper) => token?.kind === 'word' && token.upper === upper;
571
+ // A column named after NEW or OLD is a column, whatever it is called (`NEW.select`).
572
+ const words = tokens.flatMap((token, index) => token.kind === 'word' && !isOp(tokens[index - 1], '.') ? [{ upper: token.upper, text: token.text, index }] : []);
573
+ const called = (word) => isOp(tokens[word.index + 1], '(');
574
+ // `replace(…)` is SQLite's string function, not REPLACE INTO.
575
+ if (words.some((word) => WRITES.has(word.upper) && !(PURE.has(word.upper) && called(word))))
576
+ return 'it writes rows';
577
+ // FROM, but not IS [NOT] DISTINCT FROM; after IN, a name rather than a list is a table SQLite reads.
578
+ const from = words.some((word) => word.upper === 'FROM' && !isWord(tokens[word.index - 1], 'DISTINCT'));
579
+ const inTable = words.some((word) => word.upper === 'IN' && !called(word));
580
+ if (from || inTable || words.some((word) => word.upper === 'JOIN' || word.upper === 'WITH'))
581
+ return 'it reads another table';
582
+ if (words.some((word) => word.upper === 'EXISTS' || (word.upper === 'SELECT' && isOp(tokens[word.index - 1], '('))))
583
+ return 'it has a subquery, which can read another table';
584
+ const unknown = words.find((word) => called(word) && !PURE.has(word.upper) && !SYNTAX.has(word.upper));
585
+ if (unknown)
586
+ return `it calls ${unknown.text}(), which is not one of SQLite's own pure functions`;
587
+ const literal = (word) => {
588
+ const [open, kind, comma, message, close] = tokens.slice(word.index + 1, word.index + 6);
589
+ return isOp(open, '(') && isWord(kind, 'ABORT') && isOp(comma, ',') && message?.kind === 'string' && isOp(close, ')');
590
+ };
591
+ if (words.some((word) => word.upper === 'RAISE' && !literal(word)))
592
+ return "its RAISE is not RAISE(ABORT, '…') with a literal message";
593
+ return 'it does more than check the row it fires on';
594
+ }
595
+ /** The definition as tokens, one space apart: comments, spacing and keyword case never move the digest. */
596
+ function digestOf(tokens) {
597
+ const normalized = tokens
598
+ .map((token) => token.kind === 'word'
599
+ ? token.upper
600
+ : token.kind === 'string'
601
+ ? `'${token.text.replace(/'/g, "''")}'`
602
+ : token.kind === 'id'
603
+ ? `"${token.text.replace(/"/g, '""')}"`
604
+ : token.text)
605
+ .join(' ');
606
+ return `sha256:${createHash('sha256').update(`sqlite\n${normalized}`).digest('hex')}`;
607
+ }
608
+ /**
609
+ * The trigger `name`, from its `CREATE TRIGGER` text. `generated` holds the
610
+ * table's generated columns, folded: an `UPDATE OF` naming one is taken to
611
+ * fire on every update, rather than trusting when the engine recomputes it.
612
+ */
613
+ export function readSqliteTrigger(name, sql, generated) {
614
+ const unknown = { name, events: EVERY, validates: false, why: 'its definition is not one mistri can read' };
615
+ if (typeof sql !== 'string')
616
+ return unknown;
617
+ let tokens;
618
+ try {
619
+ tokens = tokenize(sql);
620
+ }
621
+ catch {
622
+ return unknown;
623
+ }
624
+ const digest = digestOf(tokens);
625
+ const cursor = new Cursor(tokens);
626
+ let events;
627
+ let columns;
628
+ let bodyStart;
629
+ try {
630
+ cursor.expectWord('CREATE');
631
+ if (cursor.word() === 'TEMP' || cursor.word() === 'TEMPORARY')
632
+ cursor.at += 1;
633
+ cursor.expectWord('TRIGGER');
634
+ if (cursor.word() === 'IF') {
635
+ cursor.at += 1;
636
+ cursor.expectWord('NOT');
637
+ cursor.expectWord('EXISTS');
638
+ }
639
+ cursor.qualified();
640
+ if (cursor.word() === 'BEFORE' || cursor.word() === 'AFTER')
641
+ cursor.at += 1;
642
+ else if (cursor.word() === 'INSTEAD') {
643
+ cursor.at += 1;
644
+ cursor.expectWord('OF');
645
+ }
646
+ const event = cursor.word();
647
+ cursor.at += 1;
648
+ if (event === 'INSERT')
649
+ events = ['insert'];
650
+ else if (event === 'DELETE')
651
+ events = ['delete'];
652
+ else if (event === 'UPDATE') {
653
+ events = ['update'];
654
+ if (cursor.word() === 'OF') {
655
+ cursor.at += 1;
656
+ columns = [cursor.name()];
657
+ while (cursor.op() === ',') {
658
+ cursor.at += 1;
659
+ columns.push(cursor.name());
660
+ }
661
+ const fold = (column) => column.replace(/[A-Z]/g, (char) => char.toLowerCase());
662
+ if (columns.some((column) => generated.has(fold(column))))
663
+ columns = undefined;
664
+ }
665
+ }
666
+ else
667
+ return { ...unknown, digest };
668
+ cursor.expectWord('ON');
669
+ cursor.qualified();
670
+ bodyStart = cursor.at;
671
+ }
672
+ catch {
673
+ return { ...unknown, digest };
674
+ }
675
+ const fired = { name, events, ...(columns ? { columns } : {}), digest };
676
+ try {
677
+ if (tokens.slice(bodyStart).some((token) => (token.kind === 'word' || token.kind === 'id') && wide(token.text)))
678
+ fail();
679
+ if (cursor.word() === 'FOR') {
680
+ cursor.at += 1;
681
+ cursor.expectWord('EACH');
682
+ cursor.expectWord('ROW');
683
+ }
684
+ if (cursor.word() === 'WHEN') {
685
+ cursor.at += 1;
686
+ expression(cursor, (at) => at.word() === 'BEGIN');
687
+ }
688
+ cursor.expectWord('BEGIN');
689
+ const effects = [];
690
+ let statements = 0;
691
+ while (cursor.word() !== 'END') {
692
+ const word = cursor.word();
693
+ if (word === 'SELECT') {
694
+ cursor.at += 1;
695
+ if (cursor.word() === 'DISTINCT' || cursor.word() === 'ALL')
696
+ cursor.at += 1;
697
+ expression(cursor, (at) => at.op() === ';', { where: true, effects });
698
+ }
699
+ else if (word === 'UPDATE')
700
+ effects.push(keyedUpdate(cursor));
701
+ else if (word === 'INSERT')
702
+ effects.push(keyedInsert(cursor));
703
+ else if (word === 'DELETE')
704
+ effects.push(keyedDelete(cursor));
705
+ else
706
+ fail();
707
+ cursor.expectOp(';');
708
+ statements += 1;
709
+ }
710
+ cursor.expectWord('END');
711
+ if (cursor.op() === ';')
712
+ cursor.at += 1;
713
+ if (cursor.peek() !== undefined || !statements)
714
+ fail();
715
+ if (!effects.length)
716
+ return { ...fired, validates: true };
717
+ return {
718
+ ...fired,
719
+ validates: false,
720
+ why: why(tokens.slice(bodyStart)),
721
+ effects,
722
+ ...(plainDefinition(sql, tokens, 'sqlite') ? {} : { unaccepted: PLAIN }),
723
+ };
724
+ }
725
+ catch {
726
+ return { ...fired, validates: false, why: why(tokens.slice(bodyStart)) };
727
+ }
728
+ }
729
+ /** Words that open a table constraint, never a column definition (a column so named must be quoted). */
730
+ const TABLE_CONSTRAINTS = new Set(['CONSTRAINT', 'PRIMARY', 'UNIQUE', 'CHECK', 'FOREIGN']);
731
+ /**
732
+ * Each column's collation, by its name folded, as a table's `CREATE TABLE` text declares it: a `COLLATE` among the
733
+ * column's own constraints (outside any parenthesis), or BINARY. SQLite keeps no other record of it (no PRAGMA says
734
+ * a column's collation), and a trigger's `NEW.code = code` compares under the left column's. Undefined where the
735
+ * text is not one this reads; a column it cannot read is missing, and either way a key over it is refused.
736
+ */
737
+ export function sqliteColumnCollations(sql) {
738
+ try {
739
+ const tokens = tokenize(sql);
740
+ let at = tokens.findIndex((token) => token.kind === 'op' && token.text === '(');
741
+ if (at < 0 || tokens[0]?.kind !== 'word' || tokens[0].upper !== 'CREATE')
742
+ return undefined;
743
+ at += 1;
744
+ const items = [[]];
745
+ for (let depth = 0;; at += 1) {
746
+ const token = tokens[at] ?? fail();
747
+ if (token.kind === 'op' && token.text === '(')
748
+ depth += 1;
749
+ else if (token.kind === 'op' && token.text === ')') {
750
+ if (depth === 0)
751
+ break;
752
+ depth -= 1;
753
+ }
754
+ else if (depth === 0 && token.kind === 'op' && token.text === ',') {
755
+ items.push([]);
756
+ continue;
757
+ }
758
+ items.at(-1).push(token);
759
+ }
760
+ const collations = new Map();
761
+ for (const item of items) {
762
+ const [first] = item;
763
+ if (!first || (first.kind === 'word' && TABLE_CONSTRAINTS.has(first.upper)))
764
+ continue;
765
+ if (first.kind !== 'word' && first.kind !== 'id' && first.kind !== 'string')
766
+ return undefined;
767
+ const name = first.text.replace(/[A-Z]/g, (char) => char.toLowerCase());
768
+ const said = [];
769
+ for (let i = 1, depth = 0; i < item.length; i += 1) {
770
+ const token = item[i];
771
+ if (token.kind === 'op' && token.text === '(')
772
+ depth += 1;
773
+ else if (token.kind === 'op' && token.text === ')')
774
+ depth -= 1;
775
+ else if (depth === 0 && token.kind === 'word' && token.upper === 'COLLATE') {
776
+ const collation = item[i + 1];
777
+ if (!collation || (collation.kind !== 'word' && collation.kind !== 'id' && collation.kind !== 'string'))
778
+ return undefined;
779
+ said.push(collation.text.toUpperCase());
780
+ }
781
+ }
782
+ // Two COLLATE clauses on one column: which one SQLite keeps is not this reader's to guess.
783
+ if (collations.has(name) || said.length > 1)
784
+ collations.delete(name);
785
+ else
786
+ collations.set(name, said[0] ?? 'BINARY');
787
+ }
788
+ return collations;
789
+ }
790
+ catch {
791
+ return undefined;
792
+ }
793
+ }
794
+ /**
795
+ * The conflict clauses a table's `CREATE TABLE` text declares (`PRIMARY KEY ON CONFLICT REPLACE`, `NOT NULL ON
796
+ * CONFLICT IGNORE`), each as `ON CONFLICT <resolution>`, upper-cased, in order. SQLite keeps no other record of them.
797
+ * Undefined where the text is not one this reads.
798
+ */
799
+ export function sqliteConflictClauses(sql) {
800
+ try {
801
+ const tokens = tokenize(sql);
802
+ if (tokens[0]?.kind !== 'word' || tokens[0].upper !== 'CREATE')
803
+ return undefined;
804
+ const clauses = [];
805
+ for (const [at, token] of tokens.entries()) {
806
+ if (token.kind !== 'word' || token.upper !== 'CONFLICT')
807
+ continue;
808
+ const before = tokens[at - 1];
809
+ const resolution = tokens[at + 1];
810
+ // `conflict` as a column's or a constraint's name is a word too: only `ON CONFLICT <word>` is the clause.
811
+ if (before?.kind !== 'word' || before.upper !== 'ON')
812
+ continue;
813
+ if (resolution?.kind !== 'word')
814
+ return undefined;
815
+ clauses.push(`ON CONFLICT ${resolution.upper}`);
816
+ }
817
+ return clauses;
818
+ }
819
+ catch {
820
+ return undefined;
821
+ }
822
+ }