@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/mod.ts ADDED
@@ -0,0 +1,1762 @@
1
+ import { purgeHistory, retained } from './purge.js'
2
+ import { preserving, type Trash, type TrashPage } from '@yaks/graph/trash'
3
+ import { purgeTrashSql, retainSql, trashed } from './trash.js'
4
+ import { cardinality, population, torn } from './population.js'
5
+ // @yaks/sqlite — a storage adapter that turns the yaks query/vocabulary/SQL
6
+ // stack into a working SQLite-backed store. It composes three sibling packages:
7
+ //
8
+ // @yaks/query parses a query string into an AST
9
+ // @yaks/vocab describes a component vocabulary and interrogates it
10
+ // @yaks/sql compiles an AST + a vocabulary into SQL + bound params
11
+ //
12
+ // and adds the two halves those packages leave to a backend: DDL (the schema a
13
+ // vocabulary implies) and writes (a patch applied to that schema). The reads it
14
+ // gets for free — it runs @yaks/sql's compiled statement and gathers the rows.
15
+ //
16
+ // Both halves are the reference every SQLite-shaped adapter shares. The schema
17
+ // is one derivation, and so is the write: ./write.ts builds each write as a
18
+ // self-sufficient statement — an owner id is a subquery, never a value looked up
19
+ // first — so the same statements this package runs one at a time are the ones
20
+ // @yaks/d1 gathers into a single batch.
21
+ //
22
+ // The model is the yaks entity graph: everything is an entity (a string id)
23
+ // carrying components (a row per component table). An entity is what its
24
+ // components make it — a blog post is a `doc` plus a `post`; a product is a
25
+ // `doc` plus a `price`. Each component covers one aspect of an entity; the set
26
+ // of components an entity carries is its identity. A read returns a bundle (an
27
+ // entity with its components gathered); a write takes a batch of bundles and
28
+ // patches them in — omitted properties untouched, a null property cleared, a
29
+ // null component dropped.
30
+ //
31
+ // It implements @yaks/graph's `Storage`, which is where the responsibilities
32
+ // divide: this package owns the bytes (schema, rows, identity, transactions)
33
+ // and @yaks/graph owns the decisions (admission, preconditions, which entities
34
+ // a delete takes with it, provenance). Point `graph()` at a store from here
35
+ // and the two halves are the whole thing.
36
+ //
37
+ // Beside the graph it keeps one thing of its own: `server_meta`, the key/value
38
+ // a store writes about itself — its lineage epoch, a sweep's mark — read and
39
+ // written through ./meta.ts, and carried by no bundle.
40
+ //
41
+ // The adapter is bound to a driver and a vocabulary once, by `storage()`, and
42
+ // reads and writes bundles from then on. The driver is any object with
43
+ // `query`/`exec` (@yaks/sql `Driver`) — an in-process SQLite for a test, a pooled
44
+ // handle for a server — so nothing here names a concrete SQLite library.
45
+
46
+ import { relabelsVocab, type Vocab } from '@yaks/vocab'
47
+ import { type And, bare, type Clause } from '@yaks/query'
48
+ import { type Filter, filter } from '@yaks/match'
49
+ import { backingsIn, derivedIn } from '@yaks/sql'
50
+ import {
51
+ type BindOpts,
52
+ type Driver,
53
+ erect,
54
+ idOf,
55
+ literals,
56
+ type Raw,
57
+ type Row,
58
+ sourceScreen,
59
+ type Stmt,
60
+ worn,
61
+ } from '@yaks/sql'
62
+ import type {
63
+ Binding,
64
+ Bundle,
65
+ Doom,
66
+ Eid,
67
+ Entity,
68
+ Graves,
69
+ Match,
70
+ Measure,
71
+ ReadOpts,
72
+ } from 'jsr:@yaks/graph@0.2.36'
73
+ import { after, type Clock, sleep } from '@yaks/fp'
74
+ import { context, scope } from '@yaks/trace'
75
+ import type { Query } from './read.js'
76
+ import {
77
+ analyzable,
78
+ analyzed,
79
+ anyStanding,
80
+ built,
81
+ emptied,
82
+ fit,
83
+ grown,
84
+ indexed,
85
+ logged,
86
+ respine,
87
+ retabled,
88
+ retired,
89
+ standing,
90
+ tabled,
91
+ } from './ddl.js'
92
+ import {
93
+ analyzedAt,
94
+ epoch,
95
+ installation,
96
+ installed,
97
+ meta,
98
+ SCHEMA,
99
+ } from './meta.js'
100
+ import {
101
+ admitted,
102
+ ast,
103
+ get,
104
+ read,
105
+ type ReadCache,
106
+ rows,
107
+ screened,
108
+ Unpointed,
109
+ type Unsettled,
110
+ } from './read.js'
111
+ import { doom } from './doom.js'
112
+ import { exclusive, unit, unwaiting } from './unit.js'
113
+ import { enter } from '@yaks/graph/enter'
114
+ import type { Branches } from 'jsr:@yaks/graph@0.2.36/storage'
115
+ import { branching, unborn } from './branches.js'
116
+ import { busy } from './error.js'
117
+ import { options } from './reader.js'
118
+ import { catalog, setOf } from './catalog.js'
119
+ import {
120
+ backfill,
121
+ classify,
122
+ entomb,
123
+ heldBy,
124
+ type Ledger,
125
+ ledger,
126
+ pendingShapes,
127
+ } from './archetype.js'
128
+ import { componentTables, objects, shape, sole } from './physical.js'
129
+ import {
130
+ analyze,
131
+ build,
132
+ forgo,
133
+ reshape,
134
+ type Sizes,
135
+ statistics,
136
+ upkeep as daily,
137
+ } from './owe.js'
138
+ import { maintenance } from './maintenance.js'
139
+ import { plan } from './plan.js'
140
+ import {
141
+ births,
142
+ erase,
143
+ type Names,
144
+ type Numbering,
145
+ patch,
146
+ prune,
147
+ remove,
148
+ revive,
149
+ spines,
150
+ } from './write.js'
151
+ import { burying } from './buried.js'
152
+ import { located, measure } from './measure.js'
153
+ import { bindings } from './rules.js'
154
+ import { basis, local, memoized, rooted, simple } from './memo.js'
155
+ import { listed, revision, storeAs } from '@yaks/sql'
156
+ import { bindStorage, readingVocab } from './shape.js'
157
+ export { bindStorage, identified, layoutOf, wordColumns } from './shape.js'
158
+ import { newest, watch } from './watch.js'
159
+ import { gotten, metered, named } from './budget.js'
160
+ import { comps, dead } from '@yaks/graph/bundle'
161
+ import { holds, raise, raisedIn, recorded, units, unraised } from './raise.js'
162
+ import { tables } from './layout.js'
163
+ import { raisedSurvey, surveyed } from './survey.js'
164
+ import { Refused } from '@yaks/graph/errors'
165
+ import {
166
+ type History,
167
+ historySchema,
168
+ keep,
169
+ type Mode,
170
+ reshapes,
171
+ SEEDING,
172
+ type Seeding,
173
+ seeds,
174
+ type Typed,
175
+ unseeded,
176
+ within,
177
+ } from './history.js'
178
+ import { add } from './follow.js'
179
+ import { sha256 } from '@yaks/graph/sha256'
180
+ export {
181
+ beside,
182
+ BRANCH,
183
+ BRANCHES,
184
+ FROM,
185
+ type History,
186
+ historySchema,
187
+ keeps,
188
+ type Mode,
189
+ SEEDING,
190
+ ticked,
191
+ TO,
192
+ } from './history.js'
193
+
194
+ export {
195
+ type Backfill,
196
+ backfill,
197
+ componentTables,
198
+ type Drift,
199
+ drift,
200
+ entomb,
201
+ heldBy,
202
+ type Ledger,
203
+ ledger,
204
+ mend,
205
+ reclassify,
206
+ reclassifyAll,
207
+ } from './archetype.js'
208
+ export { statements } from './statements.js'
209
+ import { statements } from './statements.js'
210
+ import { checks as diagnostics } from './check.js'
211
+ import type { Statements } from '@yaks/sql'
212
+ import { type MigrationControl, migrations } from './migration.js'
213
+ export { catalog } from './catalog.js'
214
+ export { pointSql } from './point.js'
215
+ export {
216
+ type Deletions,
217
+ deletions,
218
+ type DeletionWindow,
219
+ type Identity,
220
+ identity,
221
+ inspect,
222
+ type StoreSize,
223
+ type TableSize,
224
+ } from './inspect.js'
225
+ export {
226
+ asked,
227
+ checks,
228
+ columns,
229
+ defined,
230
+ heard,
231
+ objects,
232
+ pinned,
233
+ sole,
234
+ type Stood,
235
+ } from './physical.js'
236
+ export { GONE, OVER, type Overlay, overlay } from './overlay.js'
237
+ export { bindings, matched } from './rules.js'
238
+ export * from './bundle.js'
239
+ export {
240
+ holds,
241
+ lazy,
242
+ raise,
243
+ RAISED,
244
+ recorded,
245
+ rests,
246
+ stood,
247
+ unraised,
248
+ } from './raise.js'
249
+ export {
250
+ analyzed,
251
+ built,
252
+ FIT,
253
+ fit,
254
+ fitting,
255
+ grown,
256
+ indexed,
257
+ logged,
258
+ META,
259
+ type Orphan,
260
+ orphaned,
261
+ refit,
262
+ respine,
263
+ respined,
264
+ retabled,
265
+ retired,
266
+ schema,
267
+ type Standing,
268
+ standing,
269
+ tabled,
270
+ unfit,
271
+ unresolved,
272
+ } from './ddl.js'
273
+ export {
274
+ EPOCH,
275
+ epoch,
276
+ epochAt,
277
+ installed,
278
+ type Meta,
279
+ meta,
280
+ printed,
281
+ REQUIRED,
282
+ requirements,
283
+ requires,
284
+ } from './meta.js'
285
+ export { decoded, isJsonb, jsonIn, jsonOut, projected } from './jsonb.js'
286
+ export {
287
+ compSql,
288
+ get,
289
+ OWNER,
290
+ type Query,
291
+ read,
292
+ rows,
293
+ setSql,
294
+ spine,
295
+ tagOf,
296
+ } from './read.js'
297
+ export {
298
+ buried,
299
+ dropSql,
300
+ erase,
301
+ eraseSql,
302
+ minted,
303
+ mintSql,
304
+ type Names,
305
+ type Numbering,
306
+ numberSql,
307
+ patch,
308
+ patchSql,
309
+ prune,
310
+ pruneSql,
311
+ remove,
312
+ removeSql,
313
+ revive,
314
+ type Spine,
315
+ spines,
316
+ touched,
317
+ unburySql,
318
+ upsertSql,
319
+ } from './write.js'
320
+ export type { Storage } from 'jsr:@yaks/graph@0.2.36'
321
+
322
+ /**
323
+ * A transaction over an embedded database: the same shape @yaks/graph's `Tx`
324
+ * has, with every method returning immediately rather than a promise. Naming
325
+ * the synchronous form is what lets `apply()` stay synchronous over SQLite —
326
+ * and lets a caller of this package read a bundle without awaiting one.
327
+ */
328
+ export type Tx = {
329
+ /** the id of the transaction this unit's versions name, where the store
330
+ * keeps history (./history.ts) */
331
+ clock?: () => number
332
+ /** a query → whole bundles, or only `comps` when named */
333
+ read: (query: Query, opts?: ReadOpts, comps?: string[]) => Bundle[]
334
+ /** identity, not search: these entities as they stand, carrying the
335
+ * components `comps` names or every one */
336
+ get: (eids: string[], comps?: string[]) => Bundle[]
337
+ /** which entities are deleted along with these, and what has to release
338
+ * them — the death cascade computed by one recursive statement rather than a
339
+ * read per level */
340
+ doom: (eids: string[]) => Doom
341
+ /** what declared rules are evaluated through: every match run against this
342
+ * graph with `bundles` folded in, through one batch overlay (./overlay.ts) */
343
+ bindings: (
344
+ matches: Match[],
345
+ bundles: Bundle[],
346
+ covers: string[],
347
+ ) => Binding[][]
348
+ /** patch the bundles in → the entities this patch minted */
349
+ patch: (bundles: Bundle[]) => Entity[]
350
+ /** remove these entities: rows gone, identity tombstoned */
351
+ remove: (entities: Entity[]) => void
352
+ /** erase these entities, a writer's own bookkeeping: rows and identity
353
+ * gone, no tombstone */
354
+ discard: (entities: Entity[]) => void
355
+ /** Erase identities checked by an explicit orphan repair request. */
356
+ prune: (eids: string[]) => void
357
+ /** bring these tombstoned entities back: tombstone gone, identity kept */
358
+ revive: (eids: string[]) => void
359
+ /** the graves a retention sweep may prune (./buried.ts) */
360
+ buried: (
361
+ before: string,
362
+ page: { after?: string; limit: number; referenced?: boolean },
363
+ ) => Graves
364
+ }
365
+
366
+ /**
367
+ * A bound store: @yaks/graph's {@link Storage}, with synchronous reads. Its
368
+ * transactions stay synchronous when uncontended; an independent transaction
369
+ * waits for an asynchronous body already using its connection to finish.
370
+ */
371
+ // A read here takes the compiler's whole options, not just @yaks/graph's
372
+ // `ReadOpts`: a caller of this package may pass a query a derived-property
373
+ // registry or an @yaks/sql extension — the extension point @yaks/fts and
374
+ // @yaks/embedding register through — and it would be unreachable if this
375
+ // method only took `now`. `ReadOpts` is assignable to `BindOpts`, so the wider
376
+ // signature still satisfies `Storage` wherever the generic contract is what is
377
+ // wanted.
378
+ export type Store = {
379
+ /** Destructive transactions retained for recovery. */
380
+ trash: (eids?: Eid[], page?: TrashPage) => Trash[]
381
+ /** Purge one retained transaction after a person explicitly chooses it. */
382
+ purgeTrash: (id: string | string[]) => void
383
+ purgeHistory: (eids: Eid[]) => Bundle[]
384
+ retained: (values: string[]) => string[]
385
+
386
+ /** its branches, where it keeps history (./branches.ts) */
387
+ branches?: Branches
388
+ /** Matches evaluated against committed rows without a write transaction. */
389
+ bindings?: Tx['bindings']
390
+ /** Current committed-data invalidation token, including external WAL writes. */
391
+ revision?: () => unknown
392
+ /** The newest row of `comp`, which moves only when a row is added
393
+ * (./watch.ts `newest`). */
394
+ newest: (comp: string) => number
395
+ /** Call `heard` soon after another connection commits a new row of
396
+ * `comp` (./watch.ts). Only a store over a file has one. Answers a stop. */
397
+ watch?: (comp: string, heard: () => void) => () => void
398
+ statements: Statements
399
+ migrations: MigrationControl
400
+ checks: ReturnType<typeof diagnostics>
401
+ /** Whether a value this store reads for the property means its entity
402
+ * wears the component (@yaks/sql `worn`). */
403
+ worn: (comp: string, prop: string) => boolean
404
+ /** the schema statements the bound vocabulary implies */
405
+ ddl: () => Stmt[]
406
+ /**
407
+ * the `add column` statements the live tables are missing — what `ddl()`
408
+ * cannot emit, since `create table if not exists` does nothing to a table
409
+ * that already exists (ddl.ts `grown`). Read after `ddl()` has run.
410
+ */
411
+ grown: () => Stmt[]
412
+ /** the print of the statements {@link install} runs, the store's part of a
413
+ * composed schema's print (./follow.ts) */
414
+ print: () => string
415
+ /** run them — create the tables and indexes the vocabulary needs, and
416
+ * classify what the archetype backfill finds unclassified; nothing, where
417
+ * the file's schema is as this vocabulary last installed it. `beside` is
418
+ * the rest of the composed schema (./follow.ts): a table too big to rebuild
419
+ * at once is rebuilt later (./owe.ts), and its indexes and triggers there
420
+ * are raised again on the rebuilt one. Answers what it left undone, each
421
+ * also reported: a table whose rows do not fit its new shape, and a unique
422
+ * index those rows break (./owe.ts `build`) */
423
+ install: (beside?: Stmt[]) => Error[]
424
+ /** Advance one deferred schema window admitted by its estimated writes. */
425
+ maintain: (admit: (written: number) => boolean, seedRows?: number) => boolean
426
+ /** make the tables of `comps` (every component of the vocabulary, left
427
+ * out), with all that rests on them, as a first write naming them would
428
+ * (./raise.ts): for a writer that fills a table in raw SQL rather than
429
+ * through a patch. Answers the components it made a table for. */
430
+ raise: (comps?: readonly string[]) => string[]
431
+ /** analyze up to `tables` of the tables whose planner statistics
432
+ * {@link install} owes (./ddl.ts `analyzed`), each in its own unit, and
433
+ * answer how many stay owed: a full-analysis engine's install decides what
434
+ * is owed and leaves the reading to whoever calls this, off the request
435
+ * that installed. The decision is also taken again here once a day
436
+ * (./owe.ts `statistics`), since an install whose schema stands decides
437
+ * nothing: a code deploy that changes how statistics are decided reaches
438
+ * a Durable Object only this way (bug b5285b5d). Nothing is ever owed on
439
+ * any other driver. */
440
+ analyze: (tables?: number) => number
441
+ /** a query → its entities, with `comps` only where named: which entities
442
+ * match and what they carry read as one snapshot, in a unit that takes no
443
+ * write lock, so another process's commit is seen whole or not at all */
444
+ read: (
445
+ query: Query,
446
+ opts?: BindOpts & ReadOpts,
447
+ comps?: string[],
448
+ ) => Bundle[]
449
+ /** a query → the compiled statement's raw rows (counts, tallies) */
450
+ rows: (query: Query, opts?: BindOpts & ReadOpts) => Row[]
451
+ /** the graves a retention sweep may prune: tombstones laid before `before`
452
+ * that nothing in the file names (./buried.ts), a page of them from `after`,
453
+ * read as one snapshot */
454
+ buried: (
455
+ before: string,
456
+ page: { after?: string; limit: number; referenced?: boolean },
457
+ ) => Graves
458
+ /** The host database's absolute path, absent for memory and hosted stores. */
459
+ readonly file?: string
460
+ /** what the file keeps, measured off the caller's thread (./measure.ts) */
461
+ measure: (signal?: AbortSignal) => Promise<Measure | undefined>
462
+ /** a query → a statement selecting the ids of the entities it admits, as
463
+ * this store compiles its reads (./read.ts `screened`); null for a query
464
+ * with nothing to narrow by */
465
+ screen: (query: Query, opts?: BindOpts & ReadOpts) => Raw | null
466
+ /** these entities as they stand, carrying the components `comps` names or
467
+ * every one, read in a unit that takes no write lock */
468
+ get: (eids: Eid[], comps?: string[], opts?: BindOpts & ReadOpts) => Bundle[]
469
+ /** run `body` in a transaction: commit on return, roll back on throw; with
470
+ * `wait: false` a file another connection holds refuses at once,
471
+ * `retryable: true`, rather than sleeping the thread (./unit.ts) */
472
+ tx: <R>(
473
+ body: (tx: Tx) => R,
474
+ opts?: { admission?: boolean; wait?: boolean },
475
+ ) => R | Promise<Awaited<R>>
476
+ }
477
+
478
+ /**
479
+ * What `storage()` is bound with: @yaks/sql's read options (a derived-property
480
+ * registry, a fixed `now` for time phrases). They apply to every read, and the
481
+ * registry's `text` expressions to the schema too: a property whose stored
482
+ * value is not the text itself (a blob's address, @yaks/blob `blobRead`) reads
483
+ * as text through `doc_value`.
484
+ */
485
+ export type Opts = BindOpts & {
486
+ /** Timers used while transaction entry waits for another writer. */
487
+ clock?: Clock
488
+ /** Maintain global populations after the first unscoped aggregate (default).
489
+ * Stores that need counts immediately may seed them during installation;
490
+ * other stores never pay for upkeep until a count actually asks for it. */
491
+ counts?: 'lazy' | 'eager'
492
+ /** Leave row-dependent work for maintain(), while reads serve the standing rows. */
493
+ deferred?: boolean
494
+ /** Where history begins, take the live rows as their first versions a page
495
+ * at a time through maintain() rather than all in the install: for a host
496
+ * whose writes are bounded by the minute (a Durable Object). Until the
497
+ * last page, the store makes no branch. */
498
+ paced?: boolean
499
+
500
+ /** How big a table is before a file owes its schema work, and the rows a
501
+ * window does of it (./owe.ts `SIZES`): what a test shrinks. */
502
+ sizes?: Sizes
503
+ /** A single-owner host's readiness check, called on the first operation.
504
+ * True asserts that this vocabulary and its derived schema, metadata and
505
+ * archetypes already stand; false asks this adapter to install them. The
506
+ * host must bind a new store when its schema changes. File drivers never
507
+ * install on an operation: their host brings them to its composed schema
508
+ * as it opens (./follow.ts). `install()` always validates, regardless of
509
+ * this check. */
510
+ schemaReady?: () => boolean
511
+ /** Additive installation of a deliberately partial vocabulary. Existing
512
+ * indexes owned by declarations this installer does not carry stay intact. */
513
+ partial?: boolean
514
+ /** Give new spines a human-readable number. Opt-IN: left out, an entity is
515
+ * its eid and nothing else, which is what a store whose entities nobody ever
516
+ * types the number of wants. A table of letters numbers each entity in the
517
+ * series of the components it is given, and `true` takes that table from
518
+ * the prefixes the vocabulary declares (./write.ts `Numbering`). Identity, and reporting which entities
519
+ * were created, still belong to storage either way. */
520
+ number?: Numbering
521
+ /** Where an id kept as another entity's name lives (./write.ts `Names`),
522
+ * so a number given out before and kept as a name is never given again. */
523
+ names?: Names
524
+ /** Where a failure the store outlives is told: a table that stood and could
525
+ * not be fitted to the vocabulary, left as it was (ddl.ts `fit`), or a
526
+ * write that went async inside a transaction that commits when its body
527
+ * returns (./error.ts `halfway`). One line on the console, by default
528
+ * (ddl.ts `logged`). */
529
+ report?: (error: Error) => void
530
+ /** What each of these entities, by id, holds among `names` in the mode
531
+ * this connection reads, where no archetype pointer says (./mode.ts). */
532
+ held?: (
533
+ ids: number[],
534
+ names: readonly string[],
535
+ ) => Map<number, readonly string[]>
536
+ /** Keep every version a write replaces (./history.ts), naming the
537
+ * transactions this statement takes, one per unit that writes a component
538
+ * with history. From the history plugin (@yaks/journal). */
539
+ history?: History
540
+ /** Read main as of a transaction, or a branch, and write only to the branch:
541
+ * what a connection opened for a mode is bound with (./mode.ts). */
542
+ mode?: Mode
543
+ /** How many bytes of the entities it read the store keeps in memory
544
+ * (./memo.ts): 4 MiB unless its opener can spare more. */
545
+ memory?: number
546
+ /** The statements a host keeps beside the store's own over its component
547
+ * tables (search indexes and their triggers, an embedding queue's): each is
548
+ * made with the last table it rests on, by the write that first names that
549
+ * component (./raise.ts). Asked when a write first names one, so a host
550
+ * that composes them after binding the store can still give them. */
551
+ over?: (layout: Vocab) => readonly Stmt[]
552
+ }
553
+
554
+ // The read options a statement is the same under (@yaks/graph `ReadOpts`).
555
+ const UNREAD = new Set([
556
+ 'person',
557
+ 'level',
558
+ 'administrative',
559
+ 'native',
560
+ 'durable',
561
+ 'patch',
562
+ 'speaks',
563
+ 'now',
564
+ 'storageOrder',
565
+ 'unordered',
566
+ ])
567
+
568
+ // A read's options without what its caller is doing around it: the activity
569
+ // it runs under (`parent`, new with every request) and when it stops waiting
570
+ // (`signal`). A read here is synchronous and traced by its unit, so neither is
571
+ // an input of the answer, and a read made under them shares every answer and
572
+ // statement kept for the same read made without.
573
+ let asking = <O extends { signal?: AbortSignal; parent?: string }>(o?: O) => {
574
+ if (!o) return o
575
+ let { signal: _signal, parent: _parent, ...rest } = o
576
+ return rest
577
+ }
578
+
579
+ // The effective read options are data; order of object keys is immaterial,
580
+ // while arrays, query clauses, paths and literal token strings keep order.
581
+ // Every read keys its options, so an array of plain values is written whole by
582
+ // `JSON.stringify` and only objects are taken apart.
583
+ let plain = (v: unknown) => !v || typeof v != 'object'
584
+ let keyed = (value: unknown): string | undefined => {
585
+ if (plain(value)) return JSON.stringify(value)
586
+ let v = value as { toJSON?: () => unknown } & Record<string, unknown>
587
+ if (typeof v.toJSON == 'function') return keyed(v.toJSON())
588
+ if (Array.isArray(v)) {
589
+ return v.every(plain)
590
+ ? JSON.stringify(v)
591
+ : `[${v.map((x) => keyed(x) ?? 'null').join(',')}]`
592
+ }
593
+ let out: string[] = []
594
+ for (let k of Object.keys(v).sort()) {
595
+ let got = keyed(v[k])
596
+ if (got !== undefined) out.push(`${JSON.stringify(k)}:${got}`)
597
+ }
598
+ return `{${out.join(',')}}`
599
+ }
600
+
601
+ // The tables of versions a store with history keeps (./history.ts), made where
602
+ // missing and typed as the live tables stand now, and each one just made
603
+ // given the live rows as the versions they are so far: here, or, `paced`, a
604
+ // page at a time through maintain() (./maintenance.ts).
605
+ let versioned = (driver: Driver, vocab: Vocab, paced: boolean): Error[] => {
606
+ let had = new Set(objects(driver, { type: 'table' }).map((o) => o.name))
607
+ let stood = standing(driver, vocab)
608
+ let typed: Typed = (comp, c) => {
609
+ let found = stood[comp]?.cols.find((r) => r.name == c)
610
+ return found ? String(found.type ?? '') : undefined
611
+ }
612
+ let left = add(driver, historySchema(vocab, typed))
613
+ let made = (name: string) => !had.has(name)
614
+ let seed = paced ? reshapes(vocab, made) : seeds(vocab, made)
615
+ for (let s of holds(driver, vocab, seed)) driver.query(s)
616
+ // Only a live table that stands holds rows to take.
617
+ let comps = paced ? unseeded(vocab, made).filter((c) => had.has(c)) : []
618
+ if (comps.length) {
619
+ // An install while pages are still owed adds its tables behind them.
620
+ let owed = meta(driver).get(SEEDING)
621
+ let was: Seeding = owed ? JSON.parse(owed) : { comps: [], after: 0 }
622
+ meta(driver).set(
623
+ SEEDING,
624
+ JSON.stringify({ ...was, comps: [...was.comps, ...comps] }),
625
+ )
626
+ }
627
+ return left
628
+ }
629
+
630
+ /**
631
+ * Bind a store to a driver and a vocabulary — a {@link Storage} @yaks/graph
632
+ * can apply bundles to. `base` options (a derived-property registry, a fixed
633
+ * `now` for time phrases) ride every read; a per-call `opts` merges over them.
634
+ */
635
+ export let storage = (
636
+ driver: Driver,
637
+ vocab: Vocab,
638
+ base: Opts = {},
639
+ ): Store => {
640
+ // Binding asks the file nothing: the store is bound on its first use, once
641
+ // it knows how the file lays its words out (./shape.ts).
642
+ let store: Store | undefined
643
+ let at = () => store ??= bound(driver, bindStorage(driver, vocab), base)
644
+ return new Proxy({} as Store, {
645
+ get: (target, k) => {
646
+ if (k != 'reload') return Reflect.get(target, k) ?? Reflect.get(at(), k)
647
+ return (next: Vocab): boolean => {
648
+ let old = bindStorage(driver, vocab)
649
+ let fresh = bindStorage(driver, next)
650
+ if (!relabelsVocab(old, fresh)) {
651
+ bindStorage(driver, vocab)
652
+ return false
653
+ }
654
+ let options = {
655
+ ...base,
656
+ ...base.derived
657
+ ? { derived: derivedIn(base.derived, vocab, next) }
658
+ : {},
659
+ ...base.backed
660
+ ? { backed: backingsIn(base.backed, vocab, next) }
661
+ : {},
662
+ }
663
+ try {
664
+ store = bound(driver, fresh, options)
665
+ } catch (error) {
666
+ bindStorage(driver, vocab)
667
+ throw error
668
+ }
669
+ base = options
670
+ vocab = next
671
+ return true
672
+ }
673
+ },
674
+ has: (target, k) => Reflect.has(target, k) || Reflect.has(at(), k),
675
+ ownKeys: (
676
+ target,
677
+ ) => [...new Set([...Reflect.ownKeys(at()), ...Reflect.ownKeys(target)])],
678
+ getOwnPropertyDescriptor: (target, k) =>
679
+ Reflect.getOwnPropertyDescriptor(target, k) ??
680
+ Reflect.getOwnPropertyDescriptor(at(), k),
681
+ })
682
+ }
683
+
684
+ let bound = (driver: Driver, vocab: Vocab, base: Opts): Store => {
685
+ let effective = options(driver, vocab, base)
686
+ if (base.history) keep(driver, vocab, base.history, base.mode)
687
+ // What a store with history adds beside its own schema, run and printed
688
+ // with it.
689
+ let besides = base.history ? historySchema(vocab) : []
690
+ let printed = () => {
691
+ let own = plan(vocab, base.derived, !!driver.file).print
692
+ return besides.length ? sha256(`${own};history`) : own
693
+ }
694
+ // Whether this store keeps each entity's archetype pointer in step with
695
+ // its rows: every store does, whatever its vocabulary declares, since every
696
+ // whole read and removal goes by the pointer. A mode's store reads
697
+ // what an entity held then, which no pointer says (./mode.ts).
698
+ let keeping = !base.mode
699
+ // What the connection's open transaction wrote that no pointer says yet
700
+ // (./archetype.ts `ledger`).
701
+ let book = keeping ? ledger(driver) : undefined
702
+ let owing = () => book?.owed() ?? []
703
+ // All handles on this connection see the open writer's rows, including a
704
+ // graph's scope reads through the outer store rather than its tx handle.
705
+ let upkeep = maintenance(driver, vocab)
706
+ let migrating = () => !!base.deferred && upkeep.pending()
707
+ let unindexed = Object.assign(() => undefined, {
708
+ pending: { ids: [], matching: () => [] },
709
+ })
710
+ let opts = () => ({
711
+ ...effective(),
712
+ ...migrating() ? { archetypes: unindexed } : {},
713
+ ...!migrating() && book?.owed().length
714
+ ? { archetypes: catalog(driver, () => pendingShapes(driver, book)) }
715
+ : {},
716
+ })
717
+ // Who says what an entity holds where its pointer does not: the open
718
+ // transaction's ledger, or the mode this connection reads (`base.held`).
719
+ let unsettled: Unsettled | undefined = book
720
+ ? {
721
+ wrote: book.wrote,
722
+ held: (rows) => {
723
+ let known = new Map(rows.flatMap(({ eid, id, pointed }) => {
724
+ let tables = book.held(eid, pointed)
725
+ return tables ? [[id, tables] as const] : []
726
+ }))
727
+ let missing = rows.filter((r) => !known.has(r.id)).map((r) => r.id)
728
+ if (missing.length && migrating()) {
729
+ for (let [id, tables] of upkeep.held(missing)) {
730
+ known.set(id, [
731
+ ...tables,
732
+ ])
733
+ }
734
+ }
735
+ return known
736
+ },
737
+ }
738
+ : base.held && {
739
+ // No pointer says what an entity held then.
740
+ wrote: () => true,
741
+ held: (rows, names) => base.held!(rows.map((r) => r.id), names),
742
+ }
743
+ // What an install answers for, as its receipt marks it: the print, and the
744
+ // count and length of what it makes, of what rests on the tables first
745
+ // writes raised (./raise.ts), and of the `strays` beside them.
746
+ let marked = (strays: string[]) => {
747
+ let { made, raised, on } = plan(vocab, base.derived, !!driver.file)
748
+ let stand = raisedIn(driver, vocab)
749
+ let answers = [
750
+ ...made,
751
+ ...raised.flatMap((s, i) =>
752
+ on[i].length && on[i].every((c) => stand.has(c)) ? [s.name] : []
753
+ ),
754
+ ]
755
+ return [printed(), shape(driver, [...answers, ...strays]), ...strays]
756
+ .join(' ')
757
+ }
758
+ // Everything a component's first write may make (./raise.ts): the store's
759
+ // own schema, and what its host keeps beside it over component tables.
760
+ let makes = () =>
761
+ units(vocab, base.derived, !!driver.file, base.over?.(vocab))
762
+ // Raise the tables of `given` the file lacks, keeping the survey and an
763
+ // install receipt that stood before standing after.
764
+ let raising = (given: Iterable<string>): string[] => {
765
+ let before = surveyed(driver, vocab, base.derived)
766
+ let receipt = installation(driver)
767
+ let strays = receipt?.schema.split(' ').slice(2) ?? []
768
+ let current = receipt?.schema == marked(strays)
769
+ let stats = receipt?.statistics
770
+ let had = stats && new Set(analyzable(driver))
771
+ let made = raise(driver, vocab, given, makes())
772
+ raisedSurvey(driver, vocab, base.derived, before, made)
773
+ if (!made.length) return made
774
+ // An install receipt that stood before stands after: what a first write
775
+ // makes is no change an install answers for. Its statistics remember the
776
+ // tables made as empty, as they were when an install made them.
777
+ let schema = current ? marked(strays) : receipt?.schema
778
+ if (stats && schema) {
779
+ let fresh = analyzable(driver).filter((t) => !had!.has(t))
780
+ analyzedAt(driver, schema, emptied(stats, fresh))
781
+ } else if (current) meta(driver).set(SCHEMA, schema!)
782
+ return made
783
+ }
784
+ // The bundles a write names, ready to be written: each component one gives
785
+ // a value whose table waits for its first write is raised first, in the
786
+ // write's transaction (./raise.ts); a component one takes away that has no
787
+ // table is left out, since no entity wears it.
788
+ let readied = (bundles: Bundle[]): Bundle[] => {
789
+ let given = new Set<string>(), taken = false
790
+ for (let b of bundles) {
791
+ for (let [name, c] of comps(b)) {
792
+ if (c == null) taken = true
793
+ else given.add(name)
794
+ }
795
+ }
796
+ if (given.size && unraised(driver, vocab).some((c) => given.has(c))) {
797
+ raising(given)
798
+ }
799
+ if (!taken) return bundles
800
+ let missing = new Set(unraised(driver, vocab))
801
+ if (!missing.size) return bundles
802
+ return bundles.map((b) => {
803
+ let gone = comps(b).filter(([n, c]) => c == null && missing.has(n))
804
+ if (!gone.length) return b
805
+ let kept = { ...b }
806
+ for (let [n] of gone) delete kept[n]
807
+ return kept
808
+ })
809
+ }
810
+ let identity = (eids: string[], comps?: string[]) =>
811
+ get(driver, vocab, eids, opts(), comps, unsettled)
812
+ let report = base.report ?? logged
813
+ // Whether this store's vocabulary declares archetypes, so its queries are
814
+ // planned by them and its reads show them. Their descriptors are never
815
+ // numbered: no component of theirs declares a letter.
816
+ let classified = !!vocab.comp('archetype') && keeping
817
+ let memo = memoized(driver, vocab, base.derived, base.memory)
818
+ // A query's rows, from memory while the tables its answer stands on are
819
+ // unwritten (./memo.ts `answer`), in the one snapshot that decides both. A
820
+ // Where a caller's options leave a read's entities as the store's own get
821
+ // reads them, the get to read them through.
822
+ let policies = (o: Opts, within = false): string[] | undefined => {
823
+ let tables = new Set(within ? ['tombstone'] : ['entity', 'tombstone'])
824
+ let scope = o.visibility
825
+ for (
826
+ let query of [scope?.entity, ...Object.values(scope?.components ?? {})]
827
+ ) {
828
+ if (!query) continue
829
+ let names = basis(vocab, ast(query), base.derived, false, within)
830
+ if (!names) return undefined
831
+ for (let name of names) tables.add(name)
832
+ }
833
+ for (let name of Object.keys(scope?.components ?? {})) tables.add(name)
834
+ return [...tables]
835
+ }
836
+ let reading = (o: Opts, fetch = cached): ReadCache => ({
837
+ fetch: (eids, comps) => fetch(eids, comps, false),
838
+ permit: (eids, components, run, graves) => {
839
+ if (!eids.length) return []
840
+ let selected = new Set(eids)
841
+ let queries = [
842
+ o.visibility?.entity,
843
+ ...components.map((c) => o.visibility?.components?.[c]),
844
+ ].filter((q) => !!q)
845
+ let compiled = queries.map((q) => tested(ast(q!), true))
846
+ let tests = compiled.every((t) => !!t) ? compiled as Filter[] : undefined
847
+ let test: Filter | undefined = tests &&
848
+ ((b) => selected.has(b.entity.eid) && tests.every((t) => t(b)))
849
+ let names = queries.flatMap((q) =>
850
+ basis(vocab, ast(q!), base.derived) ?? []
851
+ )
852
+ if (tests && policies(o)) {
853
+ let found = fetch(eids, [...new Set(names)])
854
+ // A deleted entity is judged by its history, which only the store's
855
+ // statement reads (@yaks/sql `ghostly`).
856
+ let history = Object.values(o.backed ?? base.backed ?? {}).some((b) =>
857
+ b.held && b.about
858
+ )
859
+ if (!graves || !found.some(dead) || !history) {
860
+ return found.filter((b) => !dead(b) && test!(b)).map((b) => ({
861
+ eid: b.entity.eid,
862
+ }))
863
+ }
864
+ }
865
+ return memo.answer(
866
+ JSON.stringify(['permit', eids, components, o.visibility, !!graves]),
867
+ () => policies(o),
868
+ run,
869
+ () => ({ query: graves ? undefined : test, membership: true }),
870
+ )
871
+ },
872
+ })
873
+ let known = (o: Opts) =>
874
+ Object.keys(o).every((k) => UNREAD.has(k) || k == 'visibility')
875
+ let virtual = (eids: string[], o: Opts) =>
876
+ Object.values(o.tags ?? {}).some((tag) =>
877
+ eids.some((eid) => idOf(tag, eid) != null)
878
+ )
879
+ let reused = (
880
+ eids: string[],
881
+ comps: string[] | undefined,
882
+ o: Opts,
883
+ run: () => Bundle[],
884
+ pending: string[] = owing(),
885
+ ) => {
886
+ if (!policies(o) || virtual(eids, o)) return run()
887
+ // Registries are fixed per store. A per-call replacement is unknown and
888
+ // bypasses reuse; the remaining effective inputs belong in the key, the
889
+ // long lists of names as their numbers (@yaks/sql `listed`).
890
+ let key = () => {
891
+ let {
892
+ derived: _d,
893
+ backed: _b,
894
+ tags: _t,
895
+ extend: _e,
896
+ archetypes: _a,
897
+ absent,
898
+ missingIndexes,
899
+ ...inputs
900
+ } = o
901
+ return keyed([
902
+ 'get',
903
+ eids,
904
+ comps,
905
+ inputs,
906
+ pending,
907
+ listed(absent),
908
+ listed(missingIndexes),
909
+ ])!
910
+ }
911
+ return memo.view(key, run, comps)
912
+ }
913
+ let kept = (
914
+ fetch: (eids: string[], comps?: string[]) => Bundle[],
915
+ eids: string[],
916
+ comps?: string[],
917
+ refresh = true,
918
+ pending: string[] = owing(),
919
+ ) => {
920
+ let o = opts()
921
+ let run = () =>
922
+ o.visibility || virtual(eids, o)
923
+ ? fetch(eids, comps)
924
+ : memo.get(fetch, eids, comps, refresh)
925
+ return refresh ? reused(eids, comps, o, run, pending) : run()
926
+ }
927
+ let cached = (eids: string[], comps?: string[], refresh = true) =>
928
+ kept(identity, eids, comps, refresh)
929
+ let viewed = (
930
+ eids: string[],
931
+ comps: string[] | undefined,
932
+ o: Opts,
933
+ fetch = cached,
934
+ pending: string[] = owing(),
935
+ answered = false,
936
+ ) => {
937
+ let effective = { ...opts(), ...o }
938
+ let eligible = known(o)
939
+ // With no policy to apply, an option the statement is the same under
940
+ // leaves an identity read as memory holds it.
941
+ if (!effective.visibility && eligible) return fetch(eids, comps)
942
+ let run = () =>
943
+ get(
944
+ driver,
945
+ vocab,
946
+ eids,
947
+ effective,
948
+ comps,
949
+ unsettled,
950
+ eligible && !base.visibility && !virtual(eids, effective)
951
+ ? reading(effective, fetch)
952
+ : undefined,
953
+ answered,
954
+ )
955
+ return eligible ? reused(eids, comps, effective, run, pending) : run()
956
+ }
957
+ let fetched = (
958
+ o: Opts = {},
959
+ fetch = cached,
960
+ pending: () => string[] = owing,
961
+ ) =>
962
+ Object.keys(o).every((k) =>
963
+ k != 'now' && (UNREAD.has(k) || k == 'visibility')
964
+ )
965
+ ? (eids: string[], comps?: string[], answered?: boolean) =>
966
+ viewed(eids, comps, o, fetch, pending(), answered)
967
+ : undefined
968
+ let tests = new WeakMap<And, Map<boolean, Filter | undefined>>()
969
+ let tested = (query: And, exactIds = false): Filter | undefined => {
970
+ let known = Object.isFrozen(query) ? tests.get(query) : undefined
971
+ if (known?.has(exactIds)) return known.get(exactIds)
972
+ let test: Filter | undefined
973
+ if (basis(vocab, query, base.derived) && local(vocab, query)) {
974
+ try {
975
+ test = filter(query, vocab, { exactIds })
976
+ } catch {
977
+ // SQL decides predicates the local matcher cannot judge.
978
+ }
979
+ }
980
+ if (Object.isFrozen(query)) {
981
+ if (!known) tests.set(query, known = new Map())
982
+ known.set(exactIds, test)
983
+ }
984
+ return test
985
+ }
986
+ let resolved = (query: And, o: Opts): BindOpts['references'] => {
987
+ if (!o.visibility?.entity) return undefined
988
+ let operands = new Set<string>()
989
+ let visit = (c: Clause): void => {
990
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.forEach(visit)
991
+ // A path through a reference, or one read from the far side
992
+ // (`.members_space.member.person=P`), compares no reference of its own.
993
+ if (
994
+ c.kind != 'pred' || c.where || c.op != '=' ||
995
+ !literals(c.value)?.length || c.path.length > 2 ||
996
+ vocab.assoc(c.path[0])
997
+ ) return
998
+ let hops = vocab.aim(c.path.join('.'), bare(c)), h = hops[0]
999
+ let prop = h && vocab.prop(h.comp, h.prop)
1000
+ if (
1001
+ hops.length != 1 || !prop?.ref || prop.computed ||
1002
+ base.derived?.[`${h.comp}.${h.prop}`] || vocab.comp(prop.ref)?.computed
1003
+ ) return
1004
+ for (let eid of literals(c.value)!) operands.add(eid)
1005
+ }
1006
+ visit(query)
1007
+ if (!operands.size) return undefined
1008
+ let eids = [...operands]
1009
+ // A deleted entity the scope sees is admitted too, so its history is
1010
+ // asked by its id (@yaks/sql `ghostly`).
1011
+ let allowed = reading(o).permit(
1012
+ eids,
1013
+ [],
1014
+ () =>
1015
+ driver.query(
1016
+ admitted(
1017
+ eids,
1018
+ sourceScreen(readingVocab(driver, vocab), {
1019
+ ...opts(),
1020
+ ...o,
1021
+ graves: true,
1022
+ }),
1023
+ ),
1024
+ ),
1025
+ true,
1026
+ )
1027
+ let ids = spines(driver, allowed.map((r) => String(r.eid)))
1028
+ return Object.fromEntries(
1029
+ eids.map((eid) => [eid, ids.get(eid)?.id ?? null]),
1030
+ )
1031
+ }
1032
+ let asked = (query: And, o: Opts = {}): Row[] => {
1033
+ let catalogued = keeping
1034
+ let owing = catalogued && !!book?.owed().length
1035
+ // A read asking for graves is the statement's: it alone judges the
1036
+ // deleted (@yaks/sql `ghostly`).
1037
+ if (
1038
+ o.visibility && !owing && !o.graves && simple(vocab, query) &&
1039
+ !Object.keys(o.visibility.components ?? {}).length &&
1040
+ (!o.visibility.entity || local(vocab, ast(o.visibility.entity))) &&
1041
+ policies(o) && basis(vocab, query, base.derived, catalogued)
1042
+ ) {
1043
+ let { visibility: _visibility, ...plain } = o
1044
+ let raw = asked(query, plain)
1045
+ let permitted = new Set(
1046
+ reading(o).permit(raw.map((r) => String(r.eid)), [], () => []).map((
1047
+ r,
1048
+ ) => String(r.eid)),
1049
+ )
1050
+ return raw.filter((r) => permitted.has(String(r.eid)))
1051
+ }
1052
+ // What a caller's options change of the statement: its order of pages; a
1053
+ // `now` matters only to time phrases, which are read every time.
1054
+ let unread = Object.keys(o).some((k) => !UNREAD.has(k) && k != 'visibility')
1055
+ let tables: string[] | undefined
1056
+ let dependencies = () => {
1057
+ tables = basis(vocab, query, base.derived, catalogued)
1058
+ if (o.visibility) {
1059
+ let scoped = policies(o, !!tables && !tables.includes('entity'))
1060
+ tables = tables && scoped
1061
+ ? [...new Set([...tables, ...scoped])]
1062
+ : undefined
1063
+ }
1064
+ return tables
1065
+ }
1066
+ let key = JSON.stringify([
1067
+ query,
1068
+ !!o.storageOrder,
1069
+ !!o.unordered,
1070
+ o.visibility,
1071
+ ])
1072
+ let prove = () => {
1073
+ // A retained proof reads the same query and policy even if a caller
1074
+ // later edits the AST or visibility object it handed this read.
1075
+ let [query, , , visibility] = JSON.parse(key) as [
1076
+ And,
1077
+ boolean,
1078
+ boolean,
1079
+ Opts['visibility'],
1080
+ ]
1081
+ let o = { visibility }
1082
+ let standing: And | Filter | undefined = query
1083
+ let strict: string[] | undefined
1084
+ let shape: Filter | undefined
1085
+ let identities = (c: Clause): boolean =>
1086
+ c.kind == 'and' || c.kind == 'or'
1087
+ ? c.clauses.every(identities)
1088
+ : c.kind == 'pred' && !c.where || c.kind == 'every'
1089
+ let fixed = (c: Clause): boolean => {
1090
+ if (c.kind == 'and' || c.kind == 'or') return c.clauses.every(fixed)
1091
+ if (c.kind != 'pred') return true
1092
+ let leaf = vocab.aim(c.path.join('.'), bare(c)).at(-1)
1093
+ return !leaf || vocab.prop(leaf.comp, leaf.prop)?.category != 'ref' ||
1094
+ !c.not && c.op == '=' && !!literals(c.value)?.length
1095
+ }
1096
+ if (o.visibility) {
1097
+ let policy = o.visibility.entity
1098
+ let proof = basis(vocab, query, base.derived) && rooted(vocab, query)
1099
+ // Aspect policies can change what a predicate reads. A whole-entity
1100
+ // policy instead composes with an ordinary local membership test.
1101
+ if (
1102
+ !Object.keys(o.visibility.components ?? {}).length &&
1103
+ (local(vocab, query) || !!proof) &&
1104
+ (!policy || local(vocab, ast(policy)))
1105
+ ) {
1106
+ let ordinary = tested(query) ?? (proof ? proof.test : undefined)
1107
+ if (ordinary && !fixed(query)) ordinary = undefined
1108
+ let allowed = policy && tested(ast(policy), true)
1109
+ standing = ordinary && (!policy || allowed)
1110
+ ? (b) => ordinary(b) && (!allowed || allowed(b))
1111
+ : undefined
1112
+ if (standing && proof) shape = proof.shape
1113
+ // A reference's target can become hidden without its source changing.
1114
+ // Local source predicates cannot prove that policy change irrelevant.
1115
+ if (!simple(vocab, query)) {
1116
+ let scope = policies(o, !!tables && !tables.includes('entity'))
1117
+ strict = scope && [
1118
+ ...new Set([
1119
+ ...scope,
1120
+ ...proof ? proof.strict : [],
1121
+ ]),
1122
+ ]
1123
+ }
1124
+ } else standing = undefined
1125
+ }
1126
+ return {
1127
+ query: standing,
1128
+ membership: identities(query) && local(vocab, query),
1129
+ strict,
1130
+ shape,
1131
+ }
1132
+ }
1133
+ return unit(driver, () =>
1134
+ memo.answer(
1135
+ key,
1136
+ owing || unread ? undefined : dependencies,
1137
+ () =>
1138
+ rows(driver, vocab, query, {
1139
+ ...opts(),
1140
+ ...o,
1141
+ references: resolved(query, o) ?? o.references,
1142
+ }),
1143
+ prove,
1144
+ ), 'read')
1145
+ }
1146
+ let holding = (eids: string[]) => {
1147
+ if (!base.held) return heldBy(driver, eids, book, mend)
1148
+ let ids = [...spines(driver, eids).values()].map((r) => r.id)
1149
+ return [...new Set([...base.held(ids, tables(vocab)).values()].flat())]
1150
+ }
1151
+ let graves = burying(driver, vocab)
1152
+ let tx: Tx = {
1153
+ read: (query, signalled, comps) => {
1154
+ let o = asking(signalled)
1155
+ return metered(() =>
1156
+ read(
1157
+ driver,
1158
+ vocab,
1159
+ query,
1160
+ { ...opts(), ...o },
1161
+ comps,
1162
+ (q) => asked(q, o),
1163
+ fetched(o),
1164
+ unsettled,
1165
+ ), { what: named(query) })
1166
+ },
1167
+ get: identity,
1168
+ // The cascade reads the file as this snapshot's reads do (./reader.ts):
1169
+ // a property read as derived has no column there to point back through.
1170
+ doom: (eids) => {
1171
+ let o = opts()
1172
+ return doom(driver, vocab, eids, {
1173
+ absent: o.absent,
1174
+ lacking: Object.keys(o.derived ?? {}),
1175
+ unindexed: o.missingIndexes,
1176
+ })
1177
+ },
1178
+ // A rule reads the file as this snapshot's reads do: a word no write
1179
+ // has raised a table for, or a property derived from one, reads as worn
1180
+ // by nobody (./raise.ts).
1181
+ bindings: (matches, bundles, covers) =>
1182
+ bindings(driver, vocab, matches, bundles, covers, opts()),
1183
+ patch: (given) => {
1184
+ let bundles = readied(given)
1185
+ return made(memo.patch(
1186
+ bundles,
1187
+ (known) =>
1188
+ patch(
1189
+ driver,
1190
+ vocab,
1191
+ bundles,
1192
+ base.number,
1193
+ undefined,
1194
+ known,
1195
+ undefined,
1196
+ undefined,
1197
+ base.names,
1198
+ ),
1199
+ ))
1200
+ },
1201
+ remove: (entities) => {
1202
+ let at = new Date().toISOString()
1203
+ memo.removes(
1204
+ entities.map((e) => e.eid),
1205
+ at,
1206
+ () =>
1207
+ remove(
1208
+ driver,
1209
+ vocab,
1210
+ entities,
1211
+ holding(entities.map((e) => e.eid)),
1212
+ at,
1213
+ ),
1214
+ )
1215
+ },
1216
+ // Bookkeeping leaves whole: rows, identity and all (./write.ts `erase`).
1217
+ discard: (entities) => {
1218
+ let eids = entities.map((e) => e.eid)
1219
+ memo.writes(() => erase(driver, entities, holding(eids)), () => eids)
1220
+ },
1221
+ revive: (eids) => memo.writes(() => revive(driver, eids), () => eids),
1222
+ prune: (eids) => memo.writes(() => prune(driver, vocab, eids), () => eids),
1223
+ buried: (before, page) => graves(before, page),
1224
+ }
1225
+ // An entity met with no archetype to go by is a failure: every door
1226
+ // classifies what it wrote before its unit closes. It is reported, and
1227
+ // repaired by classifying it from the rows it holds, the one place a table
1228
+ // is asked what it holds (./archetype.ts `classify`).
1229
+ // One wording, so it is one bug wherever it is told; the entities ride
1230
+ // beside it.
1231
+ let lost = (eids: string[]) =>
1232
+ report(Object.assign(
1233
+ new Error(
1234
+ 'entities had no archetype, and were classified from the rows held',
1235
+ ),
1236
+ { name: 'Unpointed', eids: eids.slice(0, 8) },
1237
+ ))
1238
+ let mend = (eids: string[]) => {
1239
+ if (!migrating()) lost(eids)
1240
+ memo.writes(
1241
+ () => unit(driver, () => classify(driver, eids)),
1242
+ () => eids,
1243
+ true,
1244
+ )
1245
+ }
1246
+ // A read, and once more after the repair where it met such an entity. A
1247
+ // store that cannot write (a mode's) only reports.
1248
+ let mending = <R>(read: () => R): R => {
1249
+ try {
1250
+ return read()
1251
+ } catch (e) {
1252
+ if (!(e instanceof Unpointed) || !keeping) throw e
1253
+ mend(e.eids)
1254
+ return read()
1255
+ }
1256
+ }
1257
+ // Every unit keeps every pointer in step, whichever door wrote:
1258
+ // @yaks/graph's tracker, a hook writing through a detached transaction, a
1259
+ // script patching through `tx`. The connection's ledger hears each row that
1260
+ // came or went and each pointer written (./archetype.ts `ledger`); what it
1261
+ // still owes when the body returns is classified in the same unit, each
1262
+ // entity from its pointer and what the ledger heard, so no table is read.
1263
+ // Through the graph that is nothing, since its tracker points every entity
1264
+ // it moved, so its writes gain no read. Removal clears the tables its
1265
+ // entities hold (`heldBy`); the dead no pointer has been written for since
1266
+ // are pointed at the tombstone set (`entomb`), which reads nothing.
1267
+ //
1268
+ // A unit opened inside another (a graph applied in a caller's transaction)
1269
+ // shares the ledger, which follows the connection's savepoints: it reads
1270
+ // and removes what an entity holds rather than what its pointer said before
1271
+ // the outer one began, and settles whatever the transaction owes so far.
1272
+ let tracked = (book: Ledger): { tx: Tx; settle: () => void } => {
1273
+ let l = book
1274
+ // A birth is minted in the class its shape last finished in, and its
1275
+ // pointer is written again only where it finishes elsewhere.
1276
+ let remembered = births(driver)
1277
+ let born = {
1278
+ ...remembered,
1279
+ born: (eid: string, tables: string[], id?: number) => {
1280
+ remembered.born(eid, tables, id)
1281
+ l.born(eid)
1282
+ },
1283
+ }
1284
+ let owed = l.owed
1285
+ // An entity whose rows moved in this transaction is read from what it
1286
+ // holds; every other one as its pointer says, or from memory.
1287
+ let getting = (
1288
+ eids: string[],
1289
+ comps?: string[],
1290
+ refresh = true,
1291
+ ): Bundle[] => {
1292
+ let pending = owed()
1293
+ let moving = new Set(pending)
1294
+ let moved = eids.filter((eid) => moving.has(eid))
1295
+ if (!moved.length) return cached(eids, comps, refresh)
1296
+ let rest = eids.filter((eid) => !moving.has(eid))
1297
+ let at = new Map(
1298
+ [
1299
+ ...kept(
1300
+ (ids, names) => get(driver, vocab, ids, opts(), names, unsettled),
1301
+ moved,
1302
+ comps,
1303
+ refresh,
1304
+ pending,
1305
+ ),
1306
+ ...rest.length ? cached(rest, comps, refresh) : [],
1307
+ ].map((b) => [b.entity.eid, b]),
1308
+ )
1309
+ return eids.flatMap((eid) => at.get(eid) ?? [])
1310
+ }
1311
+ let settle = () => {
1312
+ let dead = l.buried()
1313
+ // A birth minted in the class it finished in owes no pointer, and
1314
+ // nothing is asked of the file for it.
1315
+ let owed = l.owed().filter((eid) => {
1316
+ let held = l.held(eid, null)
1317
+ if (!held || !remembered.settled(eid, held)) return true
1318
+ if (classified) memo.pointed(eid, setOf(driver, held).eid)
1319
+ l.pointed(eid)
1320
+ return false
1321
+ })
1322
+ if (!dead.length && !owed.length) return
1323
+ let unknown: string[] = []
1324
+ memo.writes(
1325
+ () => {
1326
+ let buried = entomb(driver, dead)
1327
+ let sorted = classify(driver, owed, (eid, pointed) => {
1328
+ let held = l.held(eid, pointed)
1329
+ if (!held) unknown.push(eid)
1330
+ return held
1331
+ }, remembered.finished)
1332
+ return buried || sorted
1333
+ },
1334
+ // A pointer is part of what a read gives only where the store shows
1335
+ // archetypes: elsewhere what memory holds of these entities stands.
1336
+ () => classified ? [...dead, ...owed] : [],
1337
+ // A class first worn mints its descriptor (./archetype.ts), an
1338
+ // entity the write does not name; one a store shows no reader of.
1339
+ (minted) => classified && minted,
1340
+ )
1341
+ if (unknown.length && !migrating()) lost(unknown)
1342
+ for (let eid of [...dead, ...owed]) l.pointed(eid)
1343
+ }
1344
+ return {
1345
+ tx: {
1346
+ ...tx,
1347
+ get: (eids, comps) => mending(() => getting(eids, comps)),
1348
+ // Queries overlay the shapes the open writer knows on its catalog;
1349
+ // no intermediate classification is persisted to answer a read.
1350
+ read: (query, signalled, comps) => {
1351
+ if (!owed().length) {
1352
+ return mending(() => tx.read(query, signalled, comps))
1353
+ }
1354
+ let o = asking(signalled)
1355
+ let archetypes = migrating()
1356
+ ? unindexed
1357
+ : catalog(driver, pendingShapes(driver, book))
1358
+ let bound = { ...opts(), ...o, archetypes }
1359
+ return metered(
1360
+ () =>
1361
+ mending(() =>
1362
+ read(
1363
+ driver,
1364
+ vocab,
1365
+ query,
1366
+ bound,
1367
+ comps,
1368
+ (q) => rows(driver, vocab, q, bound),
1369
+ fetched(o, getting, owed),
1370
+ unsettled,
1371
+ )
1372
+ ),
1373
+ { what: named(query) },
1374
+ )
1375
+ },
1376
+ patch: (given) => {
1377
+ let bundles = readied(given)
1378
+ let minted = made(memo.patch(
1379
+ bundles,
1380
+ (known) =>
1381
+ patch(
1382
+ driver,
1383
+ vocab,
1384
+ bundles,
1385
+ base.number,
1386
+ l.moved,
1387
+ known,
1388
+ born,
1389
+ unsettled,
1390
+ base.names,
1391
+ ),
1392
+ ))
1393
+ for (let b of bundles) {
1394
+ if (b.entity.archetype !== undefined) l.pointed(b.entity.eid)
1395
+ }
1396
+ return minted
1397
+ },
1398
+ prune: (eids) => {
1399
+ settle()
1400
+ tx.prune(eids)
1401
+ },
1402
+ remove: (entities) => {
1403
+ let eids = entities.map((e) => e.eid)
1404
+ let at = new Date().toISOString()
1405
+ memo.removes(
1406
+ eids,
1407
+ at,
1408
+ () =>
1409
+ remove(
1410
+ driver,
1411
+ vocab,
1412
+ entities,
1413
+ heldBy(driver, eids, l, mend),
1414
+ at,
1415
+ ),
1416
+ )
1417
+ for (let eid of eids) l.removed(eid)
1418
+ },
1419
+ // Erased, an entity leaves nothing to point: the ledger forgets it.
1420
+ discard: (entities) => {
1421
+ let eids = entities.map((e) => e.eid)
1422
+ memo.writes(
1423
+ () => erase(driver, entities, heldBy(driver, eids, l, mend)),
1424
+ () => eids,
1425
+ )
1426
+ for (let eid of eids) l.pointed(eid)
1427
+ },
1428
+ revive: (eids) =>
1429
+ memo.writes(() => revive(driver, eids, l.moved), () => eids),
1430
+ },
1431
+ settle,
1432
+ }
1433
+ }
1434
+ // A file store is brought to its schema by its host as it opens
1435
+ // (./follow.ts), never by an operation.
1436
+ // In-memory stores are private scratch values and may prepare themselves.
1437
+ let ready = false
1438
+ let prepare = () => base.deferred ? upkeep.prepare() : backfill(driver)
1439
+ // A store numbering by series moves a spine that keeps a number unique on
1440
+ // its own (./ddl.ts `respine`), before the indexes on it are raised. The
1441
+ // move writes only the numbered rows, once each, and no reference to them
1442
+ // is checked, so a Durable Object's directory of 43,000 moves in its
1443
+ // install. A file's spine is moved by its host's migration.
1444
+ let respining = () => !!base.number && !driver.file && sole(driver)
1445
+ // Counts eager are made by install; lazy ones by the first count asked, but
1446
+ // where they stand, install mends what keeps them, as a new print
1447
+ // (`POPULATION_VERSION`) owes.
1448
+ let counted = () => {
1449
+ if (!classified || base.counts != 'eager' && !torn(driver)) return
1450
+ unit(driver, () => population(driver))
1451
+ }
1452
+ let install = (beside: Stmt[] = []): Error[] => {
1453
+ storeAs(driver, vocab)
1454
+ let left: Error[] = []
1455
+ let mark = marked
1456
+ let print = printed()
1457
+ let receipt: ReturnType<typeof installation>
1458
+ let matches = () => {
1459
+ receipt = installation(driver)
1460
+ let was = receipt?.schema
1461
+ return was == mark(was?.split(' ').slice(2) ?? []) && !respining()
1462
+ }
1463
+ // The fast path only reads. A changed file is inspected again *after*
1464
+ // taking its write lock, and tables, growth and indexes commit together.
1465
+ let unchanged = matches()
1466
+ if (!unchanged) {
1467
+ let clean = false
1468
+ let seal = () => {
1469
+ epoch(driver)
1470
+ recorded(driver)
1471
+ if (keeping) prepare()
1472
+ receipt = {
1473
+ schema: mark(
1474
+ componentTables(
1475
+ driver,
1476
+ plan(vocab, base.derived, !!driver.file).made,
1477
+ ),
1478
+ ),
1479
+ statistics: receipt?.statistics,
1480
+ }
1481
+ meta(driver).set(SCHEMA, receipt.schema)
1482
+ }
1483
+ let make = () =>
1484
+ unit(driver, () => {
1485
+ if (matches()) return
1486
+ // Retired first: a component may take a name an index held.
1487
+ for (let stmt of base.partial ? [] : retired(driver, vocab)) {
1488
+ driver.query(stmt)
1489
+ }
1490
+ // A component's own objects wait for its first write (./raise.ts).
1491
+ let tables = holds(
1492
+ driver,
1493
+ vocab,
1494
+ retabled(driver, vocab, base.derived),
1495
+ )
1496
+ erect(driver, tables)
1497
+ let after = (comp: string) =>
1498
+ [...tables, ...indexed(vocab, true), ...beside].filter((s) =>
1499
+ (s.t == 'create index' || s.t == 'create trigger') && s.on == comp
1500
+ )
1501
+ let kept = new Set<string>()
1502
+ let unfit = fit(driver, vocab, (comp, r) => {
1503
+ let owes = reshape(driver, comp, r, after(comp), base.sizes)
1504
+ if (owes) kept.add(comp)
1505
+ return owes
1506
+ })
1507
+ forgo(driver, kept)
1508
+ left = [
1509
+ ...unfit,
1510
+ ...respining() ? respine(driver) : [],
1511
+ ...build(
1512
+ driver,
1513
+ holds(driver, vocab, built(driver, vocab)),
1514
+ base.sizes,
1515
+ base.deferred,
1516
+ ),
1517
+ ...besides.length ? versioned(driver, vocab, !!base.paced) : [],
1518
+ ]
1519
+ left.forEach(report)
1520
+ clean = !left.length
1521
+ // Memory templates keep schema, never a store's lineage identity.
1522
+ if (driver.file && clean) seal()
1523
+ })
1524
+ // Tables are rebuilt with foreign keys on. A rebuilt table is a
1525
+ // component's: it references `entity` and nothing references it, so
1526
+ // dropping it checks nothing and each row put back finds its entity.
1527
+ // The pragma is never set here: SQLite ignores it inside a transaction,
1528
+ // and workerd holds one open from a turn's first write, so an `on` after
1529
+ // the rebuild could leave a Durable Object without its keys.
1530
+ // Templates are only for fresh in-memory files; file installs always
1531
+ // inspect their standing schema under BEGIN IMMEDIATE.
1532
+ let fresh = !installed(driver) &&
1533
+ !anyStanding(driver, vocab)
1534
+ fresh && driver.template ? driver.template(print, make) : make()
1535
+ if (!driver.file) {
1536
+ unit(driver, () => {
1537
+ epoch(driver)
1538
+ recorded(driver)
1539
+ if (keeping) prepare()
1540
+ if (fresh || clean) {
1541
+ receipt = {
1542
+ schema: mark(
1543
+ componentTables(
1544
+ driver,
1545
+ plan(vocab, base.derived, !!driver.file).made,
1546
+ ),
1547
+ ),
1548
+ statistics: receipt?.statistics,
1549
+ }
1550
+ meta(driver).set(SCHEMA, receipt.schema)
1551
+ }
1552
+ })
1553
+ }
1554
+ }
1555
+ counted()
1556
+ let owe = () => {
1557
+ let statistics = analyzed(driver, receipt?.statistics, unchanged)
1558
+ if (statistics && receipt) analyzedAt(driver, receipt.schema, statistics)
1559
+ }
1560
+ // A file asks what it owes without the write lock, and takes it only when
1561
+ // there is a receipt to write and nobody holds it: beside another
1562
+ // connection's writer the open goes on without waiting, and the next open
1563
+ // finds the same debt from the file (./owe.ts).
1564
+ let owing = () => analyzed(driver, receipt?.statistics, unchanged)
1565
+ if (driver.statistics && !driver.file) unit(driver, owe)
1566
+ else if (driver.statistics && unit(driver, owing, 'read')) {
1567
+ try {
1568
+ unwaiting(driver, () => unit(driver, owe))
1569
+ } catch (e) {
1570
+ if (!busy(e)) throw e
1571
+ }
1572
+ }
1573
+ ready = true
1574
+ return left
1575
+ }
1576
+ let ensure = () => {
1577
+ if (driver.file || ready) return
1578
+ if (base.schemaReady?.()) ready = true
1579
+ else install()
1580
+ }
1581
+ // What a write minted: on a branch, each pointed as main sees it.
1582
+ let made = base.mode && 'branch' in base.mode
1583
+ ? (minted: Entity[]) => (unborn(driver, minted.map((e) => e.eid)), minted)
1584
+ : (minted: Entity[]) => minted
1585
+ // A store with history has branches; a mode's store is a branch's,
1586
+ // or reads the past.
1587
+ let branches = base.history && !base.mode
1588
+ ? branching(driver, vocab, base.history, opts)
1589
+ : undefined
1590
+ return {
1591
+ ...branches ? { branches } : {},
1592
+ statements: keeping
1593
+ ? Object.assign(statements(driver), { archetypes: true })
1594
+ : base.mode
1595
+ ? {
1596
+ ...statements(driver),
1597
+ archetypes: false,
1598
+ // A mode's driver is bound to another mode under the store
1599
+ // (./mode.ts).
1600
+ get mode() {
1601
+ return base.mode
1602
+ },
1603
+ }
1604
+ : statements(driver),
1605
+ checks: diagnostics(driver),
1606
+ migrations: migrations(driver),
1607
+ maintain: upkeep.work,
1608
+ revision: () => revision(driver, 'data'),
1609
+ newest: (comp: string) => newest(driver, vocab, comp),
1610
+ ...driver.watch
1611
+ ? {
1612
+ watch: (comp: string, heard: () => void) =>
1613
+ watch(driver, vocab, comp, heard),
1614
+ }
1615
+ : {},
1616
+ worn: worn(vocab, base.derived),
1617
+ // A caller replaying these statements over a standing file must add new
1618
+ // columns before creating their indexes. `schema()` alone describes a
1619
+ // fresh file; it cannot see what a standing table still lacks.
1620
+ ddl: () => [
1621
+ ...tabled(vocab, base.derived, !!driver.file),
1622
+ ...grown(vocab, standing(driver, vocab)),
1623
+ ...indexed(vocab, true),
1624
+ ],
1625
+ grown: () => grown(vocab, standing(driver, vocab)),
1626
+ print: printed,
1627
+ install,
1628
+ raise: (comps = tables(vocab)) => {
1629
+ ensure()
1630
+ return unit(driver, () => raising(comps))
1631
+ },
1632
+ analyze: (tables = Infinity) => {
1633
+ if (driver.statistics) daily(driver, [statistics], Date.now())
1634
+ let left = installation(driver)?.statistics?.owed?.length ?? 0
1635
+ for (let n = 0; n < tables && left; n++) left = analyze(driver) ?? 0
1636
+ return left
1637
+ },
1638
+ read: (query, o, comps) => {
1639
+ ensure()
1640
+ return metered(
1641
+ () =>
1642
+ mending(() => unit(driver, () => tx.read(query, o, comps), 'read')),
1643
+ { what: named(query) },
1644
+ )
1645
+ },
1646
+ rows: (query, signalled) => {
1647
+ ensure()
1648
+ let o = asking(signalled)
1649
+ let parsed = ast(query)
1650
+ if (
1651
+ classified && !owing().length && base.counts != 'eager' &&
1652
+ cardinality(parsed, vocab, { ...opts(), ...o })
1653
+ ) {
1654
+ unit(driver, () => population(driver))
1655
+ }
1656
+ return metered(() => mending(() => asked(parsed, o)), {
1657
+ what: named(query),
1658
+ })
1659
+ },
1660
+ screen: (query, o) => {
1661
+ ensure()
1662
+ return screened(driver, vocab, query, { ...opts(), ...asking(o) })
1663
+ },
1664
+ buried: (before, page) => {
1665
+ ensure()
1666
+ return unit(driver, () => graves(before, page), 'read')
1667
+ },
1668
+ get file() {
1669
+ return located(driver)
1670
+ },
1671
+ measure: (signal) => measure(driver, signal),
1672
+ get: (eids, comps, o) => {
1673
+ if (!eids.length) return []
1674
+ ensure()
1675
+ return metered(
1676
+ () =>
1677
+ mending(() =>
1678
+ unit(driver, () => viewed(eids, comps, asking(o) ?? {}), 'read')
1679
+ ),
1680
+ { what: gotten(eids) },
1681
+ )
1682
+ },
1683
+ purgeHistory: (eids) =>
1684
+ unit(driver, () => purgeHistory(driver, vocab, eids, opts())),
1685
+ retained: (values) => unit(driver, () => retained(driver, values), 'read'),
1686
+ purgeTrash: (id) =>
1687
+ unit(driver, () => {
1688
+ driver.query(purgeTrashSql(id))
1689
+ }),
1690
+ trash: (eids, page) =>
1691
+ unit(driver, () => trashed(driver, vocab, eids, page), 'read'),
1692
+ tx: <R>(
1693
+ body: (tx: Tx) => R,
1694
+ { wait }: { admission?: boolean; wait?: boolean } = {},
1695
+ ): R | Promise<Awaited<R>> =>
1696
+ exclusive(driver, () => {
1697
+ if (base.mode && 'at' in base.mode) {
1698
+ throw new Refused(
1699
+ `as of transaction ${base.mode.at} the graph is read only`,
1700
+ )
1701
+ }
1702
+ ensure()
1703
+ let run = (begun: () => void) =>
1704
+ unit(
1705
+ driver,
1706
+ (): R => {
1707
+ begun()
1708
+ return within(driver, (clock) => {
1709
+ let cached = (t: Tx): Tx => ({
1710
+ ...t,
1711
+ get: (eids, comps) => kept(t.get, eids, comps),
1712
+ ...base.history ? { clock } : {},
1713
+ })
1714
+ let retaining = (t: Tx): Tx =>
1715
+ preserving(t, vocab, (id, at, rows) => {
1716
+ for (let stmt of retainSql(id, at, rows)) driver.query(stmt)
1717
+ })
1718
+ if (!book) return body(retaining(cached(tx)))
1719
+ let { tx: t, settle } = tracked(book)
1720
+ let tracing = context()
1721
+ // An async body settles what it owes before the unit closes, as the
1722
+ // unit waits for it (./unit.ts).
1723
+ return after(
1724
+ body(retaining(base.history ? { ...t, clock } : t)),
1725
+ (out) => {
1726
+ if (tracing) scope(tracing, settle)
1727
+ else settle()
1728
+ return out
1729
+ },
1730
+ ) as R
1731
+ })
1732
+ },
1733
+ 'write',
1734
+ { wait: false, report },
1735
+ )
1736
+ return wait === false
1737
+ ? run(() => {})
1738
+ : enter(run, (ms) => sleep(ms, undefined, base.clock)) as
1739
+ | R
1740
+ | Promise<Awaited<R>>
1741
+ }),
1742
+ }
1743
+ }
1744
+
1745
+ export * from './migration.js'
1746
+ export {
1747
+ add,
1748
+ follow,
1749
+ forget,
1750
+ grow,
1751
+ lacking,
1752
+ type Named,
1753
+ printFor,
1754
+ printOf,
1755
+ type Seat,
1756
+ shed,
1757
+ unseat,
1758
+ } from './follow.js'
1759
+
1760
+ export { doom } from './doom.js'
1761
+ export { branch, branching, branchOf, seeding, Unseeded } from './branches.js'
1762
+ export { moded } from './mode.js'