@yaks/sqlite 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 +1596 -2
- package/_dist/archetype.d.ts +75 -0
- package/_dist/archetype.d.ts.map +1 -0
- package/_dist/branches.d.ts +23 -0
- package/_dist/branches.d.ts.map +1 -0
- package/_dist/budget.d.ts +52 -0
- package/_dist/budget.d.ts.map +1 -0
- package/_dist/bundle.d.ts +2 -0
- package/_dist/bundle.d.ts.map +1 -0
- package/_dist/cache.d.ts +24 -0
- package/_dist/cache.d.ts.map +1 -0
- package/_dist/catalog.d.ts +9 -0
- package/_dist/catalog.d.ts.map +1 -0
- package/_dist/check.d.ts +4 -0
- package/_dist/check.d.ts.map +1 -0
- package/_dist/db.d.ts +36 -0
- package/_dist/db.d.ts.map +1 -0
- package/_dist/ddl.d.ts +143 -0
- package/_dist/ddl.d.ts.map +1 -0
- package/_dist/doom.d.ts +22 -0
- package/_dist/doom.d.ts.map +1 -0
- package/_dist/follow.d.ts +74 -0
- package/_dist/follow.d.ts.map +1 -0
- package/_dist/history-shapes.d.ts +3 -0
- package/_dist/history-shapes.d.ts.map +1 -0
- package/_dist/history.d.ts +18 -0
- package/_dist/history.d.ts.map +1 -0
- package/_dist/inspect.d.ts +43 -0
- package/_dist/inspect.d.ts.map +1 -0
- package/_dist/jsonb.d.ts +17 -0
- package/_dist/jsonb.d.ts.map +1 -0
- package/_dist/layout.d.ts +7 -0
- package/_dist/layout.d.ts.map +1 -0
- package/_dist/ledger.d.ts +41 -0
- package/_dist/ledger.d.ts.map +1 -0
- package/_dist/meta.d.ts +89 -0
- package/_dist/meta.d.ts.map +1 -0
- package/_dist/migration.d.ts +41 -0
- package/_dist/migration.d.ts.map +1 -0
- package/_dist/mod.d.ts +201 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/mode.d.ts +14 -0
- package/_dist/mode.d.ts.map +1 -0
- package/_dist/overlay.d.ts +30 -0
- package/_dist/overlay.d.ts.map +1 -0
- package/_dist/owe.d.ts +180 -0
- package/_dist/owe.d.ts.map +1 -0
- package/_dist/physical.d.ts +89 -0
- package/_dist/physical.d.ts.map +1 -0
- package/_dist/point.d.ts +10 -0
- package/_dist/point.d.ts.map +1 -0
- package/_dist/raise.d.ts +22 -0
- package/_dist/raise.d.ts.map +1 -0
- package/_dist/read-db.d.ts +9 -0
- package/_dist/read-db.d.ts.map +1 -0
- package/_dist/read-store.d.ts +10 -0
- package/_dist/read-store.d.ts.map +1 -0
- package/_dist/read.d.ts +59 -0
- package/_dist/read.d.ts.map +1 -0
- package/_dist/reader.d.ts +11 -0
- package/_dist/reader.d.ts.map +1 -0
- package/_dist/rules.d.ts +19 -0
- package/_dist/rules.d.ts.map +1 -0
- package/_dist/service.d.ts +12 -0
- package/_dist/service.d.ts.map +1 -0
- package/_dist/shape.d.ts +12 -0
- package/_dist/shape.d.ts.map +1 -0
- package/_dist/statements.d.ts +4 -0
- package/_dist/statements.d.ts.map +1 -0
- package/_dist/survey.d.ts +31 -0
- package/_dist/survey.d.ts.map +1 -0
- package/_dist/tools.d.ts +15 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/trash.d.ts +18 -0
- package/_dist/trash.d.ts.map +1 -0
- package/_dist/unit.d.ts +11 -0
- package/_dist/unit.d.ts.map +1 -0
- package/_dist/vocab.d.ts +6 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/_dist/write.d.ts +169 -0
- package/_dist/write.d.ts.map +1 -0
- package/answer.js +110 -0
- package/answer.js.map +1 -0
- package/answer.ts +122 -0
- package/archetype.js +730 -0
- package/archetype.js.map +1 -0
- package/archetype.ts +790 -0
- package/binary_cases.ts +240 -0
- package/branches.js +195 -0
- package/branches.js.map +1 -0
- package/branches.ts +257 -0
- package/budget.js +89 -0
- package/budget.js.map +1 -0
- package/budget.ts +117 -0
- package/builtin.js +34 -0
- package/builtin.js.map +1 -0
- package/builtin.ts +31 -0
- package/bundle.js +21 -0
- package/bundle.js.map +1 -0
- package/bundle.ts +22 -0
- package/buried.js +95 -0
- package/buried.js.map +1 -0
- package/buried.ts +124 -0
- package/cache.js +153 -0
- package/cache.js.map +1 -0
- package/cache.ts +154 -0
- package/cache_worker.ts +16 -0
- package/catalog.js +173 -0
- package/catalog.js.map +1 -0
- package/catalog.ts +224 -0
- package/check.js +80 -0
- package/check.js.map +1 -0
- package/check.ts +92 -0
- package/checkpoint.js +98 -0
- package/checkpoint.js.map +1 -0
- package/checkpoint.ts +129 -0
- package/checkpoint_worker.ts +37 -0
- package/db.js +170 -0
- package/db.js.map +1 -0
- package/db.ts +173 -0
- package/ddl.js +1441 -0
- package/ddl.js.map +1 -0
- package/ddl.ts +1508 -0
- package/deno.json +1 -0
- package/doom.js +59 -0
- package/doom.js.map +1 -0
- package/doom.ts +75 -0
- package/driver.js +69 -0
- package/driver.js.map +1 -0
- package/driver.ts +101 -0
- package/error.js +30 -0
- package/error.js.map +1 -0
- package/error.ts +46 -0
- package/ffi/LICENSE +202 -0
- package/ffi/blob.js +99 -0
- package/ffi/blob.js.map +1 -0
- package/ffi/blob.ts +156 -0
- package/ffi/constants.js +65 -0
- package/ffi/constants.js.map +1 -0
- package/ffi/constants.ts +67 -0
- package/ffi/database.js +613 -0
- package/ffi/database.js.map +1 -0
- package/ffi/database.ts +931 -0
- package/ffi/ffi.js +535 -0
- package/ffi/ffi.js.map +1 -0
- package/ffi/ffi.ts +604 -0
- package/ffi/mod.js +15 -0
- package/ffi/mod.js.map +1 -0
- package/ffi/mod.ts +28 -0
- package/ffi/statement.js +555 -0
- package/ffi/statement.js.map +1 -0
- package/ffi/statement.ts +788 -0
- package/ffi/util.js +32 -0
- package/ffi/util.js.map +1 -0
- package/ffi/util.ts +48 -0
- package/follow.js +342 -0
- package/follow.js.map +1 -0
- package/follow.ts +401 -0
- package/history-branch.js +166 -0
- package/history-branch.js.map +1 -0
- package/history-branch.ts +140 -0
- package/history-shapes.js +254 -0
- package/history-shapes.js.map +1 -0
- package/history-shapes.ts +268 -0
- package/history.js +620 -0
- package/history.js.map +1 -0
- package/history.ts +674 -0
- package/inspect.js +120 -0
- package/inspect.js.map +1 -0
- package/inspect.ts +164 -0
- package/jsonb.js +73 -0
- package/jsonb.js.map +1 -0
- package/jsonb.ts +108 -0
- package/layout.js +22 -0
- package/layout.js.map +1 -0
- package/layout.ts +26 -0
- package/ledger.js +210 -0
- package/ledger.js.map +1 -0
- package/ledger.ts +210 -0
- package/legacy.js +4 -0
- package/legacy.js.map +1 -0
- package/legacy.ts +3 -0
- package/maintenance.js +148 -0
- package/maintenance.js.map +1 -0
- package/maintenance.ts +154 -0
- package/measure.js +133 -0
- package/measure.js.map +1 -0
- package/measure.ts +167 -0
- package/measure_worker.ts +18 -0
- package/memo.js +1250 -0
- package/memo.js.map +1 -0
- package/memo.ts +1480 -0
- package/meta.js +265 -0
- package/meta.js.map +1 -0
- package/meta.ts +321 -0
- package/migration.js +272 -0
- package/migration.js.map +1 -0
- package/migration.ts +286 -0
- package/mod.js +1103 -0
- package/mod.js.map +1 -0
- package/mod.ts +1762 -0
- package/mode.js +192 -0
- package/mode.js.map +1 -0
- package/mode.ts +207 -0
- package/native.js +544 -0
- package/native.js.map +1 -0
- package/native.ts +544 -0
- package/overlay.js +408 -0
- package/overlay.js.map +1 -0
- package/overlay.ts +485 -0
- package/owe.js +719 -0
- package/owe.js.map +1 -0
- package/owe.ts +873 -0
- package/package.json +99 -4
- package/physical.js +350 -0
- package/physical.js.map +1 -0
- package/physical.ts +434 -0
- package/plan.js +78 -0
- package/plan.js.map +1 -0
- package/plan.ts +104 -0
- package/point.js +81 -0
- package/point.js.map +1 -0
- package/point.ts +52 -0
- package/population.js +639 -0
- package/population.js.map +1 -0
- package/population.ts +630 -0
- package/purge.js +117 -0
- package/purge.js.map +1 -0
- package/purge.ts +127 -0
- package/raise.js +270 -0
- package/raise.js.map +1 -0
- package/raise.ts +316 -0
- package/read-db.js +381 -0
- package/read-db.js.map +1 -0
- package/read-db.ts +282 -0
- package/read-store.js +74 -0
- package/read-store.js.map +1 -0
- package/read-store.ts +86 -0
- package/read.js +1100 -0
- package/read.js.map +1 -0
- package/read.ts +1441 -0
- package/reader.js +141 -0
- package/reader.js.map +1 -0
- package/reader.ts +159 -0
- package/rules.js +88 -0
- package/rules.js.map +1 -0
- package/rules.ts +113 -0
- package/service.js +27 -0
- package/service.js.map +1 -0
- package/service.ts +41 -0
- package/shape.js +76 -0
- package/shape.js.map +1 -0
- package/shape.ts +108 -0
- package/sparse_presence_fixture.ts +45 -0
- package/sqlitepath.js +24 -0
- package/sqlitepath.js.map +1 -0
- package/sqlitepath.ts +29 -0
- package/statements.js +78 -0
- package/statements.js.map +1 -0
- package/statements.ts +96 -0
- package/survey.js +135 -0
- package/survey.js.map +1 -0
- package/survey.ts +196 -0
- package/tools.js +17 -0
- package/tools.js.map +1 -0
- package/tools.ts +50 -0
- package/trash.js +144 -0
- package/trash.js.map +1 -0
- package/trash.ts +187 -0
- package/unit.js +215 -0
- package/unit.js.map +1 -0
- package/unit.ts +211 -0
- package/versions.js +115 -0
- package/versions.js.map +1 -0
- package/versions.ts +110 -0
- package/vocab.js +19 -0
- package/vocab.js.map +1 -0
- package/vocab.json +27 -0
- package/vocab.ts +19 -0
- package/watch.js +33 -0
- package/watch.js.map +1 -0
- package/watch.ts +42 -0
- package/write.js +1164 -0
- package/write.js.map +1 -0
- package/write.ts +1356 -0
- package/written.js +200 -0
- package/written.js.map +1 -0
- package/written.ts +202 -0
package/ddl.js
ADDED
|
@@ -0,0 +1,1441 @@
|
|
|
1
|
+
// The schema, derived from a vocabulary. Given a `Vocab` (from @yaks/vocab)
|
|
2
|
+
// this emits the ordered `CREATE` statements whose tables the compiled queries
|
|
3
|
+
// from @yaks/sql read and the writes in ./write.ts patch. One function, one
|
|
4
|
+
// truth: the storage shape is a projection of the vocabulary, never a second
|
|
5
|
+
// hand-kept copy that can drift from it.
|
|
6
|
+
//
|
|
7
|
+
// The layout every statement here builds toward — the same one @yaks/sql's
|
|
8
|
+
// SQLite dialect reads:
|
|
9
|
+
// entity the identity table: an integer `id`, a string `eid`, a `num`.
|
|
10
|
+
// Every other table keys to `entity(id)` by an integer, so a
|
|
11
|
+
// reference is an integer compare after one id lookup.
|
|
12
|
+
// tombstone a deleted entity keeps its `entity` row (its eid, number
|
|
13
|
+
// and integer id) and gains a tombstone row; reads exclude it,
|
|
14
|
+
// and a later write that brings it back deletes the row.
|
|
15
|
+
// <component> one table per component, keyed by an `entity` integer owner.
|
|
16
|
+
// A scalar column stores its value; a reference stores the
|
|
17
|
+
// referent's integer id; a component with no properties is a
|
|
18
|
+
// bare tag whose presence is the fact.
|
|
19
|
+
// <index> declared indexes plus automatic reference indexes, named after
|
|
20
|
+
// the columns it covers. A unique one is the constraint a race
|
|
21
|
+
// is decided by; the vocabulary is where it is declared.
|
|
22
|
+
// doc_value a view over the `doc` component (when the vocabulary declares
|
|
23
|
+
// one): its columns read as text, plus a `rowid` alias. It is
|
|
24
|
+
// what @yaks/sql reads a `doc` row through.
|
|
25
|
+
// server_meta the store's own key/value, beside the graph: what the store
|
|
26
|
+
// knows about itself (its epoch, a sweep's mark), never about
|
|
27
|
+
// an entity. ./meta.ts reads and writes it.
|
|
28
|
+
//
|
|
29
|
+
// Every statement is a node of @yaks/sql's AST; nothing here writes SQL text.
|
|
30
|
+
//
|
|
31
|
+
// Columns are nullable by default: a patch may create a row from any subset of
|
|
32
|
+
// its properties (that is what PATCH means), so a column requires a value only
|
|
33
|
+
// where the vocabulary declares one — a `required` property is NOT NULL, and
|
|
34
|
+
// the row that omits it is rejected by the engine unless a `default` fills it.
|
|
35
|
+
// An `enum` becomes a check, so a value outside the set is rejected where it is
|
|
36
|
+
// written. A reference carries a foreign key so a dangling id is rejected by
|
|
37
|
+
// the engine, except a `keep` reference, which outlives the row it points at
|
|
38
|
+
// and stays key-free.
|
|
39
|
+
import { field, indexName, stored as sqlStored, tableAsWritten } from "@yaks/sql";
|
|
40
|
+
import { loadVocab } from "@yaks/vocab";
|
|
41
|
+
import { archetypeDoc } from "@yaks/archetype/sets";
|
|
42
|
+
import { among, and, as, col, count, eq, exists, fn, from, gt, isNull, left, lit, notNull, NOW, render, scan, select, sub, table, val } from "@yaks/sql";
|
|
43
|
+
import { checks, foreign, mainTables, objects, sole, stood } from "./physical.js";
|
|
44
|
+
import { unit } from "./unit.js";
|
|
45
|
+
import { TRASH } from "./trash.js";
|
|
46
|
+
import { clocked, versioned } from "./versions.js";
|
|
47
|
+
// A statement as the file keeps it: written with the names `v` stores its
|
|
48
|
+
// words under (@yaks/sql `render`).
|
|
49
|
+
let text = (s, v)=>render(s, undefined, undefined, v).sql;
|
|
50
|
+
import { telling, writtenDdl } from "./written.js";
|
|
51
|
+
import { tallying } from "./population.js";
|
|
52
|
+
import { META, tables } from "./layout.js";
|
|
53
|
+
export { META, tables } from "./layout.js";
|
|
54
|
+
// A column that holds an entity's integer id, keyed to the spine.
|
|
55
|
+
let ENTITY = {
|
|
56
|
+
table: 'entity',
|
|
57
|
+
cols: [
|
|
58
|
+
'id'
|
|
59
|
+
]
|
|
60
|
+
};
|
|
61
|
+
// The high-water mark a new number in a series is taken past, raised by
|
|
62
|
+
// whatever wrote one.
|
|
63
|
+
let raiseSeries = {
|
|
64
|
+
t: 'insert',
|
|
65
|
+
into: 'entity_series',
|
|
66
|
+
cols: [
|
|
67
|
+
'prefix',
|
|
68
|
+
'high'
|
|
69
|
+
],
|
|
70
|
+
rows: [
|
|
71
|
+
[
|
|
72
|
+
col('prefix', 'new'),
|
|
73
|
+
col('num', 'new')
|
|
74
|
+
]
|
|
75
|
+
],
|
|
76
|
+
upsert: [
|
|
77
|
+
{
|
|
78
|
+
on: [
|
|
79
|
+
col('prefix')
|
|
80
|
+
],
|
|
81
|
+
set: {
|
|
82
|
+
high: fn('max', col('high'), col('high', 'excluded'))
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
]
|
|
86
|
+
};
|
|
87
|
+
let lettered = and(notNull(col('num', 'new')), notNull(col('prefix', 'new')));
|
|
88
|
+
// The identity table, the tombstones, and the store's own key/value. Fixed
|
|
89
|
+
// shape — every layout has exactly this spine, whatever components sit on
|
|
90
|
+
// it.
|
|
91
|
+
let SPINE = [
|
|
92
|
+
{
|
|
93
|
+
t: 'create table',
|
|
94
|
+
name: 'entity',
|
|
95
|
+
ifNot: true,
|
|
96
|
+
cols: [
|
|
97
|
+
{
|
|
98
|
+
name: 'id',
|
|
99
|
+
type: 'integer',
|
|
100
|
+
pk: true
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
name: 'eid',
|
|
104
|
+
type: 'text',
|
|
105
|
+
notNull: true,
|
|
106
|
+
unique: true
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
name: 'num',
|
|
110
|
+
type: 'integer'
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
name: 'archetype',
|
|
114
|
+
type: 'integer',
|
|
115
|
+
ref: ENTITY
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
name: 'prefix',
|
|
119
|
+
type: 'text'
|
|
120
|
+
}
|
|
121
|
+
]
|
|
122
|
+
},
|
|
123
|
+
// Each series' high-water mark, by its letter: what the next number in it
|
|
124
|
+
// is taken past (./write.ts `series`).
|
|
125
|
+
{
|
|
126
|
+
t: 'create table',
|
|
127
|
+
name: 'entity_series',
|
|
128
|
+
ifNot: true,
|
|
129
|
+
cols: [
|
|
130
|
+
{
|
|
131
|
+
name: 'prefix',
|
|
132
|
+
type: 'text',
|
|
133
|
+
pk: true
|
|
134
|
+
},
|
|
135
|
+
{
|
|
136
|
+
name: 'high',
|
|
137
|
+
type: 'integer',
|
|
138
|
+
notNull: true
|
|
139
|
+
}
|
|
140
|
+
]
|
|
141
|
+
},
|
|
142
|
+
// The one count every number was once taken from, before series had
|
|
143
|
+
// letters (T-164367).
|
|
144
|
+
{
|
|
145
|
+
t: 'drop',
|
|
146
|
+
kind: 'trigger',
|
|
147
|
+
name: 'entity_number_insert',
|
|
148
|
+
ifExists: true
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
t: 'drop',
|
|
152
|
+
kind: 'trigger',
|
|
153
|
+
name: 'entity_number_update',
|
|
154
|
+
ifExists: true
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
t: 'drop',
|
|
158
|
+
kind: 'table',
|
|
159
|
+
name: 'entity_sequence',
|
|
160
|
+
ifExists: true
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
t: 'create trigger',
|
|
164
|
+
name: 'entity_series_insert',
|
|
165
|
+
ifNot: true,
|
|
166
|
+
timing: 'after',
|
|
167
|
+
event: 'insert',
|
|
168
|
+
on: 'entity',
|
|
169
|
+
when: lettered,
|
|
170
|
+
body: [
|
|
171
|
+
raiseSeries
|
|
172
|
+
]
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
t: 'create trigger',
|
|
176
|
+
name: 'entity_series_update',
|
|
177
|
+
ifNot: true,
|
|
178
|
+
timing: 'after',
|
|
179
|
+
event: 'update',
|
|
180
|
+
of: [
|
|
181
|
+
'num',
|
|
182
|
+
'prefix'
|
|
183
|
+
],
|
|
184
|
+
on: 'entity',
|
|
185
|
+
when: lettered,
|
|
186
|
+
body: [
|
|
187
|
+
raiseSeries
|
|
188
|
+
]
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
t: 'create table',
|
|
192
|
+
name: 'tombstone',
|
|
193
|
+
ifNot: true,
|
|
194
|
+
cols: [
|
|
195
|
+
{
|
|
196
|
+
name: 'entity',
|
|
197
|
+
type: 'integer',
|
|
198
|
+
pk: true,
|
|
199
|
+
ref: ENTITY
|
|
200
|
+
},
|
|
201
|
+
{
|
|
202
|
+
name: 'deleted_at',
|
|
203
|
+
type: 'text',
|
|
204
|
+
notNull: true
|
|
205
|
+
}
|
|
206
|
+
]
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
t: 'create table',
|
|
210
|
+
name: TRASH,
|
|
211
|
+
ifNot: true,
|
|
212
|
+
cols: [
|
|
213
|
+
{
|
|
214
|
+
name: 'batch',
|
|
215
|
+
type: 'text',
|
|
216
|
+
notNull: true
|
|
217
|
+
},
|
|
218
|
+
{
|
|
219
|
+
name: 'entity',
|
|
220
|
+
type: 'integer',
|
|
221
|
+
notNull: true,
|
|
222
|
+
ref: ENTITY
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
name: 'at',
|
|
226
|
+
type: 'text',
|
|
227
|
+
notNull: true
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
name: 'body',
|
|
231
|
+
type: 'text',
|
|
232
|
+
notNull: true
|
|
233
|
+
}
|
|
234
|
+
],
|
|
235
|
+
keys: [
|
|
236
|
+
{
|
|
237
|
+
pk: [
|
|
238
|
+
'batch',
|
|
239
|
+
'entity'
|
|
240
|
+
]
|
|
241
|
+
}
|
|
242
|
+
]
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
t: 'create index',
|
|
246
|
+
name: '_yaks_trash_entity',
|
|
247
|
+
on: TRASH,
|
|
248
|
+
ifNot: true,
|
|
249
|
+
cols: [
|
|
250
|
+
col('entity')
|
|
251
|
+
]
|
|
252
|
+
},
|
|
253
|
+
// Keyed by `k`, valued by `v`, and nothing else: whatever an application
|
|
254
|
+
// keeps here it keeps as text under a name it chose (./meta.ts).
|
|
255
|
+
{
|
|
256
|
+
t: 'create table',
|
|
257
|
+
name: META,
|
|
258
|
+
ifNot: true,
|
|
259
|
+
cols: [
|
|
260
|
+
{
|
|
261
|
+
name: 'k',
|
|
262
|
+
type: 'text',
|
|
263
|
+
pk: true
|
|
264
|
+
},
|
|
265
|
+
{
|
|
266
|
+
name: 'v',
|
|
267
|
+
type: 'text',
|
|
268
|
+
notNull: true
|
|
269
|
+
}
|
|
270
|
+
]
|
|
271
|
+
}
|
|
272
|
+
];
|
|
273
|
+
// A property's default: the current time, or a literal a row takes when the
|
|
274
|
+
// writer supplied no value. A boolean stores as the integer it reads back as.
|
|
275
|
+
let fallback = (c)=>{
|
|
276
|
+
let d = c.default;
|
|
277
|
+
return !d ? undefined : 'now' in d ? NOW : lit(d.value);
|
|
278
|
+
};
|
|
279
|
+
// A closed set's check. Every value the vocabulary admits on the way in is
|
|
280
|
+
// admitted here too (an alias is an accepted input value), so the engine never
|
|
281
|
+
// rejects what the loader accepted.
|
|
282
|
+
let closed = (c)=>c.values ? among(col(field(c.prop)), [
|
|
283
|
+
...c.values,
|
|
284
|
+
...Object.keys(c.aliases ?? {})
|
|
285
|
+
].map(lit)) : undefined;
|
|
286
|
+
// A stored property's column. Affinity comes straight off the property as the
|
|
287
|
+
// vocabulary describes it; a reference carries a foreign key unless it is a
|
|
288
|
+
// `keep` reference, which must survive its target's tombstone and so carries
|
|
289
|
+
// none. `required` becomes NOT NULL; `default` and `enum` are emitted as above.
|
|
290
|
+
let column = (c)=>({
|
|
291
|
+
name: field(c.prop),
|
|
292
|
+
type: c.affinity || undefined,
|
|
293
|
+
notNull: c.required,
|
|
294
|
+
default: fallback(c),
|
|
295
|
+
check: closed(c),
|
|
296
|
+
ref: c.category == 'ref' && c.fk ? ENTITY : undefined
|
|
297
|
+
});
|
|
298
|
+
// The same column added to a standing table. SQLite refuses `add column` a
|
|
299
|
+
// NOT NULL without a constant default and any default that is an expression,
|
|
300
|
+
// so a grown column keeps its literal default and its CHECK, arrives NOT NULL
|
|
301
|
+
// only when a literal fills the rows already there, and takes the clock only
|
|
302
|
+
// on rows written from now on (the writer stamps them; NOW is for the row that
|
|
303
|
+
// omits it).
|
|
304
|
+
let grownColumn = (c)=>{
|
|
305
|
+
let d = c.default && 'value' in c.default ? lit(c.default.value) : undefined;
|
|
306
|
+
return {
|
|
307
|
+
...column(c),
|
|
308
|
+
notNull: c.required && !!d,
|
|
309
|
+
default: d
|
|
310
|
+
};
|
|
311
|
+
};
|
|
312
|
+
// Which of a component's declared properties are stored: everything the
|
|
313
|
+
// vocabulary lists except the computed ones (a computed property is read
|
|
314
|
+
// through a supplied expression, never off a row).
|
|
315
|
+
let stored = (v, comp)=>v.props(comp).map((prop)=>v.prop(comp, prop)).filter((c)=>!c.computed);
|
|
316
|
+
// One component's table. The `entity` owner is the primary key, so a component
|
|
317
|
+
// is stored at most once per entity. A tag component (no stored properties) is
|
|
318
|
+
// just the owner column — its row's existence is the whole fact.
|
|
319
|
+
let tableDdl = (v, comp, name = comp, extra = [])=>({
|
|
320
|
+
t: 'create table',
|
|
321
|
+
name,
|
|
322
|
+
ifNot: true,
|
|
323
|
+
cols: [
|
|
324
|
+
{
|
|
325
|
+
name: 'entity',
|
|
326
|
+
type: 'integer',
|
|
327
|
+
pk: true,
|
|
328
|
+
ref: ENTITY
|
|
329
|
+
},
|
|
330
|
+
...stored(v, comp).map(column),
|
|
331
|
+
...extra
|
|
332
|
+
]
|
|
333
|
+
});
|
|
334
|
+
// One declared index, named for what it covers (@yaks/sql `indexName`), so the
|
|
335
|
+
// same declaration always names the same index and a second install is a
|
|
336
|
+
// no-op. A partial one covers only the rows that hold its `present`
|
|
337
|
+
// properties: the rows without them are as many as they like, the rows with
|
|
338
|
+
// them are one.
|
|
339
|
+
let indexDdl = (v, comp, i)=>({
|
|
340
|
+
t: 'create index',
|
|
341
|
+
name: indexName(v, comp, i.props),
|
|
342
|
+
on: comp,
|
|
343
|
+
cols: i.props.map((p)=>col(field(p))),
|
|
344
|
+
unique: i.unique,
|
|
345
|
+
ifNot: true,
|
|
346
|
+
where: i.present ? and(...i.present.map((p)=>notNull(col(field(p))))) : undefined
|
|
347
|
+
});
|
|
348
|
+
/** The `doc` view: each property read as text — through its registered `text`
|
|
349
|
+
* expression where the stored value is not the text itself (@yaks/blob keeps
|
|
350
|
+
* an address) — plus a `rowid` alias. Search indexes are composed separately
|
|
351
|
+
* by the application using @yaks/fts. */ export let docDdl = (v, derived)=>{
|
|
352
|
+
if (!v.all.includes('doc')) return [];
|
|
353
|
+
let name = `${v.stored('doc')}_value`;
|
|
354
|
+
let read = (prop)=>derived[`doc.${prop}`]?.text?.(col(field(prop))) ?? col(field(prop));
|
|
355
|
+
let props = stored(v, 'doc').map((c)=>c.prop);
|
|
356
|
+
// The view names its columns rather than selecting `*`, because `*` cannot
|
|
357
|
+
// replace one with the expression that resolves it. `*` did have one virtue —
|
|
358
|
+
// it followed a table that gained columns — so the view is dropped and
|
|
359
|
+
// recreated whenever it says something else ({@link retabled}): it holds no
|
|
360
|
+
// rows, so recreating it costs nothing, and a view that lags its table is a
|
|
361
|
+
// read that fails at the engine.
|
|
362
|
+
return [
|
|
363
|
+
{
|
|
364
|
+
t: 'drop',
|
|
365
|
+
kind: 'view',
|
|
366
|
+
name,
|
|
367
|
+
ifExists: true
|
|
368
|
+
},
|
|
369
|
+
{
|
|
370
|
+
t: 'create view',
|
|
371
|
+
name,
|
|
372
|
+
ifNot: true,
|
|
373
|
+
q: select({
|
|
374
|
+
cols: [
|
|
375
|
+
col('entity'),
|
|
376
|
+
...props.map((p)=>as(read(p), v.stored('doc', p))),
|
|
377
|
+
as(col('entity'), 'rowid')
|
|
378
|
+
],
|
|
379
|
+
from: table('doc')
|
|
380
|
+
})
|
|
381
|
+
}
|
|
382
|
+
];
|
|
383
|
+
};
|
|
384
|
+
// The whole schema as an ordered list of statements: the spine, then one table
|
|
385
|
+
// per component (the `entity` spine component is the identity table above, not
|
|
386
|
+
// a component table), the doc view, and the indexes those tables declare.
|
|
387
|
+
// `install()` in ./mod.ts runs them; a caller may also read them to inspect or
|
|
388
|
+
// migrate by hand. `derived` is the store's read overrides: a property whose
|
|
389
|
+
// stored value is not its text reads through its `text` expression.
|
|
390
|
+
export let schema = (vocab, derived = {}, file = false)=>[
|
|
391
|
+
...tabled(vocab, derived, file),
|
|
392
|
+
// After every table: an index names a column the create above just raised.
|
|
393
|
+
...indexed(vocab)
|
|
394
|
+
];
|
|
395
|
+
// The spine and one table per component, with the doc view. Everything an
|
|
396
|
+
// index may need to already exist.
|
|
397
|
+
export let tabled = (vocab, derived = {}, file = false)=>[
|
|
398
|
+
...spine(vocab),
|
|
399
|
+
...clocks(vocab, file).flatMap(versioned),
|
|
400
|
+
...told(vocab, file),
|
|
401
|
+
...docDdl(vocab, derived)
|
|
402
|
+
];
|
|
403
|
+
// The tables a file keeps a token for (./versions.ts): archetype, which every
|
|
404
|
+
// connection's catalog follows (./catalog.ts). A single-owner store sees its
|
|
405
|
+
// own writes and keeps none.
|
|
406
|
+
let clocks = (_vocab, file)=>file ? [
|
|
407
|
+
'archetype'
|
|
408
|
+
] : [];
|
|
409
|
+
// Which entity each write named, for a file's other connections to let go of
|
|
410
|
+
// just those (./written.ts). A single-owner store keeps no log either.
|
|
411
|
+
let told = (vocab, file)=>file ? writtenDdl(tables(vocab)) : [];
|
|
412
|
+
let spine = (vocab)=>[
|
|
413
|
+
...SPINE,
|
|
414
|
+
...tables(vocab).map((name)=>tableDdl(vocab, name)),
|
|
415
|
+
...pointed(vocab)
|
|
416
|
+
];
|
|
417
|
+
// The archetype descriptors and their retirements (@yaks/archetype), which
|
|
418
|
+
// every file keeps whether or not its vocabulary declares them: each entity's
|
|
419
|
+
// pointer says which tables hold it, and every whole read and removal goes by
|
|
420
|
+
// it (./archetype.ts). A vocabulary that declares them makes their tables with
|
|
421
|
+
// its own; for one that does not they are made here, and stay the store's own
|
|
422
|
+
// bookkeeping, which its reads never show.
|
|
423
|
+
let POINTED = loadVocab([
|
|
424
|
+
archetypeDoc
|
|
425
|
+
]);
|
|
426
|
+
let pointedIndex = (vocab)=>indexDdl(vocab, 'entity', {
|
|
427
|
+
props: vocab.prop('entity', 'num') ? [
|
|
428
|
+
'archetype',
|
|
429
|
+
'num'
|
|
430
|
+
] : [
|
|
431
|
+
'archetype'
|
|
432
|
+
],
|
|
433
|
+
unique: false
|
|
434
|
+
});
|
|
435
|
+
export let pointerIndex = pointedIndex(POINTED);
|
|
436
|
+
let pointed = (vocab)=>tables(POINTED).filter((name)=>!vocab.comp(name)).map((name)=>tableDdl(POINTED, name));
|
|
437
|
+
// Whether the file's view already says what `make` says. SQLite keeps a
|
|
438
|
+
// view's statement from its name on, behind a `CREATE VIEW` of its own.
|
|
439
|
+
let stands = (driver, make)=>{
|
|
440
|
+
let [row] = objects(driver, {
|
|
441
|
+
type: 'view',
|
|
442
|
+
name: make.name
|
|
443
|
+
});
|
|
444
|
+
let body = (sql)=>sql.replace(/^create view /i, '');
|
|
445
|
+
return !!row && body(String(row.sql)) == body(text({
|
|
446
|
+
...make,
|
|
447
|
+
ifNot: false
|
|
448
|
+
}, driver.stored?.v));
|
|
449
|
+
};
|
|
450
|
+
// What `retabled` answers by vocabulary and read overrides: the doc view, and
|
|
451
|
+
// each list it made for a file whose clocks stand as they should, by whether
|
|
452
|
+
// the file is one and its view stands. The same list each time, so what rests
|
|
453
|
+
// on what in it (./raise.ts `rests`) is worked out once, as for `indexed`.
|
|
454
|
+
let retables = new WeakMap();
|
|
455
|
+
/** {@link tabled} for a file that may already hold them: the doc view is
|
|
456
|
+
* dropped and made again only where the file's says something else. Making an
|
|
457
|
+
* identical view again still changes the schema, and every other connection
|
|
458
|
+
* to the file reads a changed schema as another install to answer. */ export let retabled = (driver, vocab, derived = {})=>{
|
|
459
|
+
let by = retables.get(vocab) ?? new WeakMap();
|
|
460
|
+
retables.set(vocab, by);
|
|
461
|
+
let k = by.get(derived);
|
|
462
|
+
if (!k) {
|
|
463
|
+
by.set(derived, k = {
|
|
464
|
+
view: docDdl(vocab, derived),
|
|
465
|
+
lists: new Map()
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
let file = !!driver.file;
|
|
469
|
+
let make = k.view.find((s)=>s.t == 'create view');
|
|
470
|
+
let shown = !!make && stands(driver, make);
|
|
471
|
+
let clock = clocked(driver, clocks(vocab, file));
|
|
472
|
+
let key = `${file} ${shown}`;
|
|
473
|
+
let held = clock.length ? undefined : k.lists.get(key);
|
|
474
|
+
if (held) return held;
|
|
475
|
+
let made = [
|
|
476
|
+
...spine(vocab),
|
|
477
|
+
...clock,
|
|
478
|
+
...told(vocab, file),
|
|
479
|
+
...shown ? [] : k.view
|
|
480
|
+
];
|
|
481
|
+
if (!clock.length) k.lists.set(key, made);
|
|
482
|
+
return made;
|
|
483
|
+
};
|
|
484
|
+
// Declared and automatic reference indexes. Created last, after `grown()`: an
|
|
485
|
+
// index may name a column its table only gained on this boot, and SQLite
|
|
486
|
+
// rejects one over a column that is not there yet. Kept per vocabulary, the
|
|
487
|
+
// way the statements resting on them are (./raise.ts `rests`): every store of
|
|
488
|
+
// a vocabulary asks for the same list as it opens.
|
|
489
|
+
let indexes = new WeakMap();
|
|
490
|
+
export let indexed = (vocab, storage = false)=>{
|
|
491
|
+
let held = indexes.get(vocab);
|
|
492
|
+
if (!held) indexes.set(vocab, held = indexing(vocab));
|
|
493
|
+
return storage ? [
|
|
494
|
+
...SPINED_INDEXES,
|
|
495
|
+
...vocab.comp('archetype') ? [] : [
|
|
496
|
+
pointedIndex(vocab)
|
|
497
|
+
],
|
|
498
|
+
...held
|
|
499
|
+
] : held;
|
|
500
|
+
};
|
|
501
|
+
// One entity to a number in each series, and the number's own lookup: a
|
|
502
|
+
// number is read without its letter (@yaks/id `ids`). A storage install
|
|
503
|
+
// makes it after `grown()`, which gives a standing spine its prefix; a bare
|
|
504
|
+
// schema may stand over a spine that has none.
|
|
505
|
+
let SERIES = {
|
|
506
|
+
t: 'create index',
|
|
507
|
+
name: 'entity_num_prefix',
|
|
508
|
+
on: 'entity',
|
|
509
|
+
cols: [
|
|
510
|
+
col('num'),
|
|
511
|
+
col('prefix')
|
|
512
|
+
],
|
|
513
|
+
unique: true,
|
|
514
|
+
ifNot: true
|
|
515
|
+
};
|
|
516
|
+
// The default order, newest number first and then the owner (@yaks/sql
|
|
517
|
+
// `bind`), read off an index in that order: the series index puts the
|
|
518
|
+
// letter before the owner, so a page of `.limit=1` sorted the whole spine,
|
|
519
|
+
// 6.5 million rows on the box, to give one. An index on the number alone
|
|
520
|
+
// ends in the owner, as every index does.
|
|
521
|
+
let NUMBERED = {
|
|
522
|
+
t: 'create index',
|
|
523
|
+
name: 'entity_num',
|
|
524
|
+
on: 'entity',
|
|
525
|
+
cols: [
|
|
526
|
+
col('num')
|
|
527
|
+
],
|
|
528
|
+
ifNot: true
|
|
529
|
+
};
|
|
530
|
+
let SPINED_INDEXES = [
|
|
531
|
+
SERIES,
|
|
532
|
+
NUMBERED
|
|
533
|
+
];
|
|
534
|
+
/** Whether `index` is one of the number's indexes over a spine that keeps
|
|
535
|
+
* `num` unique on its own (./physical.ts `sole`). That spine's own index
|
|
536
|
+
* already holds one entity to a number, so one to each pair, finds a number
|
|
537
|
+
* without its letter and reads the default order; building either over it
|
|
538
|
+
* would only write a row per
|
|
539
|
+
* entity, in one statement past what an object may write in a minute once a
|
|
540
|
+
* store holds 100,000. A spine rebuilt without its own index needs them. */ export let needless = (driver, index)=>SPINED_INDEXES.some((i)=>i.name == index.name && i.on == index.on) && sole(driver);
|
|
541
|
+
/** The storage indexes an install builds over a file: every one of
|
|
542
|
+
* {@link indexed} but a {@link needless} one. An index owed before it became
|
|
543
|
+
* needless is forgotten where it is worked off (./owe.ts, ./maintenance.ts),
|
|
544
|
+
* since an install whose schema stands as it was never looks again. */ export let built = (driver, vocab)=>indexed(vocab, true).filter((i)=>!needless(driver, i));
|
|
545
|
+
let indexing = (vocab)=>[
|
|
546
|
+
// Bare schema adapters can still hold the legacy spine. A storage install
|
|
547
|
+
// asks for its internal pointer index after adding the column.
|
|
548
|
+
...vocab.comp('archetype') ? [
|
|
549
|
+
pointedIndex(vocab)
|
|
550
|
+
] : [],
|
|
551
|
+
...tables(vocab).flatMap((name)=>vocab.indexes(name).map((i)=>indexDdl(vocab, name, i)))
|
|
552
|
+
];
|
|
553
|
+
// A vocabulary index has the name of its table and indexed columns, joined by
|
|
554
|
+
// underscores or dots (@yaks/sql `indexName`). Inspect the engine's column list
|
|
555
|
+
// too: another package's index on a component table is not ours to retire
|
|
556
|
+
// merely because its name starts with that table's name.
|
|
557
|
+
let managed = (driver, v, table, name)=>{
|
|
558
|
+
let cols = driver.query({
|
|
559
|
+
t: 'pragma',
|
|
560
|
+
name: 'index_info',
|
|
561
|
+
arg: name
|
|
562
|
+
}).toSorted((a, b)=>Number(a.seqno) - Number(b.seqno)).map((r)=>r.name);
|
|
563
|
+
if (!cols.length || !cols.every((c)=>typeof c == 'string')) return false;
|
|
564
|
+
let names = [
|
|
565
|
+
table,
|
|
566
|
+
...cols
|
|
567
|
+
];
|
|
568
|
+
let kept = [
|
|
569
|
+
sqlStored(v, table),
|
|
570
|
+
...cols.map((c)=>sqlStored(v, table, c))
|
|
571
|
+
];
|
|
572
|
+
return [
|
|
573
|
+
'_',
|
|
574
|
+
'.'
|
|
575
|
+
].some((by)=>name == names.join(by) || name == kept.join(by));
|
|
576
|
+
};
|
|
577
|
+
let predicate = (sql)=>(sql.match(/\bwhere\b([\s\S]*)$/i)?.[1] ?? '').toLowerCase().replace(/\s+/g, ' ').trim();
|
|
578
|
+
let fitsIndex = (held, sql, now, v)=>!!held && Number(held.unique) == Number(!!now.unique) && Number(held.partial) == Number(!!now.where) && (!now.where || predicate(sql) == predicate(text(now, v)));
|
|
579
|
+
// The SQL SQLite keeps for an index made by `create`: its statement as it
|
|
580
|
+
// renders, but for `if not exists`, which the engine leaves out, and its
|
|
581
|
+
// leading keywords, which the engine keeps in capitals.
|
|
582
|
+
let made = (create, v)=>text({
|
|
583
|
+
...create,
|
|
584
|
+
ifNot: false
|
|
585
|
+
}, v).replace(/^create (unique )?index/, (k)=>k.toUpperCase());
|
|
586
|
+
/** Retire vocabulary indexes whose declaration disappeared or changed. An
|
|
587
|
+
* index whose kept SQL is the one its declaration makes is as declared, and
|
|
588
|
+
* the engine is asked nothing about it. */ export let retired = (driver, vocab)=>{
|
|
589
|
+
let wanted = new Map(indexed(vocab, true).map((i)=>[
|
|
590
|
+
i.name,
|
|
591
|
+
i
|
|
592
|
+
]));
|
|
593
|
+
let listed = new Map();
|
|
594
|
+
return objects(driver, {
|
|
595
|
+
type: 'index'
|
|
596
|
+
}).flatMap((row)=>{
|
|
597
|
+
let table = String(row.tbl_name), name = String(row.name);
|
|
598
|
+
if (!(table == 'entity' || vocab.comp(table))) return [];
|
|
599
|
+
let now = wanted.get(name);
|
|
600
|
+
if (now?.on == table && row.sql == made(now, vocab)) return [];
|
|
601
|
+
if (!managed(driver, vocab, table, name)) return [];
|
|
602
|
+
if (now?.on == table) {
|
|
603
|
+
let held = listed.get(table);
|
|
604
|
+
if (!held) {
|
|
605
|
+
held = new Map(driver.query({
|
|
606
|
+
t: 'pragma',
|
|
607
|
+
name: 'index_list',
|
|
608
|
+
arg: table
|
|
609
|
+
}).map((r)=>[
|
|
610
|
+
String(r.name),
|
|
611
|
+
r
|
|
612
|
+
]));
|
|
613
|
+
listed.set(table, held);
|
|
614
|
+
}
|
|
615
|
+
if (fitsIndex(held.get(name), String(row.sql), now, vocab)) return [];
|
|
616
|
+
}
|
|
617
|
+
return [
|
|
618
|
+
{
|
|
619
|
+
t: 'drop',
|
|
620
|
+
kind: 'index',
|
|
621
|
+
name
|
|
622
|
+
}
|
|
623
|
+
];
|
|
624
|
+
});
|
|
625
|
+
};
|
|
626
|
+
/**
|
|
627
|
+
* Which revision of fitting ({@link grown}, {@link refit}) brings a standing
|
|
628
|
+
* file to its vocabulary. What fitting changes it reads off the file, not off
|
|
629
|
+
* the vocabulary, so a fingerprint of the statements alone calls a file
|
|
630
|
+
* current that an older fitting left behind. This is part of every install's
|
|
631
|
+
* fingerprint instead, and moving it fits every store once more: move it when
|
|
632
|
+
* fitting learns to see something it did not.
|
|
633
|
+
*/ export let FIT = 10;
|
|
634
|
+
/** Whether fitting asks a file about the table `name`. */ export let fitting = (vocab)=>(name)=>name == 'entity' || tables(vocab).includes(name);
|
|
635
|
+
/** The {@link Standing} a file holds now, read through a driver that answers
|
|
636
|
+
* at once. */ export let standing = (driver, vocab)=>stood(driver, fitting(vocab));
|
|
637
|
+
/** Whether any table {@link standing} would hold stands in the file, read
|
|
638
|
+
* off the catalogue without asking each table. */ export let anyStanding = (driver, vocab)=>{
|
|
639
|
+
let pick = fitting(vocab);
|
|
640
|
+
return objects(driver, {
|
|
641
|
+
type: 'table'
|
|
642
|
+
}).some((t)=>pick(t.name));
|
|
643
|
+
};
|
|
644
|
+
// SQLite keeps the CREATE declaration without IF NOT EXISTS. An identical
|
|
645
|
+
// declaration already has every column and constraint fitting would check.
|
|
646
|
+
let declarations = new WeakMap();
|
|
647
|
+
let declaration = (sql)=>sql.replace(/^create table /i, '');
|
|
648
|
+
/** Whether a table SQLite keeps the CREATE text `sql` of stands as `s`
|
|
649
|
+
* declares it, every column and constraint included. */ export let declares = (sql, s, v)=>sql != null && declaration(sql) == declaration(text({
|
|
650
|
+
...s,
|
|
651
|
+
ifNot: false
|
|
652
|
+
}, v));
|
|
653
|
+
let declared = (vocab)=>{
|
|
654
|
+
let held = declarations.get(vocab);
|
|
655
|
+
if (!held) {
|
|
656
|
+
held = new Map(tabled(vocab).filter((s)=>s.t == 'create table').map((s)=>[
|
|
657
|
+
s.name,
|
|
658
|
+
declaration(text({
|
|
659
|
+
...s,
|
|
660
|
+
ifNot: false
|
|
661
|
+
}, vocab))
|
|
662
|
+
]));
|
|
663
|
+
declarations.set(vocab, held);
|
|
664
|
+
}
|
|
665
|
+
return held;
|
|
666
|
+
};
|
|
667
|
+
/** The tables the file declares exactly as the vocabulary does. Adding or
|
|
668
|
+
* dropping a column rewrites the declaration SQLite keeps, so each of these
|
|
669
|
+
* has every column and constraint, and nothing need ask it about them. */ export let exact = (driver, vocab)=>{
|
|
670
|
+
let fresh = declared(vocab);
|
|
671
|
+
return new Set(objects(driver, {
|
|
672
|
+
type: 'table'
|
|
673
|
+
}).filter((t)=>declaration(String(t.sql)) == fresh.get(String(t.name))).map((t)=>String(t.name)));
|
|
674
|
+
};
|
|
675
|
+
/** The {@link Standing} of each table that stood other than as the vocabulary
|
|
676
|
+
* declares it: what fitting, or a reader, must ask the file about. */ export let behind = (driver, vocab, kept = exact(driver, vocab))=>{
|
|
677
|
+
let pick = fitting(vocab);
|
|
678
|
+
return stood(driver, (name)=>pick(name) && !kept.has(name));
|
|
679
|
+
};
|
|
680
|
+
// The component tables that stood.
|
|
681
|
+
let comps = (vocab, was)=>tables(vocab).filter((name)=>name in was);
|
|
682
|
+
// Whether a table that stood already says what its fresh statement says about
|
|
683
|
+
// the three things only a rebuild changes: which columns are keyed to another
|
|
684
|
+
// table, what each column checks, and which refuse a null. A column the table
|
|
685
|
+
// lacks is `grown`'s, and arrives with its check. A column that refuses a null
|
|
686
|
+
// its vocabulary now allows (a property no longer `required`, or no longer
|
|
687
|
+
// named and kept for its values) could never be cleared, so it could never
|
|
688
|
+
// be cleared; a column that admits a null its vocabulary refuses is how
|
|
689
|
+
// `grown` adds one on purpose, and admission holds the writes.
|
|
690
|
+
let fits = (t, fresh, changes, v)=>{
|
|
691
|
+
let keyed = fresh.cols.filter((c)=>c.ref).map((c)=>c.name);
|
|
692
|
+
let checked = checks(text(fresh, v));
|
|
693
|
+
let names = [
|
|
694
|
+
'',
|
|
695
|
+
...t.cols.map((r)=>sqlStored(v, fresh.name, String(r.name)).toLowerCase())
|
|
696
|
+
];
|
|
697
|
+
let loose = new Set(fresh.cols.filter((c)=>!c.notNull).map((c)=>c.name));
|
|
698
|
+
return keyed.length == t.keys.length && keyed.every((c)=>t.keys.includes(c)) && !changes && names.every((n)=>(t.checks[n] ?? '') == (checked[n] ?? '')) && !t.cols.some((r)=>Number(r.notnull) && loose.has(String(r.name)));
|
|
699
|
+
};
|
|
700
|
+
// An eid and its integer reference are two storage forms for one entity.
|
|
701
|
+
// Versions of an app can move in either direction, so resolve through the
|
|
702
|
+
// entity spine whenever its vocabulary changes that relation.
|
|
703
|
+
let referenceFields = (vocab, comp)=>new Set(stored(vocab, comp).filter((p)=>p.category == 'ref').map((p)=>field(p.prop)));
|
|
704
|
+
let converted = (t, fresh, references)=>fresh.cols.flatMap((c)=>{
|
|
705
|
+
let old = t.cols.find((r)=>r.name == c.name);
|
|
706
|
+
let type = String(old?.type).toLowerCase();
|
|
707
|
+
if (references.has(c.name) && c.type == 'integer' && type == 'text') {
|
|
708
|
+
return [
|
|
709
|
+
{
|
|
710
|
+
name: c.name,
|
|
711
|
+
from: 'eid',
|
|
712
|
+
to: 'id'
|
|
713
|
+
}
|
|
714
|
+
];
|
|
715
|
+
}
|
|
716
|
+
if (!c.ref && c.type == 'text' && type == 'integer' && t.keys.includes(c.name)) {
|
|
717
|
+
return [
|
|
718
|
+
{
|
|
719
|
+
name: c.name,
|
|
720
|
+
from: 'id',
|
|
721
|
+
to: 'eid'
|
|
722
|
+
}
|
|
723
|
+
];
|
|
724
|
+
}
|
|
725
|
+
return [];
|
|
726
|
+
});
|
|
727
|
+
/** Values that cannot resolve through the entity spine, one check per
|
|
728
|
+
* converted column, each answering an {@link Orphan} where one stands. A
|
|
729
|
+
* failed conversion must leave its old column untouched rather than turn a
|
|
730
|
+
* missing id into null. */ export let unresolved = (vocab, was)=>Object.fromEntries(comps(vocab, was).flatMap((comp)=>{
|
|
731
|
+
let fresh = tableDdl(vocab, comp);
|
|
732
|
+
let changes = converted(was[comp], fresh, referenceFields(vocab, comp));
|
|
733
|
+
return changes.length ? [
|
|
734
|
+
[
|
|
735
|
+
comp,
|
|
736
|
+
changes.map(({ name, from, to })=>select({
|
|
737
|
+
cols: [
|
|
738
|
+
as(lit(name), 'prop'),
|
|
739
|
+
as(col('eid', '__row'), 'row'),
|
|
740
|
+
as(col(name, comp), 'value')
|
|
741
|
+
],
|
|
742
|
+
from: table(comp),
|
|
743
|
+
joins: [
|
|
744
|
+
left(table('entity', '__ref'), eq(col(from, '__ref'), col(name, comp))),
|
|
745
|
+
left(table('entity', '__row'), eq(col('id', '__row'), col('entity', comp)))
|
|
746
|
+
],
|
|
747
|
+
where: and(notNull(col(name, comp)), isNull(col(to, '__ref'))),
|
|
748
|
+
limit: lit(1)
|
|
749
|
+
}))
|
|
750
|
+
]
|
|
751
|
+
] : [];
|
|
752
|
+
}));
|
|
753
|
+
/// orphaned('outing', { prop: 'day', row: 'o1', value: 'Saturday' }).message.startsWith('outing keeps its old shape: outing.day names an entity now, and o1 holds "Saturday", which names none.') -> true
|
|
754
|
+
/** What a store says of a component whose reference column it could not
|
|
755
|
+
* convert ({@link unresolved}): the table is as it stood, and the refusal
|
|
756
|
+
* names the property, a row and the value, and the ways out. */ export let orphaned = (comp, { prop, row, value })=>new Error(`${comp} keeps its old shape: ${comp}.${prop} names an entity now, and ` + `${row ?? 'a row'} holds ${JSON.stringify(value)}, which names none. ` + `Set ${comp}.${prop} on each such row to the eid of the entity it ` + "means, or clear it, through the app's own commands or a store_load " + 'of bundles naming each row, then deploy again; or keep the old ' + 'value under its own property and declare the reference under a new ' + 'name.');
|
|
757
|
+
/**
|
|
758
|
+
* What {@link grown} cannot fix: a constraint the vocabulary changed its mind
|
|
759
|
+
* about after a table was created. A reference's death word decides whether its
|
|
760
|
+
* column carries a foreign key, an enum is its column's check (`closed`),
|
|
761
|
+
* `required` is its NOT NULL, and SQLite alters none of them in place. So a
|
|
762
|
+
* table whose keys or checks disagree with the vocabulary is rebuilt.
|
|
763
|
+
*
|
|
764
|
+
* Undeclared columns come back, even when empty: another process may have
|
|
765
|
+
* installed a newer vocabulary. Removing a column is an explicit migration.
|
|
766
|
+
* A kept column keeps its type and nothing else.
|
|
767
|
+
*
|
|
768
|
+
* Each table that needs it, by name: none for a file that already fits, which
|
|
769
|
+
* is every boot but the one after the vocabulary changed.
|
|
770
|
+
*/ export let refitting = (vocab, was)=>Object.fromEntries(comps(vocab, was).flatMap((comp)=>{
|
|
771
|
+
let t = was[comp];
|
|
772
|
+
let said = new Set(stored(vocab, comp).map((c)=>field(c.prop)));
|
|
773
|
+
let extra = t.cols.filter((r)=>r.name != 'entity' && !said.has(String(r.name))).map((r)=>({
|
|
774
|
+
name: String(r.name),
|
|
775
|
+
type: String(r.type ?? '') || undefined
|
|
776
|
+
}));
|
|
777
|
+
let fresh = tableDdl(vocab, comp, comp, extra);
|
|
778
|
+
let refs = converted(t, fresh, referenceFields(vocab, comp));
|
|
779
|
+
if (fits(t, fresh, refs.length, vocab)) return [];
|
|
780
|
+
let old = t.cols.map((r)=>String(r.name));
|
|
781
|
+
let cols = fresh.cols.map((r)=>r.name).filter((n)=>old.includes(n));
|
|
782
|
+
let changed = Object.fromEntries(refs.map(({ name, from, to })=>[
|
|
783
|
+
name,
|
|
784
|
+
{
|
|
785
|
+
from,
|
|
786
|
+
to
|
|
787
|
+
}
|
|
788
|
+
]));
|
|
789
|
+
return [
|
|
790
|
+
[
|
|
791
|
+
comp,
|
|
792
|
+
{
|
|
793
|
+
fresh,
|
|
794
|
+
old,
|
|
795
|
+
cols,
|
|
796
|
+
changed
|
|
797
|
+
}
|
|
798
|
+
]
|
|
799
|
+
];
|
|
800
|
+
}));
|
|
801
|
+
/** The value `r` carries over for column `c`, read off `row`: as stored, or
|
|
802
|
+
* through the entity spine where its stored form changes. */ export let carried = (r, c, row, name = c)=>{
|
|
803
|
+
let to = r.changed[c];
|
|
804
|
+
return to ? sub(select({
|
|
805
|
+
cols: [
|
|
806
|
+
col(to.to)
|
|
807
|
+
],
|
|
808
|
+
from: table('entity'),
|
|
809
|
+
where: eq(col(to.from), col(name, row))
|
|
810
|
+
})) : col(name, row);
|
|
811
|
+
};
|
|
812
|
+
/**
|
|
813
|
+
* The statements rebuilding each table {@link refitting} names, in one unit:
|
|
814
|
+
* its rows set aside as they are, the table made again as the vocabulary
|
|
815
|
+
* says, and the rows brought back. It is made under its own name rather than
|
|
816
|
+
* renamed into it, because a rename checks every view and trigger that names
|
|
817
|
+
* the table while it is gone (`doc_value` names `doc`). The table's triggers
|
|
818
|
+
* and undeclared indexes go with it, for whoever raised them to raise again at
|
|
819
|
+
* boot (@yaks/fts `adopt`); the declared indexes are {@link indexed}'s, which
|
|
820
|
+
* runs after. A table too big to rebuild in one unit is owed instead, and
|
|
821
|
+
* rebuilt beside itself in windows (./owe.ts).
|
|
822
|
+
*/ export let refit = (vocab, was)=>Object.fromEntries(Object.entries(refitting(vocab, was)).map(([comp, r])=>{
|
|
823
|
+
let aside = `${sqlStored(vocab, comp)}__refit`;
|
|
824
|
+
let field = (p)=>sqlStored(vocab, comp, p);
|
|
825
|
+
return [
|
|
826
|
+
comp,
|
|
827
|
+
[
|
|
828
|
+
// A column of no type holds each value exactly as it was stored.
|
|
829
|
+
{
|
|
830
|
+
t: 'create table',
|
|
831
|
+
name: aside,
|
|
832
|
+
cols: r.old.map((c)=>({
|
|
833
|
+
name: field(c)
|
|
834
|
+
}))
|
|
835
|
+
},
|
|
836
|
+
{
|
|
837
|
+
t: 'insert',
|
|
838
|
+
into: aside,
|
|
839
|
+
cols: r.old.map(field),
|
|
840
|
+
q: select({
|
|
841
|
+
cols: r.old.map((c)=>col(field(c))),
|
|
842
|
+
from: {
|
|
843
|
+
t: 'table',
|
|
844
|
+
name: sqlStored(vocab, comp),
|
|
845
|
+
physical: true
|
|
846
|
+
}
|
|
847
|
+
})
|
|
848
|
+
},
|
|
849
|
+
{
|
|
850
|
+
t: 'drop',
|
|
851
|
+
kind: 'table',
|
|
852
|
+
name: comp
|
|
853
|
+
},
|
|
854
|
+
r.fresh,
|
|
855
|
+
{
|
|
856
|
+
t: 'insert',
|
|
857
|
+
into: comp,
|
|
858
|
+
cols: r.cols,
|
|
859
|
+
q: select({
|
|
860
|
+
cols: r.cols.map((c)=>carried(r, c, aside, field(c))),
|
|
861
|
+
from: table(aside)
|
|
862
|
+
})
|
|
863
|
+
},
|
|
864
|
+
{
|
|
865
|
+
t: 'drop',
|
|
866
|
+
kind: 'table',
|
|
867
|
+
name: aside
|
|
868
|
+
}
|
|
869
|
+
]
|
|
870
|
+
];
|
|
871
|
+
}));
|
|
872
|
+
// What `schema()` alone cannot do: add the columns a component gained after its
|
|
873
|
+
// table was already created. `create table if not exists` does nothing to a
|
|
874
|
+
// table that exists, so a vocabulary that gained a property leaves the table at
|
|
875
|
+
// the shape it was first created with, and every read naming the new column
|
|
876
|
+
// fails at the engine ("no such column"). SQLite has no `add column if not
|
|
877
|
+
// exists`, so the standing shape is read and only the missing columns are
|
|
878
|
+
// added.
|
|
879
|
+
//
|
|
880
|
+
// Additive only, and deliberately: nothing is dropped and nothing is retyped,
|
|
881
|
+
// because rows are already written under the columns the table has. A column
|
|
882
|
+
// is emitted in the form SQLite accepts in an `add column` (grownColumn above).
|
|
883
|
+
export let grown = (vocab, was)=>[
|
|
884
|
+
...[
|
|
885
|
+
{
|
|
886
|
+
name: 'archetype',
|
|
887
|
+
type: 'integer',
|
|
888
|
+
ref: ENTITY
|
|
889
|
+
},
|
|
890
|
+
{
|
|
891
|
+
name: 'prefix',
|
|
892
|
+
type: 'text'
|
|
893
|
+
}
|
|
894
|
+
].filter((c)=>was.entity && !was.entity.cols.some((r)=>r.name == c.name)).map((add)=>({
|
|
895
|
+
t: 'alter table',
|
|
896
|
+
table: 'entity',
|
|
897
|
+
add
|
|
898
|
+
})),
|
|
899
|
+
...comps(vocab, was).flatMap((comp)=>{
|
|
900
|
+
let has = new Set(was[comp].cols.map((r)=>String(r.name)));
|
|
901
|
+
return stored(vocab, comp).filter((c)=>!has.has(field(c.prop))).map((c)=>({
|
|
902
|
+
t: 'alter table',
|
|
903
|
+
table: comp,
|
|
904
|
+
add: grownColumn(c)
|
|
905
|
+
}));
|
|
906
|
+
})
|
|
907
|
+
];
|
|
908
|
+
// The spine as it is declared, and what is raised on it.
|
|
909
|
+
let SPINED = SPINE.find((s)=>s.t == 'create table' && s.name == 'entity');
|
|
910
|
+
let ON_SPINE = SPINE.filter((s)=>s.t == 'create trigger' && s.on == 'entity');
|
|
911
|
+
// Every trigger this package raises on the spine, by name: its own counts', the
|
|
912
|
+
// archetype counts' (./population.ts) and the write log's (./written.ts).
|
|
913
|
+
let SPUN = new Map([
|
|
914
|
+
...ON_SPINE,
|
|
915
|
+
...tallying,
|
|
916
|
+
...telling('entity')
|
|
917
|
+
].map((s)=>[
|
|
918
|
+
s.name,
|
|
919
|
+
s
|
|
920
|
+
]));
|
|
921
|
+
// The triggers to raise again on a spine made anew: its own, and each other
|
|
922
|
+
// that stood on it. One this package does not make would be lost, so it is
|
|
923
|
+
// refused before anything moves.
|
|
924
|
+
let spun = (driver)=>{
|
|
925
|
+
let stood = objects(driver, {
|
|
926
|
+
tbl_name: 'entity',
|
|
927
|
+
type: 'trigger'
|
|
928
|
+
}).map((o)=>o.name);
|
|
929
|
+
let alien = stood.filter((name)=>!SPUN.has(name));
|
|
930
|
+
if (alien.length) {
|
|
931
|
+
throw new Error(`the spine holds triggers this package does not make: ${alien.join(', ')}`);
|
|
932
|
+
}
|
|
933
|
+
let names = new Set(stood);
|
|
934
|
+
return [
|
|
935
|
+
...ON_SPINE,
|
|
936
|
+
...[
|
|
937
|
+
...SPUN.values()
|
|
938
|
+
].filter((s)=>!ON_SPINE.includes(s) && names.has(s.name))
|
|
939
|
+
];
|
|
940
|
+
};
|
|
941
|
+
/** The column a spine's number moves out of when it stops being unique on its
|
|
942
|
+
* own ({@link respined}): it keeps that old constraint, and no value. */ export let RETIRED_NUM = 'retired_num';
|
|
943
|
+
/**
|
|
944
|
+
* The spine moved off a number unique on its own (./physical.ts `sole`), as
|
|
945
|
+
* every spine made before series had letters keeps it: there T-5 and M-5
|
|
946
|
+
* cannot both stand, so a store that numbers by series moves it as it
|
|
947
|
+
* installs. SQLite drops a column's `unique` only with its table, and
|
|
948
|
+
* dropping the spine with foreign keys on, as a Durable Object keeps them,
|
|
949
|
+
* deletes each row and checks every table naming it, and putting the rows
|
|
950
|
+
* back checks each again: a store's entities times the hundreds of
|
|
951
|
+
* references to them. So no row moves. The column holding the old constraint
|
|
952
|
+
* is renamed {@link RETIRED_NUM} and emptied, and a new `num` takes its
|
|
953
|
+
* numbers; an update of columns no reference names checks none. The spine's
|
|
954
|
+
* indexes and triggers name its number, so they are dropped first and its
|
|
955
|
+
* triggers raised again after. Its indexes are the install's to raise.
|
|
956
|
+
*/ export let respined = (driver)=>{
|
|
957
|
+
if (!sole(driver)) return [];
|
|
958
|
+
let raised = spun(driver);
|
|
959
|
+
let on = objects(driver, {
|
|
960
|
+
tbl_name: 'entity'
|
|
961
|
+
}).filter((o)=>o.sql && (o.type == 'index' || o.type == 'trigger'));
|
|
962
|
+
return [
|
|
963
|
+
...on.map((o)=>({
|
|
964
|
+
t: 'drop',
|
|
965
|
+
kind: o.type,
|
|
966
|
+
name: o.name
|
|
967
|
+
})),
|
|
968
|
+
{
|
|
969
|
+
t: 'alter table',
|
|
970
|
+
table: 'entity',
|
|
971
|
+
rename: {
|
|
972
|
+
column: 'num',
|
|
973
|
+
to: RETIRED_NUM
|
|
974
|
+
}
|
|
975
|
+
},
|
|
976
|
+
{
|
|
977
|
+
t: 'alter table',
|
|
978
|
+
table: 'entity',
|
|
979
|
+
add: SPINED.cols.find((c)=>c.name == 'num')
|
|
980
|
+
},
|
|
981
|
+
{
|
|
982
|
+
t: 'update',
|
|
983
|
+
table: 'entity',
|
|
984
|
+
set: {
|
|
985
|
+
num: col(RETIRED_NUM),
|
|
986
|
+
[RETIRED_NUM]: lit(null)
|
|
987
|
+
},
|
|
988
|
+
// The numbered rows only, through the retired column's own index: the
|
|
989
|
+
// rest hold none to move, and on the box they are 97% of six million.
|
|
990
|
+
where: notNull(col(RETIRED_NUM))
|
|
991
|
+
},
|
|
992
|
+
...raised
|
|
993
|
+
];
|
|
994
|
+
};
|
|
995
|
+
/** The spine rebuilt where it keeps a number unique on its own
|
|
996
|
+
* ({@link respined}), in a unit of its own: one the engine refused is left as
|
|
997
|
+
* it stood, and returned with the engine's reason. */ export let respine = (driver)=>{
|
|
998
|
+
try {
|
|
999
|
+
let stmts = respined(driver);
|
|
1000
|
+
if (!stmts.length) return [];
|
|
1001
|
+
unit(driver, ()=>stmts.forEach((s)=>driver.query(s)));
|
|
1002
|
+
return [];
|
|
1003
|
+
} catch (e) {
|
|
1004
|
+
return [
|
|
1005
|
+
unfit('entity', e)
|
|
1006
|
+
];
|
|
1007
|
+
}
|
|
1008
|
+
};
|
|
1009
|
+
/**
|
|
1010
|
+
* Bring the tables that stood to the vocabulary, through a driver that answers
|
|
1011
|
+
* at once: the columns they lack ({@link grown}), then a rebuild of each whose
|
|
1012
|
+
* constraints moved ({@link refit}), in one unit. A table whose rows do not fit
|
|
1013
|
+
* the shape the vocabulary now says (a value its enum no longer lists) is left
|
|
1014
|
+
* exactly as it stood, and returned with the engine's reason: those rows need a
|
|
1015
|
+
* migration that prepares them. Until one runs, the old constraint admits them,
|
|
1016
|
+
* and admission holds every new write to the vocabulary. A table `owe` takes
|
|
1017
|
+
* on is left for it to rebuild later.
|
|
1018
|
+
*/ export let fit = (driver, vocab, owe = ()=>false)=>unit(driver, ()=>{
|
|
1019
|
+
let was = behind(driver, vocab);
|
|
1020
|
+
for (let stmt of grown(vocab, was))driver.query(stmt);
|
|
1021
|
+
let missing = Object.fromEntries(Object.entries(unresolved(vocab, was)).map(([comp, checks])=>[
|
|
1022
|
+
comp,
|
|
1023
|
+
checks.map((q)=>driver.query(q)[0]).find(Boolean)
|
|
1024
|
+
]));
|
|
1025
|
+
let plans = refitting(vocab, was);
|
|
1026
|
+
return Object.entries(refit(vocab, was)).flatMap(([comp, stmts])=>{
|
|
1027
|
+
let orphan = missing[comp];
|
|
1028
|
+
if (orphan) return [
|
|
1029
|
+
orphaned(comp, orphan)
|
|
1030
|
+
];
|
|
1031
|
+
if (owe(comp, plans[comp])) return [];
|
|
1032
|
+
try {
|
|
1033
|
+
unit(driver, ()=>stmts.forEach((s)=>driver.query(s)));
|
|
1034
|
+
return [];
|
|
1035
|
+
} catch (e) {
|
|
1036
|
+
return [
|
|
1037
|
+
unfit(comp, e)
|
|
1038
|
+
];
|
|
1039
|
+
}
|
|
1040
|
+
});
|
|
1041
|
+
});
|
|
1042
|
+
/** Where a store tells what it outlived when its caller names nowhere else:
|
|
1043
|
+
* one line on the console. It is the state of the data, not a defect in the
|
|
1044
|
+
* code, so a stack says nothing, and it repeats on every open until fixed. */ export let logged = (e)=>console.error(`@yaks/sqlite: ${e.message}`);
|
|
1045
|
+
/** What is reported of a table whose rebuild ({@link refit}) the engine
|
|
1046
|
+
* refused, `e` being its refusal: the table is as it stood. */ export let unfit = (comp, e)=>new Error(`${comp} keeps its old shape: its rows need a migration that prepares ` + `them for the vocabulary's (${e instanceof Error ? e.message : e})`, {
|
|
1047
|
+
cause: e
|
|
1048
|
+
});
|
|
1049
|
+
/**
|
|
1050
|
+
* How many rows of each index analyze samples. Bounded, because the numbers the
|
|
1051
|
+
* planner needs are orders of magnitude — `call` holds fifty thousand rows and
|
|
1052
|
+
* `entity` a million — and a sample of four hundred says that as well as a
|
|
1053
|
+
* whole scan does. On a 1 GB graph the bounded pass costs ~110 ms where the
|
|
1054
|
+
* unbounded one costs 5.4 s. The sample does not bound the count: `ANALYZE`
|
|
1055
|
+
* still reads every page of an index, or of a table with none, to count its
|
|
1056
|
+
* rows, so a table with no index is counted in windows instead
|
|
1057
|
+
* ({@link counted}).
|
|
1058
|
+
*/ export let SAMPLE = 400;
|
|
1059
|
+
/**
|
|
1060
|
+
* Keep the statistics the query planner reads this schema with.
|
|
1061
|
+
*
|
|
1062
|
+
* Every component table is keyed `entity integer primary key` and carries no
|
|
1063
|
+
* secondary index, so without `sqlite_stat1` SQLite has nothing to size one by
|
|
1064
|
+
* and falls back to its built-in guess of about a million rows for all of them.
|
|
1065
|
+
* A query for "the entities that carry `call`" is then planned as a walk of
|
|
1066
|
+
* the whole spine probing `call` per row, instead of a scan of the fifty
|
|
1067
|
+
* thousand `call` rows — which is how opening an imported graph came to read
|
|
1068
|
+
* the archive end to end six times before answering (T-37734).
|
|
1069
|
+
*
|
|
1070
|
+
* Installation analyzes nothing: it answers the receipt of which tables are
|
|
1071
|
+
* owed an analysis ({@link owing}), and {@link analyzing} works them off a
|
|
1072
|
+
* table at a time, away from the install that owed them (./owe.ts `work` on a
|
|
1073
|
+
* file, a Durable Object's alarm), since one `ANALYZE` holds the write lock
|
|
1074
|
+
* while it reads its table. A file's analysis is sampled ({@link SAMPLE}),
|
|
1075
|
+
* and a table of its with no index is counted a window at a time in a
|
|
1076
|
+
* snapshot, holding no lock ({@link counted});
|
|
1077
|
+
* a full-analysis engine (a Durable Object's, which refuses `analysis_limit`)
|
|
1078
|
+
* provides its stored bytes without scanning rows. An unchanged store below
|
|
1079
|
+
* tenfold byte growth bills no rows for statistics, including after a
|
|
1080
|
+
* connection restart. A table empty at its last analysis that holds rows now
|
|
1081
|
+
* is owed, and so, after a schema change, is a populated table or index
|
|
1082
|
+
* without statistics. Existing complete statistics are adopted once by
|
|
1083
|
+
* installations predating receipts. A table holding at most one row is never
|
|
1084
|
+
* analyzed: it is remembered as empty and checked with a count of two rows at
|
|
1085
|
+
* most. Each whose statistics say it holds fewer than {@link SMALL} rows is
|
|
1086
|
+
* checked for twice as many ({@link small}).
|
|
1087
|
+
*
|
|
1088
|
+
* Optimize decides none of it: empty tables get no stat1 row, so it names
|
|
1089
|
+
* them on every run, and it names as often a table whose row count it guesses
|
|
1090
|
+
* wrong from one page, such as one of variable-sized rows, which `ANALYZE`
|
|
1091
|
+
* then counts end to end under the write lock. Only a database in memory,
|
|
1092
|
+
* which nobody else writes, still optimizes at once.
|
|
1093
|
+
*/ export let analyzed = (driver, previous, unchanged = false)=>{
|
|
1094
|
+
if (!driver.statistics) return;
|
|
1095
|
+
if (typeof driver.statistics == 'object') {
|
|
1096
|
+
return owing(driver, driver.statistics.bytes(), previous, unchanged);
|
|
1097
|
+
}
|
|
1098
|
+
if (driver.file) return owing(driver, size(driver), previous, unchanged);
|
|
1099
|
+
sample(driver);
|
|
1100
|
+
driver.query({
|
|
1101
|
+
t: 'pragma',
|
|
1102
|
+
name: 'optimize',
|
|
1103
|
+
value: 0x10002
|
|
1104
|
+
});
|
|
1105
|
+
};
|
|
1106
|
+
// The bytes a file stores, as its pages say, reading no rows.
|
|
1107
|
+
let size = (driver)=>{
|
|
1108
|
+
let first = (name)=>Number(Object.values(driver.query({
|
|
1109
|
+
t: 'pragma',
|
|
1110
|
+
name
|
|
1111
|
+
})[0] ?? {})[0] ?? 0);
|
|
1112
|
+
return first('page_count') * first('page_size');
|
|
1113
|
+
};
|
|
1114
|
+
// A sampled analysis reads a bounded share of each index.
|
|
1115
|
+
let sample = (driver)=>{
|
|
1116
|
+
if (driver.statistics == 'sampled') {
|
|
1117
|
+
driver.query({
|
|
1118
|
+
t: 'pragma',
|
|
1119
|
+
name: 'analysis_limit',
|
|
1120
|
+
value: SAMPLE
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
};
|
|
1124
|
+
let populated = (driver, probes)=>{
|
|
1125
|
+
let filled = [];
|
|
1126
|
+
for(let i = 0; i < probes.length; i += PROBES){
|
|
1127
|
+
let some = probes.slice(i, i + PROBES);
|
|
1128
|
+
let [row] = driver.query(select({
|
|
1129
|
+
cols: some.map(([name, past], j)=>as(exists(select({
|
|
1130
|
+
cols: [
|
|
1131
|
+
lit(1)
|
|
1132
|
+
],
|
|
1133
|
+
from: table(name),
|
|
1134
|
+
limit: lit(1),
|
|
1135
|
+
offset: past ? lit(past) : undefined
|
|
1136
|
+
})), `t${j}`))
|
|
1137
|
+
}));
|
|
1138
|
+
filled.push(...some.filter((_, j)=>Number(row[`t${j}`])).map(([n])=>n));
|
|
1139
|
+
}
|
|
1140
|
+
return filled;
|
|
1141
|
+
};
|
|
1142
|
+
// Each of `names` probed for more than `past` rows.
|
|
1143
|
+
let past = (names, n = 1)=>names.map((name)=>[
|
|
1144
|
+
name,
|
|
1145
|
+
n
|
|
1146
|
+
]);
|
|
1147
|
+
// Below SQLite's column limit and a Durable Object's, for one statement's
|
|
1148
|
+
// probes.
|
|
1149
|
+
let PROBES = 100;
|
|
1150
|
+
// Whether a table remembered by name is still there: a catalogue read, no rows.
|
|
1151
|
+
let extant = (driver, name)=>driver.query({
|
|
1152
|
+
t: 'pragma',
|
|
1153
|
+
name: 'table_list',
|
|
1154
|
+
arg: name
|
|
1155
|
+
}).length > 0;
|
|
1156
|
+
// Whether a table expected to hold rows does: one billed row at most.
|
|
1157
|
+
let holds = (driver, name)=>populated(driver, past([
|
|
1158
|
+
name
|
|
1159
|
+
], 0)).length > 0;
|
|
1160
|
+
// Whether a table holds a second row: two billed rows at most.
|
|
1161
|
+
let many = (driver, name)=>populated(driver, past([
|
|
1162
|
+
name
|
|
1163
|
+
])).length > 0;
|
|
1164
|
+
/**
|
|
1165
|
+
* The tables whose statistics say they hold fewer than {@link SMALL} rows,
|
|
1166
|
+
* each with the rows they say, read off `sqlite_stat1`. SQLite may plan a
|
|
1167
|
+
* probe of such a table by its key as a scan of it, which costs about the same
|
|
1168
|
+
* while it holds that few. Once it holds thousands, every probe reads all of
|
|
1169
|
+
* them: `cost`, analyzed at one row and grown to 15,108 while the store as a
|
|
1170
|
+
* whole grew less than tenfold, made a lookup of 29 receipts read 476,675 rows
|
|
1171
|
+
* (bug b5285b5d), and `last_deploy`, analyzed at two or three rows and grown
|
|
1172
|
+
* to 232, made the admin's list of 399 apps read 100,189 (bug 16830a75). A
|
|
1173
|
+
* Durable Object may not write `sqlite_stat1`, so no statement mends such a
|
|
1174
|
+
* row; only an analysis of the table once it holds more does. Each decision
|
|
1175
|
+
* reads them here and owes an analysis to each holding twice the rows its
|
|
1176
|
+
* statistics say ({@link doubled}). Analysis never writes a one-row statistic
|
|
1177
|
+
* ({@link analyzing}), but a copy's far end, or an analysis from before, may
|
|
1178
|
+
* have, and no receipt knows of it. The engine's own tables are left out: a
|
|
1179
|
+
* Durable Object's statistics list `_cf_KV` and `_cf_METADATA`, which its
|
|
1180
|
+
* authorizer refuses to any statement of the object's (bug c95c5a57).
|
|
1181
|
+
*/ export let small = (stats)=>{
|
|
1182
|
+
let most = new Map();
|
|
1183
|
+
for (let r of stats){
|
|
1184
|
+
let tbl = String(r.tbl), n = Number(String(r.stat ?? '').split(' ')[0]);
|
|
1185
|
+
if (foreign(tbl) || !Number.isFinite(n)) continue;
|
|
1186
|
+
most.set(tbl, Math.max(most.get(tbl) ?? 0, n));
|
|
1187
|
+
}
|
|
1188
|
+
return [
|
|
1189
|
+
...most
|
|
1190
|
+
].filter(([, n])=>n < SMALL);
|
|
1191
|
+
};
|
|
1192
|
+
/**
|
|
1193
|
+
* Below this many rows, a table's statistics may have SQLite scan it for each
|
|
1194
|
+
* probe by key. Measured in workerd on the admin's list of apps: a LEFT JOIN of
|
|
1195
|
+
* `last_deploy` after five others was planned as a scan with a statistic of
|
|
1196
|
+
* one, two or three rows, and as a seek from four; alone or first among them,
|
|
1197
|
+
* only one row scanned. The margin is for wider joins.
|
|
1198
|
+
*/ export let SMALL = 16;
|
|
1199
|
+
// The probes of {@link small}'s tables: each holding at least twice the rows
|
|
1200
|
+
// its statistics say, and a second row where they say one or none.
|
|
1201
|
+
let doubled = (tables)=>tables.map(([name, n])=>[
|
|
1202
|
+
name,
|
|
1203
|
+
Math.max(1, 2 * n - 1)
|
|
1204
|
+
]);
|
|
1205
|
+
// The rows of `sqlite_stat1`: one for each table and index analyzed.
|
|
1206
|
+
let stat1 = (driver)=>extant(driver, 'sqlite_stat1') ? scan(driver, 'sqlite_stat1', undefined, [
|
|
1207
|
+
'tbl',
|
|
1208
|
+
'idx',
|
|
1209
|
+
'stat'
|
|
1210
|
+
]).map((r)=>({
|
|
1211
|
+
...r,
|
|
1212
|
+
tbl: tableAsWritten(driver.stored?.v, String(r.tbl))
|
|
1213
|
+
})) : [];
|
|
1214
|
+
let joined = (owed = [], more)=>[
|
|
1215
|
+
...new Set([
|
|
1216
|
+
...owed,
|
|
1217
|
+
...more
|
|
1218
|
+
])
|
|
1219
|
+
];
|
|
1220
|
+
// Statistics cover ordinary tables and the tables a virtual table stores its
|
|
1221
|
+
// rows in.
|
|
1222
|
+
let kept = ({ type })=>type == 'table' || type == 'shadow';
|
|
1223
|
+
/** The tables planner statistics are kept for ({@link analyzed}). */ export let analyzable = (driver)=>mainTables(driver).filter(kept).map((r)=>r.name);
|
|
1224
|
+
/** `statistics`, remembering as empty each of `made`, tables made since it
|
|
1225
|
+
* was taken: one a first write makes (./raise.ts) is made empty, and is owed
|
|
1226
|
+
* an analysis once it holds rows, as one an install made would be. */ export let emptied = (statistics, made)=>({
|
|
1227
|
+
...statistics,
|
|
1228
|
+
empty: [
|
|
1229
|
+
...new Set([
|
|
1230
|
+
...statistics.empty,
|
|
1231
|
+
...made
|
|
1232
|
+
])
|
|
1233
|
+
]
|
|
1234
|
+
});
|
|
1235
|
+
/**
|
|
1236
|
+
* The planner statistics a full-analysis engine owes, as the receipt keeps
|
|
1237
|
+
* them (./meta.ts `Statistics`), or undefined where nothing new is owed or
|
|
1238
|
+
* the store holds nothing to analyze. Deciding reads no rows of any table that
|
|
1239
|
+
* holds some: the stored bytes, zero-billed counts of the tables remembered
|
|
1240
|
+
* empty, and after a schema change the catalogue and the statistics standing.
|
|
1241
|
+
* A table owed stays owed until {@link analyzing} reaches it, and one
|
|
1242
|
+
* remembered empty that has been dropped since is forgotten.
|
|
1243
|
+
*/ let owing = (driver, bytes, previous, unchanged)=>{
|
|
1244
|
+
let owed = previous?.owed ?? [];
|
|
1245
|
+
if (previous && unchanged && bytes < previous.bytes * 10) {
|
|
1246
|
+
let stands = new Set(analyzable(driver));
|
|
1247
|
+
let empty = previous.empty.filter((name)=>stands.has(name));
|
|
1248
|
+
let few = small(stat1(driver)).filter(([name])=>stands.has(name) && !owed.includes(name) && !empty.includes(name));
|
|
1249
|
+
let filled = populated(driver, [
|
|
1250
|
+
...past(empty),
|
|
1251
|
+
...doubled(few)
|
|
1252
|
+
]);
|
|
1253
|
+
if (!filled.length && empty.length == previous.empty.length && !('few' in previous)) return;
|
|
1254
|
+
return {
|
|
1255
|
+
bytes: previous.bytes,
|
|
1256
|
+
empty: empty.filter((name)=>!filled.includes(name)),
|
|
1257
|
+
owed: joined(owed, filled)
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
let names = mainTables(driver).filter(kept);
|
|
1261
|
+
let stats = stat1(driver);
|
|
1262
|
+
let taken = new Set(stats.map((r)=>String(r.tbl)));
|
|
1263
|
+
let indexes = new Set(stats.map((r)=>String(r.idx)));
|
|
1264
|
+
// Adopt the statistics that stand, and owe the populated tables lacking
|
|
1265
|
+
// them: one with statistics for some of its indexes held rows when it was
|
|
1266
|
+
// analyzed, and one with none that is not owed already is remembered as
|
|
1267
|
+
// empty while it holds at most one row.
|
|
1268
|
+
if (previous ? bytes < previous.bytes * 10 : taken.has('entity')) {
|
|
1269
|
+
let missing = names.map((r)=>r.name).filter((name)=>!taken.has(name) && !owed.includes(name));
|
|
1270
|
+
let filled = populated(driver, past(missing));
|
|
1271
|
+
let partial = names.filter((r)=>taken.has(r.name) && driver.query({
|
|
1272
|
+
t: 'pragma',
|
|
1273
|
+
name: 'index_list',
|
|
1274
|
+
arg: r.name
|
|
1275
|
+
}).some((i)=>!indexes.has(String(r.withoutRowid && i.origin == 'pk' ? r.name : i.name)))).map((r)=>r.name);
|
|
1276
|
+
let few = small(stats).filter(([name])=>names.some((r)=>r.name == name) && !owed.includes(name));
|
|
1277
|
+
let more = populated(driver, doubled(few));
|
|
1278
|
+
return {
|
|
1279
|
+
bytes: previous?.bytes ?? bytes,
|
|
1280
|
+
empty: missing.filter((name)=>!filled.includes(name)),
|
|
1281
|
+
owed: joined(owed, [
|
|
1282
|
+
...partial,
|
|
1283
|
+
...filled,
|
|
1284
|
+
...more
|
|
1285
|
+
])
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
if (!holds(driver, 'entity')) return;
|
|
1289
|
+
// Tenfold growth, or no statistics to adopt: every table that holds more
|
|
1290
|
+
// than a row afresh, found at two billed rows a table, and the bytes stored
|
|
1291
|
+
// now are what the next growth is measured from.
|
|
1292
|
+
let all = names.map((r)=>r.name);
|
|
1293
|
+
let filled = populated(driver, past(all));
|
|
1294
|
+
return {
|
|
1295
|
+
bytes,
|
|
1296
|
+
empty: all.filter((name)=>!filled.includes(name)),
|
|
1297
|
+
owed: filled
|
|
1298
|
+
};
|
|
1299
|
+
};
|
|
1300
|
+
/**
|
|
1301
|
+
* Analyze up to `n` of the tables `statistics` owes, one `ANALYZE` each, and
|
|
1302
|
+
* answer the receipt that follows: those tables no longer owed, and each
|
|
1303
|
+
* that holds at most one row remembered as empty and left unanalyzed, since
|
|
1304
|
+
* statistics saying it holds one would have SQLite scan it for every probe
|
|
1305
|
+
* once it holds more ({@link small}). A table dropped since it was owed is no
|
|
1306
|
+
* longer owed. Each statement reads that table's index rows, so a caller
|
|
1307
|
+
* bounds `n` to keep a window short.
|
|
1308
|
+
*/ export let analyzing = (driver, statistics, n)=>{
|
|
1309
|
+
let owed = statistics.owed ?? [];
|
|
1310
|
+
let taken = owed.slice(0, n);
|
|
1311
|
+
let empty = statistics.empty.filter((name)=>!taken.includes(name));
|
|
1312
|
+
if (taken.length) sample(driver);
|
|
1313
|
+
for (let name of taken){
|
|
1314
|
+
if (!extant(driver, name)) continue;
|
|
1315
|
+
if (many(driver, name)) driver.query({
|
|
1316
|
+
t: 'analyze',
|
|
1317
|
+
table: name
|
|
1318
|
+
});
|
|
1319
|
+
else empty.push(name);
|
|
1320
|
+
}
|
|
1321
|
+
return {
|
|
1322
|
+
bytes: statistics.bytes,
|
|
1323
|
+
empty,
|
|
1324
|
+
owed: owed.slice(taken.length)
|
|
1325
|
+
};
|
|
1326
|
+
};
|
|
1327
|
+
/**
|
|
1328
|
+
* Whether a file's statistics for `name` are taken by counting its rows
|
|
1329
|
+
* ({@link tally}) instead of by `ANALYZE`: a rowid table with no index, whose
|
|
1330
|
+
* only statistic is its row count. `ANALYZE` counts such a table by reading
|
|
1331
|
+
* every page of it under the write lock, whatever `analysis_limit` says, so on
|
|
1332
|
+
* the box's 10 GB file one table held it 20 s (bug bace8585). Every component
|
|
1333
|
+
* table is one, and so is a text index's data.
|
|
1334
|
+
*/ export let counted = (driver, name)=>driver.statistics == 'sampled' && extant(driver, name) && !driver.query({
|
|
1335
|
+
t: 'pragma',
|
|
1336
|
+
name: 'index_list',
|
|
1337
|
+
arg: name
|
|
1338
|
+
}).length;
|
|
1339
|
+
/**
|
|
1340
|
+
* One window of counting the first table `statistics` owes ({@link counted}):
|
|
1341
|
+
* up to `n` of its rows past where `statistics.counting` stopped, read by
|
|
1342
|
+
* rowid alone, in the caller's snapshot. A row written behind the count is
|
|
1343
|
+
* missed and one deleted is counted; the planner needs only the order of
|
|
1344
|
+
* magnitude.
|
|
1345
|
+
*/ export let tally = (driver, statistics, n)=>{
|
|
1346
|
+
let name = statistics.owed[0];
|
|
1347
|
+
let at = statistics.counting?.table == name ? statistics.counting : {
|
|
1348
|
+
table: name,
|
|
1349
|
+
rows: 0
|
|
1350
|
+
};
|
|
1351
|
+
let [r] = driver.query(select({
|
|
1352
|
+
cols: [
|
|
1353
|
+
as(count(), 'n'),
|
|
1354
|
+
as(fn('max', col('id')), 'last')
|
|
1355
|
+
],
|
|
1356
|
+
from: from(select({
|
|
1357
|
+
cols: [
|
|
1358
|
+
as(col('rowid'), 'id')
|
|
1359
|
+
],
|
|
1360
|
+
from: table(name),
|
|
1361
|
+
where: at.after == null ? undefined : gt(col('rowid'), val(at.after)),
|
|
1362
|
+
order: [
|
|
1363
|
+
col('rowid')
|
|
1364
|
+
],
|
|
1365
|
+
limit: val(n)
|
|
1366
|
+
}), 'r')
|
|
1367
|
+
}));
|
|
1368
|
+
let read = Number(r?.n ?? 0);
|
|
1369
|
+
return {
|
|
1370
|
+
table: name,
|
|
1371
|
+
rows: at.rows + read,
|
|
1372
|
+
after: read ? Number(r.last) : at.after,
|
|
1373
|
+
since: at.after,
|
|
1374
|
+
done: read < n
|
|
1375
|
+
};
|
|
1376
|
+
};
|
|
1377
|
+
/**
|
|
1378
|
+
* The receipt that follows a window of counting ({@link tally}), in the unit
|
|
1379
|
+
* that writes it: the count so far, or once it is `done`, the table's
|
|
1380
|
+
* statistics written as `ANALYZE` writes a table with no index's (its count,
|
|
1381
|
+
* or no row for a table of at most one row, remembered as empty, {@link
|
|
1382
|
+
* analyzing}), and the table no longer
|
|
1383
|
+
* owed. A receipt that moved since the window read it is answered as it
|
|
1384
|
+
* stands, and the next window reads again.
|
|
1385
|
+
*/ export let tallied = (driver, statistics, { since, done, ...counting })=>{
|
|
1386
|
+
let [name, ...rest] = statistics.owed ?? [];
|
|
1387
|
+
let standing = statistics.counting?.table == name ? statistics.counting : undefined;
|
|
1388
|
+
if (name != counting.table || standing?.after != since) return statistics;
|
|
1389
|
+
if (!done) return {
|
|
1390
|
+
...statistics,
|
|
1391
|
+
counting
|
|
1392
|
+
};
|
|
1393
|
+
let empty = statistics.empty.filter((e)=>e != name);
|
|
1394
|
+
if (extant(driver, name)) {
|
|
1395
|
+
let rows = counting.rows > 1 ? counting.rows : 0;
|
|
1396
|
+
stated(driver, name, rows);
|
|
1397
|
+
if (!rows) empty.push(name);
|
|
1398
|
+
}
|
|
1399
|
+
return {
|
|
1400
|
+
bytes: statistics.bytes,
|
|
1401
|
+
empty,
|
|
1402
|
+
owed: rest
|
|
1403
|
+
};
|
|
1404
|
+
};
|
|
1405
|
+
// Write `rows` as the statistics of `name`, a table with no index, and have
|
|
1406
|
+
// the planner read them again: `ANALYZE sqlite_schema` reads no table, and
|
|
1407
|
+
// makes `sqlite_stat1` where none stands.
|
|
1408
|
+
let stated = (driver, name, rows)=>{
|
|
1409
|
+
let v = driver.stored?.v;
|
|
1410
|
+
if (v) name = sqlStored(v, name);
|
|
1411
|
+
let reload = ()=>driver.query({
|
|
1412
|
+
t: 'analyze',
|
|
1413
|
+
table: 'sqlite_schema'
|
|
1414
|
+
});
|
|
1415
|
+
if (!extant(driver, 'sqlite_stat1')) reload();
|
|
1416
|
+
driver.query({
|
|
1417
|
+
t: 'delete',
|
|
1418
|
+
from: 'sqlite_stat1',
|
|
1419
|
+
where: eq(col('tbl'), val(name))
|
|
1420
|
+
});
|
|
1421
|
+
if (rows) {
|
|
1422
|
+
driver.query({
|
|
1423
|
+
t: 'insert',
|
|
1424
|
+
into: 'sqlite_stat1',
|
|
1425
|
+
cols: [
|
|
1426
|
+
'tbl',
|
|
1427
|
+
'idx',
|
|
1428
|
+
'stat'
|
|
1429
|
+
],
|
|
1430
|
+
rows: [
|
|
1431
|
+
[
|
|
1432
|
+
val(name),
|
|
1433
|
+
val(null),
|
|
1434
|
+
val(String(rows))
|
|
1435
|
+
]
|
|
1436
|
+
]
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
reload();
|
|
1440
|
+
};
|
|
1441
|
+
//# sourceMappingURL=ddl.js.map
|