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