@yaks/fts 0.0.0-stage → 0.2.36

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.
package/ddl.ts ADDED
@@ -0,0 +1,960 @@
1
+ // Creating the indexes, and keeping them correct.
2
+ //
3
+ // One FTS5 index per indexed component, named `<comp>_fts`. Each is an
4
+ // external-content index (`content='<comp>'`): it stores the inverted index and
5
+ // nothing else, reading the text itself back out of the component's own table,
6
+ // so the prose is never stored twice. `content_rowid='entity'` makes the
7
+ // index's rowid the component's integer owner column — the entity's id in the
8
+ // `entity` table — so a match yields an id the rest of the query already uses,
9
+ // and no join is needed to get there.
10
+ //
11
+ // Three triggers keep each index current. External-content indexes impose one
12
+ // rule: a delete must be given exactly the values the matching insert was
13
+ // given, or the index keeps terms for text that is no longer there. So both
14
+ // sides read the column the same way — the stored text, or '' for a null — and
15
+ // an update is written as a delete followed by an insert.
16
+ //
17
+ // When a column does not hold its own text. @yaks/blob stores a body's SHA-256
18
+ // and keeps the prose in a separate table, so a trigger reading the column
19
+ // would index the hash and a search would only ever find the body by its title.
20
+ // A `text` expression in the store's @yaks/sql `Derived` describes how to
21
+ // resolve such a column, and it is applied on both sides:
22
+ //
23
+ // - the triggers insert the resolved text, so every write path indexes prose
24
+ // — the plugin's writes, a plain `insert into doc`, a restore;
25
+ // - the index's content source becomes a view that resolves the same way
26
+ // (`<comp>_text`), because FTS5 reads the content back for `snippet()` and
27
+ // for `rebuild`, and both would otherwise see the hash.
28
+ //
29
+ // Resolving inside a trigger is sound because a blob is immutable and
30
+ // content-addressed: the text a hash stands for is the same when the delete
31
+ // trigger reads it as when the insert trigger did, which is all the rule above
32
+ // requires. And a body written in the same transaction is already stored — the
33
+ // bytes are inserted before the row that references them.
34
+ //
35
+ // An index read on behalf of another component (`entry` found by
36
+ // `content.body`) covers only the entities carrying that component. Its view
37
+ // joins the two tables, and its triggers fire on both: a write to the text
38
+ // indexes it when the entity already is one, and the entity becoming one (or
39
+ // ceasing to be) indexes the text already there (or removes it). Whichever of
40
+ // the two rows a transaction writes second is the one that indexes, so an
41
+ // entity is indexed once however its bundle's components are ordered.
42
+ //
43
+ // `heal()` is the other half. An index that has drifted from its table (a
44
+ // trigger that did not run, a file restored around it) returns wrong results
45
+ // quietly, so it is checked and rebuilt rather than trusted.
46
+ //
47
+ // `adopt()` is for a database that already has search objects — created by an
48
+ // earlier version of this package, or by an application before it used one. It
49
+ // makes what is there match what `schema()` returns, keeping an index whose
50
+ // columns already match (its terms need no re-indexing) and re-creating one
51
+ // that does not, and it drops any other trigger that writes into one of these
52
+ // indexes: an external-content index has exactly three writers, and a fourth
53
+ // double-counts every row.
54
+
55
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
56
+ import {
57
+ columnsOf,
58
+ type Field,
59
+ type Index,
60
+ indexes,
61
+ piecesOf,
62
+ tableOf,
63
+ tailOf,
64
+ textName,
65
+ viewOf,
66
+ worded,
67
+ } from './fields.js'
68
+ import {
69
+ among,
70
+ and,
71
+ as,
72
+ catalogue,
73
+ col,
74
+ count,
75
+ type CreateTable,
76
+ type CreateTrigger,
77
+ type CreateView,
78
+ type CreateVirtual,
79
+ type Derived,
80
+ type Driver,
81
+ type Drop,
82
+ eq,
83
+ erect,
84
+ exists,
85
+ type Expr,
86
+ field,
87
+ fn,
88
+ ge,
89
+ gt,
90
+ type Insert,
91
+ join,
92
+ le,
93
+ lit,
94
+ lt,
95
+ not,
96
+ op,
97
+ or,
98
+ render,
99
+ select,
100
+ type Stmt,
101
+ sub,
102
+ table,
103
+ tableAsWritten,
104
+ val,
105
+ type Write,
106
+ } from '@yaks/sql'
107
+
108
+ // FTS views already name their inputs by stored column name.
109
+ let contentTable = (name: string, as?: string) => ({
110
+ t: 'table' as const,
111
+ name,
112
+ as,
113
+ physical: true,
114
+ })
115
+
116
+ // How one column of `comp` reads as text, given the expression for its stored
117
+ // value: through the registered `text` expression where there is one, else as
118
+ // stored, which is every ordinary column. A substring index reads it `cut`.
119
+ let reader =
120
+ (ix: Index, derived: Derived) => (prop: string, stored: Expr): Expr => {
121
+ let text = whole(ix, derived)(prop, stored)
122
+ return ix.trigram ? cut(text) : text
123
+ }
124
+
125
+ // How one column of `comp` reads as its whole text, uncut.
126
+ let whole =
127
+ (ix: Index, derived: Derived) => (prop: string, stored: Expr): Expr =>
128
+ derived[`${ix.comp}.${prop}`]?.text?.(stored) ?? stored
129
+
130
+ /** How much of a text a substring index holds: its first mebibyte. One row's
131
+ * trigrams are made inside the write that stores it, about 190 ms a MiB, and
132
+ * the box's transcripts hold texts of 33 MB. The 50 past it hold 278 MB of
133
+ * their 2.2 GB. */
134
+ export let CUT = 1 << 20
135
+
136
+ /** The trigram a substring index holds for a text longer than {@link CUT}:
137
+ * three private-use characters, which no needle holds (a `~=` needle is
138
+ * ASCII), so a test reads each such row whole, as well as the ones its
139
+ * needle's trigrams find, until the text's tail index holds every piece of
140
+ * the rest. */
141
+ export let PAST = '\u{F8FF}\u{F8FF}\u{F8FF}'
142
+
143
+ /** The trigram a tail index holds in a text's done row, once it holds every
144
+ * piece of the text. */
145
+ export let DONE = '\u{F8FE}\u{F8FE}\u{F8FE}'
146
+
147
+ /** The rows a tail index keeps for each text: an entity's are
148
+ * `entity * PIECES + i`, its `i`th piece, and its done row at 0. A SQLite
149
+ * text holds at most 10^9 bytes, 954 pieces of {@link CUT}. */
150
+ export let PIECES = 1 << 10
151
+
152
+ /** The longest run of a text one of its pieces is sure to hold whole: each
153
+ * starts SPAN - 1 characters before the one before it ends. A test asks for
154
+ * the trigrams of its needle's first SPAN characters (./compile.ts). */
155
+ export let SPAN = 1 << 10
156
+
157
+ // A text as a substring index holds it: its first CUT characters, then PAST
158
+ // when there were more.
159
+ let cut = (text: Expr): Expr =>
160
+ op(
161
+ '||',
162
+ fn('substr', text, lit(1), lit(CUT)),
163
+ fn('iif', gt(fn('length', text), lit(CUT)), lit(PAST), lit('')),
164
+ )
165
+
166
+ // Row `id` of a tail index, out of `text`: the done row's marker, or a piece,
167
+ // the CUT characters after the one before it, and the SPAN - 1 before them.
168
+ let piece = (id: Expr, text: Expr): Expr => {
169
+ let i = op('%', id, lit(PIECES))
170
+ let start = op('-', op('*', i, lit(CUT)), lit(SPAN - 2))
171
+ return fn(
172
+ 'iif',
173
+ eq(i, lit(0)),
174
+ lit(DONE),
175
+ fn('substr', text, start, lit(CUT + SPAN - 1)),
176
+ )
177
+ }
178
+
179
+ // The rows of a tail index or its piece table that are `entity`'s text's.
180
+ let pieceOf = (entity: Expr): Expr =>
181
+ and(
182
+ ge(col('id'), op('*', entity, lit(PIECES))),
183
+ lt(col('id'), op('*', op('+', entity, lit(1)), lit(PIECES))),
184
+ )
185
+
186
+ // A substring index's tail index: its piece table, the view reading each
187
+ // piece out of its text, the index, and the triggers that drop a text's
188
+ // pieces when it changes or goes. The first window of `pieces` raises the
189
+ // tail index, so a write of short text pays only for the head index.
190
+ let tail = (
191
+ ix: Index,
192
+ derived: Derived,
193
+ ): (CreateTable | CreateView | CreateVirtual | CreateTrigger)[] => {
194
+ let { comp, props } = ix, columns = columnsOf(ix)
195
+ let fts = tailOf(ix), list = piecesOf(ix)
196
+ let text = (p: string, row?: string, column = field(p)) =>
197
+ fn('coalesce', whole(ix, derived)(p, col(column, row)), lit(''))
198
+ let gone: Write[] = [
199
+ {
200
+ t: 'insert',
201
+ into: fts,
202
+ cols: [fts, 'rowid', ...columns],
203
+ q: select({
204
+ cols: [
205
+ lit('delete'),
206
+ col('id'),
207
+ ...props.map((p) => piece(col('id'), text(p, 'old'))),
208
+ ],
209
+ from: table(list),
210
+ where: pieceOf(col('entity', 'old')),
211
+ }),
212
+ },
213
+ { t: 'delete', from: list, where: pieceOf(col('entity', 'old')) },
214
+ ]
215
+ let trigger = (
216
+ event: 'update' | 'delete',
217
+ when?: Expr,
218
+ ): CreateTrigger => ({
219
+ t: 'create trigger',
220
+ name: `${fts}_${event}`,
221
+ ifNot: true,
222
+ timing: 'after',
223
+ event,
224
+ on: comp,
225
+ ...when && { when },
226
+ body: gone,
227
+ })
228
+ return [
229
+ {
230
+ t: 'create table',
231
+ name: list,
232
+ ifNot: true,
233
+ cols: [{ name: 'id', type: 'integer', pk: true }],
234
+ },
235
+ {
236
+ t: 'create view',
237
+ name: textName(fts),
238
+ ifNot: true,
239
+ q: select({
240
+ cols: [
241
+ as(col('id', 'p'), 'id'),
242
+ ...props.map((p, i) =>
243
+ as(piece(col('id', 'p'), text(p, 'c', columns[i])), columns[i])
244
+ ),
245
+ ],
246
+ from: table(list, 'p'),
247
+ joins: [join(
248
+ contentTable(comp, 'c'),
249
+ eq(col('entity', 'c'), op('/', col('id', 'p'), lit(PIECES))),
250
+ )],
251
+ }),
252
+ },
253
+ {
254
+ t: 'create virtual table',
255
+ name: fts,
256
+ ifNot: true,
257
+ using: 'fts5',
258
+ args: [
259
+ ...columns,
260
+ ['content', textName(fts)],
261
+ ['content_rowid', 'id'],
262
+ ...GRAMS,
263
+ ],
264
+ },
265
+ trigger(
266
+ 'update',
267
+ or(
268
+ ...props.map((p) =>
269
+ op('is not', col(field(p), 'old'), col(field(p), 'new'))
270
+ ),
271
+ ),
272
+ ),
273
+ trigger('delete'),
274
+ ]
275
+ }
276
+
277
+ // Empty a tail index: every text it held pieces of is owed again.
278
+ let forget = (db: Driver, ix: Index) => {
279
+ db.query(command(tailOf(ix), 'delete-all'))
280
+ db.query({ t: 'delete', from: piecesOf(ix) })
281
+ }
282
+
283
+ // Whether the file holds a table, view or index by this name.
284
+ let holds = (db: Driver, name: string): boolean =>
285
+ catalogue(db).some((o) => o.name == name)
286
+
287
+ /**
288
+ * Make the next piece of the first text a substring index holds only the
289
+ * first {@link CUT} of, and its done row with its last: one window of the
290
+ * work a long text's write leaves, about 190 ms for a piece. Run it in a
291
+ * unit of its own, as @yaks/sqlite's owed work does (`Chore`). False when
292
+ * no standing head index holds text that still owes pieces.
293
+ */
294
+ export let pieces = (
295
+ db: Driver,
296
+ fields: Field[],
297
+ derived: Derived = {},
298
+ ): boolean => {
299
+ for (let ix of standing(db, fields)) {
300
+ if (!ix.trigram || !holds(db, tableOf(ix))) continue
301
+ let head = tableOf(ix), fts = tailOf(ix), list = piecesOf(ix)
302
+ let raised = holds(db, fts)
303
+ let [owed] = db.query(select({
304
+ cols: [as(col('rowid'), 'entity')],
305
+ from: table(head),
306
+ where: and(
307
+ op('match', col(head), val(`"${PAST}"`)),
308
+ ...raised
309
+ ? [
310
+ not(exists(select({
311
+ cols: [lit(1)],
312
+ from: table(list),
313
+ where: eq(col('id'), op('*', col('rowid', head), lit(PIECES))),
314
+ }))),
315
+ ]
316
+ : [],
317
+ ),
318
+ order: [col('rowid')],
319
+ limit: lit(1),
320
+ }))
321
+ if (!owed) continue
322
+ let at = Number(owed.entity) * PIECES
323
+ let last = raised
324
+ ? db.query(select({
325
+ cols: [as(fn('max', col('id')), 'last')],
326
+ from: table(list),
327
+ where: pieceOf(val(Number(owed.entity))),
328
+ }))[0].last
329
+ : null
330
+ if (!raised) erect(db, tail(ix, derived))
331
+ let i = last == null ? 1 : Number(last) - at + 1
332
+ let [{ size }] = db.query(select({
333
+ cols: [as(
334
+ fn(
335
+ 'max',
336
+ ...ix.props.map((p) =>
337
+ fn('length', whole(ix, derived)(p, col(field(p))))
338
+ ),
339
+ ),
340
+ 'size',
341
+ )],
342
+ from: table(ix.comp),
343
+ where: eq(col('entity'), val(Number(owed.entity))),
344
+ }))
345
+ let ids = (i + 1) * CUT >= Number(size) ? [at + i, at] : [at + i]
346
+ db.query({
347
+ t: 'insert',
348
+ into: list,
349
+ cols: ['id'],
350
+ rows: ids.map((id) => [val(id)]),
351
+ })
352
+ db.query({
353
+ t: 'insert',
354
+ into: fts,
355
+ cols: ['rowid', ...columnsOf(ix)],
356
+ q: select({
357
+ cols: [col('id'), ...columnsOf(ix).map((p) => col(p))],
358
+ from: table(textName(fts)),
359
+ where: among(col('id'), ids.map((id) => val(id))),
360
+ }),
361
+ })
362
+ return true
363
+ }
364
+ return false
365
+ }
366
+
367
+ // An FTS5 command: a row written to the index's own hidden column.
368
+ let command = (fts: string, word: string, rank?: number): Insert => ({
369
+ t: 'insert',
370
+ into: fts,
371
+ cols: rank == null ? [fts] : [fts, 'rank'],
372
+ rows: [[lit(word), ...(rank == null ? [] : [lit(rank)])]],
373
+ })
374
+
375
+ // How a substring index tokenizes: every three characters, case folded, and
376
+ // only which rows hold each (`detail=none`), not where. A test then reads
377
+ // the rows holding all of a needle's trigrams (`grammed`). On the box's
378
+ // transcripts that keeps the index at half the size of the text it covers,
379
+ // where positions would make it 2.4 times the text.
380
+ let GRAMS: [string, string][] = [['tokenize', 'trigram'], ['detail', 'none']]
381
+
382
+ // The trigger names an index owns: three on its text's table, and two more on
383
+ // `on` for a scoped one.
384
+ let TRIGGERS = ['insert', 'delete', 'update']
385
+ let SCOPED = ['join', 'leave']
386
+ let owned = (ix: Index): string[] =>
387
+ [...TRIGGERS, ...ix.on ? SCOPED : []].map((s) => `${tableOf(ix)}_${s}`)
388
+
389
+ // What an index reads its content back through: the component table, or its
390
+ // text view where a column must be resolved, the text is read on behalf of
391
+ // another component, or a substring index holds it cut.
392
+ let sourceOf = (ix: Index, derived: Derived): string =>
393
+ ix.on || ix.trigram ||
394
+ ix.props.some((p) => derived[`${ix.comp}.${p}`]?.text)
395
+ ? viewOf(ix)
396
+ : ix.comp
397
+
398
+ // One index and the triggers keeping it, plus the view it reads its content
399
+ // back through when any of its columns has to be resolved or it is read on
400
+ // behalf of another component. An index being filled in windows (`Filler`)
401
+ // has triggers that keep only the rows its `cursor` has passed: a row ahead of
402
+ // it is read as it stands when its window comes, and deleting a row the index
403
+ // never held would corrupt it.
404
+ let index = (ix: Index, derived: Derived, cursor?: Expr): Stmt[] => {
405
+ let { comp, props, on } = ix, columns = columnsOf(ix)
406
+ let fts = tableOf(ix)
407
+ let read = reader(ix, derived)
408
+ // The values a trigger inserts: the column read as text, or '' for a null —
409
+ // the index never holds a null term, and the delete side must mirror the
410
+ // insert side exactly.
411
+ let side = (row: string, named = props.map(field)) =>
412
+ props.map((p, i) => fn('coalesce', read(p, col(named[i], row)), lit('')))
413
+ let add = (row: string): Insert => ({
414
+ t: 'insert',
415
+ into: fts,
416
+ cols: ['rowid', ...columns],
417
+ rows: [[col('entity', row), ...side(row)]],
418
+ })
419
+ let drop: Insert = {
420
+ t: 'insert',
421
+ into: fts,
422
+ cols: [fts, 'rowid', ...columns],
423
+ rows: [[lit('delete'), col('entity', 'old'), ...side('old')]],
424
+ }
425
+ // The text a scoped entity already holds, as it joins or leaves `on`.
426
+ let held = (row: 'new' | 'old', first: Expr[]): Insert => ({
427
+ t: 'insert',
428
+ into: fts,
429
+ cols: [...(row == 'old' ? [fts] : []), 'rowid', ...columns],
430
+ q: select({
431
+ cols: [...first, col('entity', row), ...side('c', columns)],
432
+ from: contentTable(comp, 'c'),
433
+ where: eq(col('entity', 'c'), col('entity', row)),
434
+ }),
435
+ })
436
+ // The text's own triggers, which for a scoped index fire only for an entity
437
+ // that already carries `on`.
438
+ let guard = (over: string, event: CreateTrigger['event']) => {
439
+ let row = event == 'delete' ? 'old' : 'new'
440
+ let scoped = on && over == comp
441
+ ? exists(select({
442
+ cols: [lit(1)],
443
+ from: table(on),
444
+ where: eq(col('entity', on), col('entity', row)),
445
+ }))
446
+ : undefined
447
+ let passed = cursor && le(col('entity', row), cursor)
448
+ let when = scoped && passed ? and(scoped, passed) : scoped ?? passed
449
+ return when ? { when } : {}
450
+ }
451
+ let trigger = (
452
+ what: string,
453
+ event: CreateTrigger['event'],
454
+ over: string,
455
+ body: Insert[],
456
+ ): CreateTrigger => ({
457
+ t: 'create trigger',
458
+ name: `${fts}_${what}`,
459
+ ifNot: true,
460
+ timing: 'after',
461
+ event,
462
+ on: over,
463
+ ...guard(over, event),
464
+ body,
465
+ })
466
+ // Where FTS5 reads a column back from: the component table itself, or the
467
+ // view that resolves it. `<name>_text` is this package's own name,
468
+ // deliberately not @yaks/sqlite's `doc_value` — that view is the read source
469
+ // for whole `doc` rows, and a narrower view taking its place under
470
+ // `if not exists` would hide the columns a query needs.
471
+ let content = sourceOf(ix, derived)
472
+ return [
473
+ ...(content == comp ? [] : [view(ix, derived)]),
474
+ {
475
+ t: 'create virtual table',
476
+ name: fts,
477
+ ifNot: true,
478
+ using: 'fts5',
479
+ args: [
480
+ ...columns,
481
+ ['content', content],
482
+ ['content_rowid', 'entity'],
483
+ ...ix.trigram ? GRAMS : [],
484
+ ],
485
+ },
486
+ trigger('insert', 'insert', comp, [add('new')]),
487
+ trigger('delete', 'delete', comp, [drop]),
488
+ trigger('update', 'update', comp, [drop, add('new')]),
489
+ // The entity becoming one of `on`, or ceasing to be one, with its text
490
+ // already written.
491
+ ...on
492
+ ? [
493
+ trigger('join', 'insert', on, [held('new', [])]),
494
+ trigger('leave', 'delete', on, [held('old', [lit('delete')])]),
495
+ ]
496
+ : [],
497
+ ]
498
+ }
499
+
500
+ // The view presenting an index's columns as text, joined to `on` for a scoped
501
+ // one.
502
+ let view = (ix: Index, derived: Derived): CreateView => {
503
+ let { comp, props, on } = ix, columns = columnsOf(ix)
504
+ let read = reader(ix, derived)
505
+ let c = on ? 'c' : undefined
506
+ return {
507
+ t: 'create view',
508
+ name: viewOf(ix),
509
+ ifNot: true,
510
+ q: select({
511
+ cols: [
512
+ as(col('entity', c), 'entity'),
513
+ ...props.map((p, i) => as(read(p, col(columns[i], c)), columns[i])),
514
+ as(col('entity', c), 'rowid'),
515
+ ],
516
+ from: contentTable(comp, c),
517
+ joins: on
518
+ ? [
519
+ join(
520
+ contentTable(on, 'o'),
521
+ eq(col('entity', 'o'), col('entity', 'c')),
522
+ ),
523
+ ]
524
+ : [],
525
+ }),
526
+ }
527
+ }
528
+
529
+ // The search schema installed on write, as statements in the order they
530
+ // must run: per index, its text view where one is needed, then the index and
531
+ // its triggers. Run them after the component tables exist — an
532
+ // external-content index names the table it mirrors. `derived` is the store's
533
+ // read overrides (@yaks/sql `Derived`): a column whose stored value is not its
534
+ // text (@yaks/blob `blobRead` registers one per body) is indexed through its
535
+ // `text` expression, which resolves the old and new values without re-reading
536
+ // the owner row. An override with no `text` would index the stored value, so it
537
+ // is refused.
538
+ export let schema = (
539
+ fields: Field[],
540
+ derived: Derived = {},
541
+ vocab?: Vocab,
542
+ ): Stmt[] => {
543
+ for (let { comp, prop } of fields) {
544
+ let key = `${comp}.${prop}`
545
+ if (derived[key] && !derived[key].text) {
546
+ throw new Error(
547
+ `FTS ${key}: read override needs a stored-value text expression`,
548
+ )
549
+ }
550
+ }
551
+ return indexes(fields, vocab).flatMap((ix) => index(ix, derived))
552
+ }
553
+
554
+ /**
555
+ * The text every index reads, one select per index: its properties off the
556
+ * table or view it is kept from, the way its triggers read them. What a
557
+ * whole-store pass over the indexed text reads (./lexicon.ts). Given the
558
+ * file, only the indexes whose tables it holds.
559
+ */
560
+ export let sources = (
561
+ fields: Field[],
562
+ derived: Derived = {},
563
+ db?: Driver,
564
+ ): Stmt[] =>
565
+ (db ? standing(db, worded(fields)) : indexes(worded(fields))).map((ix) => {
566
+ let source = sourceOf(ix, derived)
567
+ return select({
568
+ cols: ix.props.map((p, i) =>
569
+ as(col(source == ix.comp ? field(p) : columnsOf(ix)[i]), p)
570
+ ),
571
+ from: table(source),
572
+ })
573
+ })
574
+
575
+ // The indexes of `fields` whose tables the file holds. A store makes a
576
+ // component's table the first time a write names it (@yaks/sqlite), and an
577
+ // index with it; until then there is nothing to index, adopt or heal.
578
+ // `made` also counts an index that stands without its tables, which is not
579
+ // one waiting for a write but one whose table something else dropped.
580
+ let standing = (db: Driver, fields: Field[], made = false): Index[] => {
581
+ let tables = new Set(
582
+ catalogue(db).filter((o) => o.type == 'table').map((o) => o.name),
583
+ )
584
+ return indexes(fields, db.stored?.v).filter((ix) =>
585
+ tables.has(ix.comp) && (!ix.on || tables.has(ix.on)) ||
586
+ made && tables.has(tableOf(ix))
587
+ )
588
+ }
589
+
590
+ // Is index `fts` still consistent with the table `of` it holds a row for
591
+ // each row of? Two checks, the cheap one first: does it hold one row per row
592
+ // of the table (a tail index's of its piece table), and does FTS5's
593
+ // own integrity check pass. Returns a description of the problem, or undefined
594
+ // for a healthy index.
595
+ //
596
+ // The row count is read from the index's `_docsize` shadow table, never as
597
+ // `count(*)` over the index itself: for an external-content index SQLite
598
+ // computes that count from the table it mirrors, so it would agree with the
599
+ // table by construction and never notice a row the triggers missed.
600
+ //
601
+ // Start-up asks only for the row count. FTS5's own integrity check reads both
602
+ // shadow tables in full — 0.4s on a thirty-thousand-row index, seconds on a
603
+ // larger one — to detect damage no writer of ours can cause, so it runs only
604
+ // when a caller asks for it (`deep: true`), never on the pass a command line
605
+ // makes on its way in. The row count is what catches the drift a missed
606
+ // trigger leaves behind, which is the damage that actually happens.
607
+ //
608
+ // A scoped index holds one row per entity carrying both components, so its
609
+ // rows are counted through its view's join rather than off the text's table.
610
+ // Both counts belong to one statement's read snapshot: a writer committing
611
+ // between separate reads would make a whole index look incomplete and cause
612
+ // a needless rebuild, holding the writer for the entire transcript archive.
613
+ let fault = (
614
+ db: Driver,
615
+ fts: string,
616
+ of: string,
617
+ deep: boolean,
618
+ ): string | undefined => {
619
+ let rows = (t: string) => sub(select({ cols: [count()], from: table(t) }))
620
+ try {
621
+ let counts = db.query(select({
622
+ cols: [
623
+ as(rows(`${fts}_docsize`), 'indexed'),
624
+ as(rows(of), 'held'),
625
+ ],
626
+ }))[0]
627
+ let indexed = Number(counts.indexed), held = Number(counts.held)
628
+ if (indexed != held) return `${fts} holds ${indexed} of ${held} rows`
629
+ if (deep) db.query(command(fts, 'integrity-check', 1))
630
+ } catch (e) {
631
+ return e instanceof Error ? e.message : String(e)
632
+ }
633
+ }
634
+
635
+ // What an index is checked against: a row for each of its component's, or of
636
+ // its view's join for a scoped one.
637
+ let heldOf = (ix: Index): string => ix.on ? viewOf(ix) : ix.comp
638
+
639
+ export type HealOpts = {
640
+ // also run FTS5's own integrity check, not just the row count (default
641
+ // false) — it reads the whole index, so it suits a maintenance pass rather
642
+ // than start-up
643
+ deep?: boolean
644
+ /** Who refills a drifted index in windows, rather than `rebuild`ing it in
645
+ * one statement. An index it is filling already holds only the rows its
646
+ * cursor has passed, so it is left to it. */
647
+ fill?: Filler
648
+ /** The store's read overrides, which the triggers of an index being
649
+ * refilled read its columns through (`schema`). */
650
+ derived?: Derived
651
+ }
652
+
653
+ // Check every index and rebuild the ones that have drifted, or have `fill`
654
+ // refill them; returns the names of the indexes rebuilt or owed (usually
655
+ // none). A rebuild that does not fix the problem throws an error naming both
656
+ // results — the first reports what was wrong, the second whether the damage
657
+ // extends beyond the index.
658
+ export let heal = (
659
+ db: Driver,
660
+ fields: Field[],
661
+ opts: HealOpts = {},
662
+ ): string[] => {
663
+ let deep = opts.deep ?? false
664
+ let derived = opts.derived ?? {}
665
+ let healed: string[] = []
666
+ for (let ix of standing(db, fields, true)) {
667
+ let fts = tableOf(ix)
668
+ if (opts.fill?.pending(fts)) continue
669
+ let before = fault(db, fts, heldOf(ix), deep)
670
+ // A tail index is checked against its piece table, and emptied when it
671
+ // drifted or its substring index did, its texts owed again.
672
+ if (ix.trigram && holds(db, tailOf(ix))) {
673
+ let drifted = !before && fault(db, tailOf(ix), piecesOf(ix), deep)
674
+ if (before || drifted) forget(db, ix)
675
+ if (drifted) healed.push(tailOf(ix))
676
+ }
677
+ if (!before) continue
678
+ healed.push(fts)
679
+ let cursor = opts.fill?.owe(filling(ix, derived))
680
+ if (cursor) {
681
+ erect(db, behind(db, ix, derived, cursor))
682
+ continue
683
+ }
684
+ db.query(command(fts, 'rebuild'))
685
+ let after = fault(db, fts, heldOf(ix), deep)
686
+ if (after) {
687
+ throw new Error(
688
+ `${fts} is still broken after a rebuild; before: ${before}; after: ${after}`,
689
+ )
690
+ }
691
+ }
692
+ return healed
693
+ }
694
+
695
+ // What `adopt` did, by index name: the indexes it created or re-created (and
696
+ // so rebuilt from their tables), the triggers it dropped because they were not
697
+ // this package's, and the indexes `heal` rebuilt afterwards.
698
+ export type Adopted = {
699
+ recut: string[]
700
+ dropped: string[]
701
+ healed: string[]
702
+ }
703
+
704
+ // The columns an index declares, in order, as SQLite reports them; [] when the
705
+ // index does not exist.
706
+ let declared = (db: Driver, fts: string): string[] => {
707
+ try {
708
+ return db.query({ t: 'pragma', name: 'table_info', arg: fts })
709
+ .map((r) => String(r.name))
710
+ } catch {
711
+ return []
712
+ }
713
+ }
714
+
715
+ // The schema objects of one type, with the text each was created by.
716
+ let objects = (
717
+ schema: ReturnType<typeof catalogue>,
718
+ type: string,
719
+ name?: string,
720
+ ) => schema.filter((o) => o.type == type && (name == null || o.name == name))
721
+
722
+ // The text a schema object was created by, or undefined when there is none.
723
+ let stored = (
724
+ schema: ReturnType<typeof catalogue>,
725
+ type: string,
726
+ name: string,
727
+ ): string | undefined => {
728
+ let row = objects(schema, type, name)[0]
729
+ return row ? String(row.sql ?? '') : undefined
730
+ }
731
+
732
+ // Where an index reads its content back from: the `content=` name in its own
733
+ // definition, or undefined when the index does not exist.
734
+ let source = (
735
+ schema: ReturnType<typeof catalogue>,
736
+ fts: string,
737
+ ): string | undefined =>
738
+ /content='([^']*)'/.exec(stored(schema, 'table', fts) ?? '')?.[1]
739
+
740
+ // A definition with its `create view [if not exists]` preamble removed. SQLite
741
+ // stores the statement it was given minus the `if not exists`, with its leading
742
+ // keywords in capitals, so the part from the name onward is what two
743
+ // definitions can be compared by.
744
+ let body = (sql: string, name: string): string => {
745
+ let at = `"${name}"`
746
+ return sql.slice(sql.indexOf(at) + at.length).trim()
747
+ }
748
+
749
+ // Keep populated tails whose definitions still match. Empty tails from an
750
+ // eager install and tails that need refilling can wait for the next window.
751
+ let fitTail = (
752
+ db: Driver,
753
+ before: ReturnType<typeof catalogue>,
754
+ ix: Index,
755
+ derived: Derived,
756
+ rebuild: boolean,
757
+ ): void => {
758
+ let fts = tailOf(ix), list = piecesOf(ix)
759
+ if (!before.some(({ name }) => name == list || name.startsWith(fts))) return
760
+ let objects = tail(ix, derived).map((stmt) => {
761
+ let kind: Drop['kind'] = stmt.t == 'create view'
762
+ ? 'view'
763
+ : stmt.t == 'create trigger'
764
+ ? 'trigger'
765
+ : 'table'
766
+ return { stmt, kind, name: stmt.name, sql: stored(before, kind, stmt.name) }
767
+ })
768
+ if (!objects.some(({ sql }) => sql != null)) return
769
+ let intact = !rebuild && objects.every(({ stmt, name, sql }) =>
770
+ sql != null &&
771
+ body(sql, name) ==
772
+ body(render(stmt, undefined, undefined, db.stored?.v).sql, name)
773
+ )
774
+ if (
775
+ intact && db.query(select({
776
+ cols: [lit(1)],
777
+ from: table(list),
778
+ limit: lit(1),
779
+ })).length
780
+ ) return
781
+ for (let { kind, name, sql } of objects.reverse()) {
782
+ if (sql != null) db.query({ t: 'drop', kind, name, ifExists: true })
783
+ }
784
+ }
785
+
786
+ // The names of any triggers that write into an index other than this package's
787
+ // own.
788
+ let strays = (schema: ReturnType<typeof catalogue>, ix: Index): string[] => {
789
+ let fts = tableOf(ix)
790
+ let ours = new Set(owned(ix))
791
+ let word = new RegExp(`\\b${fts}\\b`)
792
+ return objects(schema, 'trigger')
793
+ .filter((r) => !ours.has(String(r.name)) && word.test(String(r.sql ?? '')))
794
+ .map((r) => String(r.name))
795
+ }
796
+
797
+ // Make a database's search objects match what `schema()` returns, and be
798
+ // consistent with their tables.
799
+ //
800
+ // For each index: one whose declared columns already match is kept, with its
801
+ // indexed terms intact; one that is missing or declares different columns is
802
+ // dropped, created again from the schema, and rebuilt from its table (a new
803
+ // external-content index starts out empty). Any trigger writing into the index
804
+ // that is not one of this package's own is dropped, and ours are created
805
+ // again. A view holds no rows, so the text view is re-created whenever the one
806
+ // in the database differs from what `schema()` returns — but only then:
807
+ // dropping a view is a schema write, and a process that calls `adopt()` on
808
+ // every start-up should be able to start up without writing anything. A
809
+ // trigger of ours written by an earlier version of this package is re-created
810
+ // the same way. Finally `heal` checks the row counts, so an index that was
811
+ // kept but is missing rows — one created after part of its table already
812
+ // existed — is rebuilt too.
813
+ //
814
+ // Everything else runs with `if not exists` / `if exists`, so a second call on
815
+ // the same database changes nothing, writes nothing, and returns empty lists.
816
+ export type AdoptOpts = Omit<HealOpts, 'derived'> & {
817
+ /** Check retained indexes for drift (default true). Schema installation can
818
+ * keep unchanged indexes without reading their content. */
819
+ heal?: boolean
820
+ }
821
+
822
+ /** An index to fill: its name, where it reads its content back from, its
823
+ * columns, and the triggers it keeps once it holds every row. */
824
+ export type Fill = {
825
+ fts: string
826
+ source: string
827
+ props: string[]
828
+ fields?: string[]
829
+ triggers: CreateTrigger[]
830
+ }
831
+
832
+ // What filling `ix` takes: where it reads its content back from, its
833
+ // columns, and the triggers it keeps once it holds every row.
834
+ let filling = (ix: Index, derived: Derived): Fill => ({
835
+ fts: tableOf(ix),
836
+ source: sourceOf(ix, derived),
837
+ props: columnsOf(ix),
838
+ ...sourceOf(ix, derived) == ix.comp ? { fields: ix.props.map(field) } : {},
839
+ triggers: index(ix, derived).filter((s) => s.t == 'create trigger'),
840
+ })
841
+
842
+ // Empty a standing index for windows to fill behind `cursor`: its rows go,
843
+ // and so do its triggers, whose replacements keep only the rows the cursor
844
+ // has passed. Returns its statements, with those triggers, to raise.
845
+ let behind = (db: Driver, ix: Index, derived: Derived, cursor: Expr) => {
846
+ let fts = tableOf(ix)
847
+ if (declared(db, fts).length) db.query(command(fts, 'delete-all'))
848
+ for (let t of owned(ix)) {
849
+ db.query({ t: 'drop', kind: 'trigger', name: t, ifExists: true })
850
+ }
851
+ return index(ix, derived, cursor)
852
+ }
853
+
854
+ /**
855
+ * Someone who fills an index in windows, behind a cursor: its triggers keep
856
+ * only the rows the cursor has passed, each window reads the next rows from
857
+ * the index's content into it, and the last puts {@link Fill.triggers} in
858
+ * place. @yaks/sqlite's owed work is one.
859
+ */
860
+ export type Filler = {
861
+ /** the cursor an index still being filled guards its triggers with */
862
+ pending: (fts: string) => Expr | undefined
863
+ /** take on filling `fill`, which is empty: its cursor, or undefined to have
864
+ * it rebuilt at once */
865
+ owe: (fill: Fill) => Expr | undefined
866
+ }
867
+
868
+ export let adopt = (
869
+ db: Driver,
870
+ fields: Field[],
871
+ derived: Derived = {},
872
+ opts: AdoptOpts = {},
873
+ ): Adopted => {
874
+ let recut: string[] = [], dropped: string[] = []
875
+ // Adoption compares the objects that stood when it began. Its own DDL
876
+ // must not make every later comparison reread the entire schema.
877
+ let before = catalogue(db)
878
+ let v = db.stored?.v
879
+ let written = (s: Stmt) => render(s, undefined, undefined, v).sql
880
+ let gone = (kind: 'trigger' | 'view' | 'table', name: string) =>
881
+ db.query({ t: 'drop', kind, name, ifExists: true })
882
+ // What one of `mine` would be stored as, by the name it creates.
883
+ let text = (mine: Stmt[], name: string): string | undefined => {
884
+ let s = mine.find((s) =>
885
+ (s.t == 'create view' || s.t == 'create trigger') && s.name == name
886
+ )
887
+ return s && written(s)
888
+ }
889
+ let planned: {
890
+ ix: Index
891
+ mine: Stmt[]
892
+ rebuild: boolean
893
+ cursor?: Expr
894
+ }[] = []
895
+ for (let ix of standing(db, fields)) {
896
+ let fts = tableOf(ix)
897
+ let have = declared(db, fts)
898
+ let columns = columnsOf(ix)
899
+ let same = have.length == columns.length &&
900
+ have.every((c, i) => c == columns[i]) &&
901
+ tableAsWritten(v, source(before, fts) ?? '') == sourceOf(ix, derived)
902
+ for (let t of strays(before, ix)) {
903
+ gone('trigger', t)
904
+ dropped.push(t)
905
+ }
906
+ let pending = opts.fill?.pending(fts)
907
+ let mine = index(ix, derived, pending)
908
+ let changed = false
909
+ let ours: ['view' | 'trigger', string][] = [
910
+ ['view', viewOf(ix)],
911
+ ...owned(ix).map((t): ['trigger', string] => ['trigger', t]),
912
+ ]
913
+ for (let [kind, name] of ours) {
914
+ let had = stored(before, kind, name)
915
+ let now = text(mine, name)
916
+ if (
917
+ had != null &&
918
+ (kind == 'trigger' && !same || now == null ||
919
+ body(had, name) != body(now, name))
920
+ ) {
921
+ gone(kind, name)
922
+ changed = true
923
+ }
924
+ // A rebuilt content table loses its triggers, but not its external
925
+ // index. Refill that index before its replacement writers start.
926
+ if (kind == 'trigger' && had == null) changed = true
927
+ }
928
+ if (!same) gone('table', fts)
929
+ let rebuild = !same || opts.heal === false && changed
930
+ if (ix.trigram) fitTail(db, before, ix, derived, rebuild)
931
+ planned.push({ ix, mine, rebuild })
932
+ }
933
+ // Size every fill against its content view before installing any indexes.
934
+ // Raising each index separately would invalidate the catalogue for the next
935
+ // one: a fresh host would repeatedly load its entire growing schema.
936
+ if (opts.fill) {
937
+ erect(
938
+ db,
939
+ planned.flatMap(({ mine, rebuild }) =>
940
+ rebuild ? mine.filter((s) => s.t == 'create view') : []
941
+ ),
942
+ )
943
+ for (let plan of planned) {
944
+ if (plan.rebuild) plan.cursor = opts.fill.owe(filling(plan.ix, derived))
945
+ }
946
+ }
947
+ for (let plan of planned) {
948
+ // Filled in windows: an emptied index, and triggers behind the cursor.
949
+ if (plan.cursor) plan.mine = behind(db, plan.ix, derived, plan.cursor)
950
+ }
951
+ erect(db, planned.flatMap(({ mine }) => mine))
952
+ for (let { ix, rebuild, cursor } of planned) {
953
+ if (!rebuild) continue
954
+ let fts = tableOf(ix)
955
+ if (!cursor) db.query(command(fts, 'rebuild'))
956
+ recut.push(fts)
957
+ }
958
+ let healed = opts.heal === false ? [] : heal(db, fields, { ...opts, derived })
959
+ return { recut, dropped, healed }
960
+ }