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