@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/read.ts ADDED
@@ -0,0 +1,1441 @@
1
+ import { logicalVocab } from '@yaks/sql/core'
2
+ import { readingVocab } from './shape.js'
3
+ import { Unpointed } from './error.js'
4
+ import {
5
+ cardinality,
6
+ census,
7
+ classified,
8
+ installed,
9
+ POPULATION,
10
+ populationCount,
11
+ populations,
12
+ } from './population.js'
13
+ // Reads: a query in, whole entities out. This is the SELECT half of the
14
+ // adapter. The heavy lifting — turning a query into SQL — belongs to the
15
+ // sibling packages: @yaks/query parses the query text into an AST, @yaks/vocab
16
+ // describes the vocabulary, and @yaks/sql compiles the two into a statement
17
+ // that selects the matching entities' ids. This file runs that statement, then
18
+ // gathers each matched entity's components into a bundle.
19
+ //
20
+ // `rows()` is the raw form: it returns the compiled statement's rows verbatim,
21
+ // which is what aggregate and projection queries (a count, a tally, a field
22
+ // list) want. `read()` is the whole-entity form built on it: it takes the ids
23
+ // `rows()` returns and reads back every component each entity has.
24
+ // `screened()` is the statement alone, for a search beside the graph to run.
25
+
26
+ import { unraised } from './raise.js'
27
+ import { installed as received } from './meta.js'
28
+ import { field } from '@yaks/sql/query'
29
+ import { type And, map, parse } from '@yaks/query/core'
30
+ import type { Prop, Vocab } from 'jsr:@yaks/vocab@0.2.36'
31
+ import {
32
+ absentDerived,
33
+ among,
34
+ and,
35
+ as,
36
+ type Backings,
37
+ type BindOpts,
38
+ col,
39
+ compile,
40
+ cross,
41
+ type Cte,
42
+ type Derived,
43
+ derivedOf,
44
+ type Driver,
45
+ each,
46
+ eidAt,
47
+ eidOf,
48
+ eq,
49
+ exists,
50
+ type Expr,
51
+ fn,
52
+ from,
53
+ idOf,
54
+ type Join,
55
+ join,
56
+ left,
57
+ lit,
58
+ oneOf,
59
+ op,
60
+ pinned,
61
+ type Query as Sub,
62
+ type Raw,
63
+ render,
64
+ revision,
65
+ type Row,
66
+ screen,
67
+ type Select,
68
+ select,
69
+ setOf,
70
+ type Source,
71
+ sourceScreen,
72
+ storedOnly,
73
+ sub,
74
+ table,
75
+ tagged,
76
+ tagIn,
77
+ type Tags,
78
+ val,
79
+ visibleBacked,
80
+ visibleDerived,
81
+ } from '@yaks/sql/query'
82
+ import type { Bundle, Comp } from './bundle.ts'
83
+ import { sha256 } from '@yaks/graph/sha256'
84
+ import { tombstoned } from '@yaks/graph/bundle'
85
+ import { catalog, described as learn, descriptor } from './catalog.js'
86
+ import { unit } from './unit.js'
87
+ import { decoded, jsonOut, projected } from './jsonb.js'
88
+ import { tables } from './layout.js'
89
+
90
+ // A query, as text or as an already-built AST. Text is parsed; an AST passes
91
+ // through, so a caller may hand-build one with @yaks/query's builders.
92
+ export type Query = string | And
93
+
94
+ export let ast = (q: Query): And => typeof q == 'string' ? parse(q) : q
95
+
96
+ // The raw compiled rows for a query — a membership query returns `{ eid }` per
97
+ // match, an aggregate returns its value/count shape, and a `.fields`
98
+ // projection's columns come back as a component read would return them. The
99
+ // values are bound as parameters.
100
+ export let rows = (
101
+ driver: Driver,
102
+ vocab: Vocab,
103
+ query: Query,
104
+ opts: BindOpts = {},
105
+ ): Row[] => {
106
+ let ask = () => {
107
+ let parsed = ast(query)
108
+ // A store's counted populations are of the living.
109
+ let shape =
110
+ opts.graves || opts.archetypes?.pending || !vocab.comp('archetype')
111
+ ? undefined
112
+ : cardinality(parsed, vocab, opts)
113
+ if (
114
+ shape && (!opts.archetypes || opts.archetypes({}) != undefined) &&
115
+ classified(driver)
116
+ ) {
117
+ if (shape.tally || shape.archetype || opts.visibility?.entity) {
118
+ let buckets = populations(driver)?.filter((b) => {
119
+ let row = { entity: { eid: b.value, archetype: b.value } }
120
+ return shape.visible(b.tables) &&
121
+ (!shape.archetype || shape.archetype(row))
122
+ })
123
+ if (buckets) {
124
+ return shape.tally
125
+ ? buckets.map(({ value, n }) => ({ value, n }))
126
+ : [{
127
+ value: '',
128
+ n: buckets.reduce((n, b) =>
129
+ n + (!shape.comp || shape.comp == 'entity' ||
130
+ b.tables.includes(shape.comp)
131
+ ? b.n
132
+ : 0), 0),
133
+ }]
134
+ }
135
+ } else {
136
+ let n = populationCount(driver, shape.comp, shape.presence)
137
+ if (n != undefined) return [{ value: '', n }]
138
+ }
139
+ }
140
+ let population =
141
+ !opts.graves && !opts.archetypes?.pending && parsed.clauses.length == 1 &&
142
+ parsed.clauses[0].kind == 'tally' &&
143
+ parsed.clauses[0].path.join('.') == 'entity.archetype' &&
144
+ installed(driver) && classified(driver)
145
+ ? POPULATION
146
+ : undefined
147
+ let compiled = compile(
148
+ parsed,
149
+ readingVocab(driver, vocab),
150
+ catalogued(driver, vocab, {
151
+ ...opts,
152
+ population,
153
+ census: census(driver),
154
+ }),
155
+ )
156
+ // An answer proved without the engine (@yaks/sql `compile`) stands on a
157
+ // file that was installed: one that never was is refused by the engine,
158
+ // as a read of tables it does not hold.
159
+ let proved = compiled.answer && (!driver.file || received(driver) != null)
160
+ ? compiled.answer
161
+ : undefined
162
+ return (proved ?? driver.query(compiled)).map((r) =>
163
+ projected(vocab, r, parsed)
164
+ )
165
+ }
166
+ // The catalog and entity statement must see the same commit. Otherwise a
167
+ // concurrent writer could introduce a new matching set between the two. A
168
+ // read unit is one snapshot without the write lock, so a long query never
169
+ // makes a writer on another connection wait (./unit.ts).
170
+ return unit(driver, ask, 'read')
171
+ }
172
+
173
+ // A compile's options over this file: the caller's, and the file's archetype
174
+ // catalog where the vocabulary keeps one, so every presence and kind test is
175
+ // a lookup on the archetype index.
176
+ let catalogued = (driver: Driver, vocab: Vocab, opts: BindOpts): BindOpts => ({
177
+ ...opts,
178
+ archetypes: opts.archetypes ?? catalog(driver),
179
+ // Where the vocabulary declares none, the descriptors every file keeps
180
+ // (./ddl.ts) are the store's bookkeeping, and no entity of its graph.
181
+ ...vocab.comp('archetype') ? {} : { bookkeeping: KEPT },
182
+ stable: opts.stable ?? driver.stable,
183
+ })
184
+ let KEPT = ['archetype']
185
+
186
+ /**
187
+ * The entities a query admits, as a statement selecting their integer ids as
188
+ * `id` (@yaks/sql `screen`), compiled as this file's reads are: what a search
189
+ * run beside the graph is narrowed by. It names the archetypes that match now,
190
+ * so run it before anything else writes.
191
+ */
192
+ export let screened = (
193
+ driver: Driver,
194
+ vocab: Vocab,
195
+ query: Query,
196
+ opts: BindOpts = {},
197
+ ): Raw | null =>
198
+ screen(
199
+ ast(query),
200
+ readingVocab(driver, vocab),
201
+ catalogued(driver, vocab, opts),
202
+ )
203
+
204
+ // The properties a gather reads: the stored ones, plus any computed property
205
+ // the caller registered an expression for. A computed property has no row to
206
+ // read, so without a registration there is nothing to select — but with one it
207
+ // is a column like any other, and leaving it out of the bundle while the filter
208
+ // resolves it would make `.task.status=open` select rows whose `status` the
209
+ // result does not carry.
210
+ let read1 = (v: Vocab, comp: string, derived: Derived): Prop[] =>
211
+ v.props(comp).map((p) => v.prop(comp, p)!)
212
+ .filter((c) =>
213
+ (!c.computed || derived[`${comp}.${c.prop}`]) &&
214
+ derived[`${comp}.${c.prop}`]?.whole !== false
215
+ )
216
+
217
+ // The projected read for one component: each scalar straight off the row, each
218
+ // reference joined back to its target's eid, each JSON value as its JSON text
219
+ // (./jsonb.ts, parsed by `decoded` once the row is back), keyed by the owner
220
+ // eid. A component with no properties reads a bare presence flag.
221
+ //
222
+ // A property whose read differs from its storage is read through its registered
223
+ // expression instead — the same `derived` registry @yaks/sql consults when it
224
+ // compiles a query (see @yaks/sql/derived.ts). That is what keeps the two
225
+ // readers agreeing: a value the filter resolves one way cannot come back
226
+ // gathered another. It is also where a content-addressed property is
227
+ // resolved — @yaks/blob registers one override per body property, and the
228
+ // gather returns the text rather than the address the row holds.
229
+ //
230
+ // So the component table is aliased by its own name here, exactly as the binder
231
+ // joins it, and an override's `deps` are left-joined the same way: a registered
232
+ // expression is written once and reads the same in both places.
233
+ //
234
+ // A reference to a computed component's entity (the journal's `_change.tx`)
235
+ // reads as that entity's eid, written out from the id it holds: such an
236
+ // entity has no row in the entity table to join (@yaks/sql `Backing`).
237
+ //
238
+ // Read `named`, a reference reads as the id it holds instead, listed in
239
+ // `refs`: a set read names every id it found in one statement afterwards
240
+ // (`naming`), rather than joining the entity table once per row for an eid
241
+ // that most rows share.
242
+ //
243
+ // A reference to a backed entity reads the tag its eid ends with from the
244
+ // statement's binding (@yaks/sql `tagIn`), listed in `tagged`: the statement
245
+ // binds those (`tagging`), so one projection serves every store.
246
+ type Projection = {
247
+ sel: Expr[]
248
+ joins: Join[]
249
+ refs?: string[]
250
+ tagged?: string[]
251
+ }
252
+ let projection = (
253
+ v: Vocab,
254
+ comp: string,
255
+ derived: Derived,
256
+ backed: Backings,
257
+ tags: Tags,
258
+ named = false,
259
+ ): Projection => {
260
+ let own = (prop: string) => col(prop, comp)
261
+ let sel: Expr[] = []
262
+ let joins: Join[] = []
263
+ let refs: string[] = []
264
+ let reading = new Set<string>()
265
+ let deps = new Set<string>()
266
+ for (let c of read1(v, comp, derived)) {
267
+ let over = derived[`${comp}.${c.prop}`]
268
+ let tag = c.ref && backed[c.ref] && tags[c.ref] ? c.ref : undefined
269
+ if (over) {
270
+ for (let d of over.deps ?? []) deps.add(d)
271
+ let value = !c.computed && storedOnly(over, v)
272
+ ? over.text!(own(field(c.prop)))
273
+ : over.expr(own('entity'))
274
+ sel.push(as(value, c.prop))
275
+ } else if (tag) {
276
+ reading.add(tag)
277
+ sel.push(as(eidAt(tagIn(tag), own(field(c.prop))), c.prop))
278
+ } else if (c.category == 'ref' && named) {
279
+ refs.push(c.prop)
280
+ sel.push(as(own(field(c.prop)), c.prop))
281
+ } else if (c.category == 'ref') {
282
+ let a = `r_${c.prop.replaceAll(/[^A-Za-z0-9]/g, '_')}`
283
+ joins.push(left(table('entity', a), eq(col('id', a), own(field(c.prop)))))
284
+ sel.push(as(col('eid', a), c.prop))
285
+ } else if (c.scalar == 'jsonb') {
286
+ sel.push(as(jsonOut(own(field(c.prop))), c.prop))
287
+ } else {
288
+ sel.push(as(own(field(c.prop)), c.prop))
289
+ }
290
+ }
291
+ for (let d of deps) {
292
+ if (d == comp) continue
293
+ joins.push(left(table(d), eq(col('entity', d), own('entity'))))
294
+ }
295
+ return {
296
+ sel,
297
+ joins,
298
+ ...refs.length ? { refs } : {},
299
+ ...reading.size ? { tagged: [...reading] } : {},
300
+ }
301
+ }
302
+
303
+ // The `with` a statement reading `p` binds its tags in.
304
+ let tagging = (p: Projection, tags: Tags = {}): Cte[] =>
305
+ p.tagged ? tagged(tags, p.tagged) : []
306
+
307
+ // What `key` holds in `m`, made on first ask.
308
+ let at = <K, V>(
309
+ m: { get(k: K): V | undefined; set(k: K, v: V): unknown },
310
+ key: K,
311
+ make: () => V,
312
+ ): V => {
313
+ let v = m.get(key)
314
+ if (v === undefined) m.set(key, v = make())
315
+ return v
316
+ }
317
+
318
+ // A read's trees, kept per vocabulary and registries while they live. A store
319
+ // asks the same few reads thousands of times a session, and @yaks/sql renders
320
+ // a tree it has seen once, so only the part holding the ids is written again.
321
+ // The registries are built once per store and never changed.
322
+ let NONE = {}
323
+ let kept = new WeakMap<
324
+ object,
325
+ WeakMap<object, WeakMap<object, Map<string, Projection>>>
326
+ >()
327
+ // A status a vocabulary's ladder computes is read like any registered one
328
+ // (@yaks/sql `derivedOf`).
329
+ // The tags are each store's own, so only which components carry one keys it.
330
+ let project = (
331
+ v: Vocab,
332
+ comp: string,
333
+ derived: Derived = NONE,
334
+ backed: Backings = NONE,
335
+ tags: Tags = NONE,
336
+ named = false,
337
+ ): Projection => {
338
+ let all = derivedOf(v, derived)
339
+ return at(
340
+ at(
341
+ at(at(kept, v, () => new WeakMap()), all, () => new WeakMap()),
342
+ backed,
343
+ () => new Map(),
344
+ ),
345
+ `${named} ${comp} ${Object.keys(tags)}`,
346
+ () => projection(v, comp, all, backed, tags, named),
347
+ )
348
+ }
349
+
350
+ // The eids of the entities these ids are, in one statement: what a set read
351
+ // asks once for every reference its rows hold. An id no entity has stays
352
+ // unnamed, as a reference whose target is gone reads.
353
+ let naming = (driver: Driver, ids: Iterable<unknown>): Map<number, string> => {
354
+ let asked = [
355
+ ...new Set([...ids].flatMap((id) => id == null ? [] : [Number(id)])),
356
+ ]
357
+ if (!asked.length) return new Map()
358
+ return new Map(
359
+ driver.query(select({
360
+ cols: [col('id', 'e'), col('eid', 'e')],
361
+ ...owning(asked, table('entity', 'e'), col('id', 'e')),
362
+ })).map((r) => [Number(r.id), String(r.eid)]),
363
+ )
364
+ }
365
+ // A row's references, named.
366
+ let named = (
367
+ value: Row,
368
+ refs: string[] | undefined,
369
+ names: Map<number, string>,
370
+ ): Row => {
371
+ if (!refs) return value
372
+ let out = { ...value }
373
+ for (let prop of refs) {
374
+ out[prop] = out[prop] == null ? null : names.get(Number(out[prop])) ?? null
375
+ }
376
+ return out
377
+ }
378
+
379
+ /**
380
+ * The rows of `comp` that table `name` holds where `where` matches, each read
381
+ * as a whole read reads its component (references as eids, JSON parsed,
382
+ * booleans as booleans), by its owner's id. The table stands where the
383
+ * component's would, aliased by its name: its table of versions
384
+ * (./history.ts) does, so any version reads as the live row it was.
385
+ */
386
+ export let valuesOf = (
387
+ driver: Driver,
388
+ vocab: Vocab,
389
+ comp: string,
390
+ name: string,
391
+ where: Expr,
392
+ opts: BindOpts = {},
393
+ ): [number, Comp][] => {
394
+ let p = project(vocab, comp, opts.derived, opts.backed, opts.tags, true)
395
+ let rows = driver.query(select({
396
+ with: tagging(p, opts.tags),
397
+ cols: [as(col('entity', comp), '@id'), ...p.sel],
398
+ from: table(name, comp),
399
+ joins: p.joins,
400
+ where,
401
+ }))
402
+ let names = naming(
403
+ driver,
404
+ rows.flatMap((r) => p.refs?.map((x) => r[x]) ?? []),
405
+ )
406
+ return rows.map(({ '@id': id, ...value }) => [
407
+ Number(id),
408
+ decoded(vocab, comp, named(value, p.refs, names)) as Comp,
409
+ ])
410
+ }
411
+
412
+ /** Whole components keyed by identity, for reads that select one version. */
413
+ export let rowsOf = (...args: Parameters<typeof valuesOf>): Map<number, Comp> =>
414
+ new Map(valuesOf(...args))
415
+
416
+ // One component's read, whatever names its owners: `lead` is what is selected
417
+ // before the component's own columns, `owner` the condition on `o`, the
418
+ // owner's spine row.
419
+ let selectComp = (
420
+ v: Vocab,
421
+ comp: string,
422
+ derived: Derived,
423
+ lead: Expr[],
424
+ owner: Expr,
425
+ ): Select => {
426
+ let { sel, joins } = project(v, comp, derived)
427
+ return select({
428
+ cols: [...lead, ...(sel.length ? sel : [as(lit(1), 'present')])],
429
+ from: table(comp),
430
+ joins: [
431
+ join(table('entity', 'o'), eq(col('id', 'o'), col('entity', comp))),
432
+ ...joins,
433
+ ],
434
+ where: owner,
435
+ })
436
+ }
437
+
438
+ /**
439
+ * The SELECT that reads one component of one entity, named by its eid.
440
+ * Exported because gathering a bundle is every SQLite-shaped adapter's job,
441
+ * and they must all read a property the same way: @yaks/d1 sends these
442
+ * statements as one batch instead of one at a time, and nothing else differs.
443
+ */
444
+ // Remote adapters already explicitly plan their component projections. Keep
445
+ // their established gather contract; SQLite's own get/read uses the opted-out
446
+ // projection above. An adapter can opt in through the property registry.
447
+ let complete = new WeakMap<Derived, Derived>()
448
+ let completeDerived = (derived: Derived): Derived =>
449
+ at(complete, derived, () => ({
450
+ ...derived,
451
+ ...Object.fromEntries(
452
+ Object.entries(derived).filter(([, d]) => d.whole === false).map((
453
+ [p, d],
454
+ ) => [p, { ...d, whole: true }]),
455
+ ),
456
+ }))
457
+
458
+ export let compSql = (
459
+ v: Vocab,
460
+ comp: string,
461
+ eid: string,
462
+ derived: Derived = {},
463
+ ): Select =>
464
+ selectComp(
465
+ v,
466
+ comp,
467
+ completeDerived(derived),
468
+ [],
469
+ eq(col('eid', 'o'), val(eid)),
470
+ )
471
+
472
+ /**
473
+ * The column a set-shaped read keys its rows by. Not a component prop — a prop
474
+ * is an identifier, so nothing in a vocabulary can collide with it.
475
+ */
476
+ export let OWNER = '@eid'
477
+
478
+ /**
479
+ * The same read widened from one entity to a set: every entity `owners` names,
480
+ * each row carrying its owner's eid under {@link OWNER}. `owners` is a query
481
+ * selecting one `eid` column.
482
+ *
483
+ * This is what makes a whole read one round trip over a remote database
484
+ * (@yaks/d1 `wholeSql`): the hits are named by the query that found them
485
+ * instead of by eids a first trip had to go and fetch.
486
+ */
487
+ export let setSql = (
488
+ v: Vocab,
489
+ comp: string,
490
+ owners: Sub,
491
+ derived: Derived = {},
492
+ ): Select =>
493
+ selectComp(
494
+ v,
495
+ comp,
496
+ completeDerived(derived),
497
+ [as(col('eid', 'o'), OWNER)],
498
+ among(col('eid', 'o'), owners),
499
+ )
500
+
501
+ /**
502
+ * An entity's tombstone, or null: the grave of the entity whose id `id` reads.
503
+ * A subquery on the tombstone's key rather than a join, so it is answered by
504
+ * that key whatever the planner's statistics remember: told a store's graves
505
+ * were few, SQLite would rather scan every one of them for each entity it reads
506
+ * than seek the one it needs.
507
+ */
508
+ export let grave = (id: Expr): Expr =>
509
+ sub(select({
510
+ cols: [col('entity', 't')],
511
+ from: table('tombstone', 't'),
512
+ where: eq(col('entity', 't'), id),
513
+ }))
514
+
515
+ /**
516
+ * The spine rows of the entities `which` names, as `e`: each one's id, eid,
517
+ * number and grave, and its archetype's eid and table set where the
518
+ * vocabulary declares archetypes. What every whole read starts from. Left
519
+ * `kind`-only, it carries the archetype as the id the entity points at
520
+ * (`@kind`), which every file this package installs keeps, for a reader that
521
+ * knows the descriptors already (`kinded`).
522
+ */
523
+ /** A spine row's number and the letter of its series, as an `entity` row
524
+ * carries them: nothing where it has no number, and no prefix on a row
525
+ * numbered before series had letters. */
526
+ export let numberOf = (
527
+ row: Row,
528
+ ): { num?: number; prefix?: string } =>
529
+ row.num == null ? {} : {
530
+ num: Number(row.num),
531
+ ...row.prefix == null ? {} : { prefix: String(row.prefix) },
532
+ }
533
+
534
+ export let spine = (vocab: Vocab, which: Expr, kind = false): Select => {
535
+ let typed = !!vocab.comp('archetype')
536
+ return select({
537
+ cols: [
538
+ col('id', 'e'),
539
+ col('eid', 'e'),
540
+ col('num', 'e'),
541
+ col('prefix', 'e'),
542
+ as(grave(col('id', 'e')), 'dead'),
543
+ ...(kind ? [as(col('archetype', 'e'), '@kind')] : !typed ? [] : [
544
+ as(col('eid', 'a'), 'archetype'),
545
+ as(col('tables', 'shape'), '@tables'),
546
+ ]),
547
+ ],
548
+ from: table('entity', 'e'),
549
+ joins: [
550
+ ...(typed && !kind
551
+ ? [
552
+ left(table('entity', 'a'), eq(col('id', 'a'), col('archetype', 'e'))),
553
+ left(
554
+ table('archetype', 'shape'),
555
+ eq(col('entity', 'shape'), col('archetype', 'e')),
556
+ ),
557
+ ]
558
+ : []),
559
+ ],
560
+ where: which,
561
+ })
562
+ }
563
+
564
+ // The rows of `src` whose `key` is one of `ids`, driven from the requested
565
+ // set. SQLite estimates json_each at a fixed cardinality, so an IN subquery
566
+ // can choose a table scan when statistics remember a small component (even
567
+ // after its history grows); CROSS JOIN keeps the owners outside the indexed
568
+ // spine/component probes. One owner is an equality on the key instead, which
569
+ // reads no list.
570
+ let owning = (
571
+ ids: readonly (string | number)[],
572
+ src: Source,
573
+ key: Expr,
574
+ ): { from: Source; joins: Join[]; where: Expr } =>
575
+ ids.length == 1 ? { from: src, joins: [], where: eq(key, val(ids[0])) } : {
576
+ from: from(each(ids), '@owners'),
577
+ joins: [cross(src)],
578
+ where: eq(key, col('value', '@owners')),
579
+ }
580
+ let namedSpine = (vocab: Vocab, eids: string[]): Select => {
581
+ let { from, joins, where } = owning(
582
+ eids,
583
+ table('entity', 'e'),
584
+ col('eid', 'e'),
585
+ )
586
+ let base = spine(vocab, where, true)
587
+ return select({ ...base, from, joins: [...joins, ...base.joins!] })
588
+ }
589
+
590
+ // An archetype's eid and tables never change once its row stands, and a store
591
+ // holds a few dozen, so a read keeps them per connection rather than joining
592
+ // both into every entity it reads. A new descriptor, a deleted entity or a
593
+ // rollback starts the keeping over (@yaks/sql `revision`).
594
+ let kinds = new WeakMap<Driver, { at: number; held: Map<number, Row> }>()
595
+
596
+ /**
597
+ * Descriptors a patch wrote since revision `from`, as its entity's id, eid and
598
+ * table set, where nothing else moved one: what this connection keeps of the
599
+ * catalog (./catalog.ts) and of the archetypes its reads name takes them in
600
+ * rather than reading every descriptor again.
601
+ */
602
+ export let described = (
603
+ driver: Driver,
604
+ from: number,
605
+ rows: readonly { id: number; eid: string; tables: string }[],
606
+ ): void => {
607
+ let cache = kinds.get(driver)
608
+ if (cache?.at == from) {
609
+ for (let r of rows) cache.held.set(r.id, { ...r })
610
+ cache.at = revision(driver, 'descriptors')
611
+ }
612
+ learn(driver, from, rows)
613
+ }
614
+ let kinded = (driver: Driver, rows: Row[]): Row[] => {
615
+ let at = revision(driver, 'descriptors')
616
+ let cache = kinds.get(driver)
617
+ if (cache?.at != at) kinds.set(driver, cache = { at, held: new Map() })
618
+ let { held } = cache
619
+ let missing = [
620
+ ...new Set(
621
+ rows.flatMap((r) =>
622
+ r['@kind'] == null || held.has(Number(r['@kind']))
623
+ ? []
624
+ : [Number(r['@kind'])]
625
+ ),
626
+ ),
627
+ ]
628
+ if (missing.length) {
629
+ let { from, joins, where } = owning(
630
+ missing,
631
+ table('entity', 'e'),
632
+ col('id', 'e'),
633
+ )
634
+ let found = driver.query(select({
635
+ cols: [col('id', 'e'), col('eid', 'e'), col('tables', 'a')],
636
+ from,
637
+ joins: [
638
+ ...joins,
639
+ left(table('archetype', 'a'), eq(col('entity', 'a'), col('id', 'e'))),
640
+ ],
641
+ where,
642
+ }))
643
+ for (let row of found) held.set(Number(row.id), row)
644
+ }
645
+ for (let row of rows) {
646
+ let kind = row['@kind'] == null ? undefined : held.get(Number(row['@kind']))
647
+ row.archetype = kind?.eid ?? null
648
+ row['@tables'] = kind?.tables ?? null
649
+ }
650
+ return rows
651
+ }
652
+
653
+ // A previous table set is only a guess about which read to prepare. The read
654
+ // always fetches the current spine, descriptor and component values together;
655
+ // a descriptor that names another table sends it through the ordinary gather.
656
+ let shapes = new WeakMap<
657
+ Driver,
658
+ WeakMap<Vocab, Map<string, readonly string[]>>
659
+ >()
660
+ let stored = new WeakMap<Vocab, Set<string>>()
661
+ let readable = (vocab: Vocab) => at(stored, vocab, () => new Set(tables(vocab)))
662
+ // A joined read rendered for one entity and for many, each with the place of
663
+ // the bind that names them, which holds `ANY` until a read names its own.
664
+ let ANY = '\0'
665
+ type Named = { statement: Raw; at: number }
666
+ // `tagged` names the components whose tags the statements bind first.
667
+ type Joined = {
668
+ one: Named
669
+ many: Named
670
+ names: string[]
671
+ props: string[][]
672
+ tagged: string[]
673
+ }
674
+ let joined = new WeakMap<
675
+ Vocab,
676
+ WeakMap<object, WeakMap<object, Map<string, Joined | null>>>
677
+ >()
678
+ let bounded = <K, V>(cache: Map<K, V>, key: K, value: V, limit: number) => {
679
+ if (cache.size >= limit && !cache.has(key)) {
680
+ cache.delete(cache.keys().next().value!)
681
+ }
682
+ cache.set(key, value)
683
+ return value
684
+ }
685
+
686
+ // Each facet's references and derived dependencies have their own scope.
687
+ // Inline joins retain indexed owner probes; a LEFT JOIN over a subquery with
688
+ // its own joins would make SQLite materialize that facet's entire table.
689
+ let scoped = (
690
+ p: Projection,
691
+ name: string,
692
+ prefix: string,
693
+ ): Projection | null => {
694
+ let aliases = new Map([[name, prefix]])
695
+ for (let j of p.joins) {
696
+ if (j.src.t != 'table') return null
697
+ let alias = j.src.as ?? j.src.name
698
+ aliases.set(alias, `${prefix}:${alias}`)
699
+ }
700
+ let raw = false
701
+ let rename = (node: unknown): unknown => {
702
+ if (!node || typeof node != 'object') return node
703
+ if (Array.isArray(node)) return node.map(rename)
704
+ let value = node as Record<string, unknown>
705
+ // Bound/literal values are data, not SQL trees. A lowered fragment cannot
706
+ // have its identifiers renamed, so it retains the ordinary gather.
707
+ if (value.t == 'val' || value.t == 'lit') return node
708
+ if (value.t == 'raw') {
709
+ // A compiler-proven closed relation has no outer aliases to rename.
710
+ // Other fragments might refer to this row, even inside FROM subqueries.
711
+ if (!value.closed) raw = true
712
+ return node
713
+ }
714
+ if (value.t == 'col') {
715
+ return { ...value, of: aliases.get(String(value.of)) ?? value.of }
716
+ }
717
+ if (value.t == 'table') {
718
+ return {
719
+ ...value,
720
+ as: aliases.get(String(value.as ?? value.name)) ?? value.as,
721
+ }
722
+ }
723
+ return Object.fromEntries(
724
+ Object.entries(value).map(([k, v]) => [k, rename(v)]),
725
+ )
726
+ }
727
+ let out = rename(p) as Projection
728
+ return raw ? null : out
729
+ }
730
+
731
+ let joinedPlan = (
732
+ vocab: Vocab,
733
+ names: string[],
734
+ opts: BindOpts,
735
+ ): Joined | null => {
736
+ let cache = at(
737
+ at(
738
+ at(joined, vocab, () => new WeakMap()),
739
+ opts.derived ?? NONE,
740
+ () => new WeakMap(),
741
+ ),
742
+ opts.backed ?? NONE,
743
+ () => new Map(),
744
+ )
745
+ let key = JSON.stringify([names, Object.keys(opts.tags ?? {})])
746
+ if (cache.has(key)) return cache.get(key)!
747
+ let base = namedSpine(vocab, [ANY, ANY])
748
+ let columns = [...base.cols!]
749
+ let props: string[][] = []
750
+ let reading = new Set<string>()
751
+ let width = columns.length
752
+ for (let [i, name] of names.entries()) {
753
+ let alias = `@g${i}`
754
+ let p = scoped(
755
+ project(vocab, name, opts.derived, opts.backed, opts.tags),
756
+ name,
757
+ alias,
758
+ )
759
+ // A row is packed as JSON, which holds no bytes: a component with a
760
+ // binary property keeps the set-shaped gather.
761
+ let bytes = vocab.props(name).some((prop) =>
762
+ vocab.prop(name, prop)?.scalar == 'binary'
763
+ )
764
+ if (!p || bytes) return bounded(cache, key, null, 128)
765
+ p.tagged?.forEach((c) => reading.add(c))
766
+ let fields = p.sel.map((e) => {
767
+ if (e.t != 'as' && e.t != 'col') {
768
+ throw Error('a projected property needs a name')
769
+ }
770
+ return e.name
771
+ })
772
+ props.push(fields)
773
+ width += fields.length + 1
774
+ // The outer read and every nested projection fit workerd's column and
775
+ // SQLite's joined-table limits. Wide entities keep the set-shaped gather.
776
+ if (width > 100 || p.joins.length + 1 > 60) {
777
+ return bounded(cache, key, null, 128)
778
+ }
779
+ // Read every value in one primary-key lookup. A scalar lookup pins the
780
+ // plan even for one-row statistics; packing the row avoids billing that
781
+ // same lookup again for each property. Concatenation drops JSON's subtype
782
+ // so every adapter returns the same text for this internal projection.
783
+ columns.push(as(
784
+ sub(select({
785
+ cols: [op(
786
+ '||',
787
+ fn(
788
+ 'json_array',
789
+ col('entity', alias),
790
+ ...p.sel.map((e) => e.t == 'as' ? e.e : e),
791
+ ),
792
+ lit(''),
793
+ )],
794
+ from: table(name, alias),
795
+ joins: p.joins,
796
+ where: eq(col('entity', alias), col('id', 'e')),
797
+ })),
798
+ `@${i}`,
799
+ ))
800
+ }
801
+ // Bound first, each store's own tags are the statement's first parameters.
802
+ let tags = [...reading]
803
+ let blank = Object.fromEntries(tags.map((c) => [c, '']))
804
+ let named = (eids: string[]): Named => {
805
+ let spine = namedSpine(vocab, eids)
806
+ let statement = render(
807
+ select({ ...spine, with: tagged(blank, tags), cols: columns }),
808
+ undefined,
809
+ undefined,
810
+ vocab,
811
+ )
812
+ let bind = eids.length == 1 ? eids[0] : JSON.stringify(eids)
813
+ return { statement, at: statement.params.indexOf(bind) }
814
+ }
815
+ let one = named([ANY]), many = named([ANY, ANY])
816
+ if (
817
+ [one, many].some(({ statement }) =>
818
+ statement.sql.length > 90_000 || statement.params.length > 100
819
+ )
820
+ ) return bounded(cache, key, null, 128)
821
+ return bounded(cache, key, { one, many, names, props, tagged: tags }, 128)
822
+ }
823
+
824
+ let joinedGet = (
825
+ driver: Driver,
826
+ vocab: Vocab,
827
+ eids: string[],
828
+ opts: BindOpts,
829
+ names: string[],
830
+ wanted?: string[],
831
+ unsettled?: Unsettled,
832
+ ): Bundle[] | { spine: Row[] } | undefined => {
833
+ let plan = joinedPlan(readingVocab(driver, vocab), names, opts)
834
+ if (!plan) return
835
+ let { statement, at } = eids.length == 1 ? plan.one : plan.many
836
+ let params = [...statement.params]
837
+ plan.tagged.forEach((c, i) => params[i] = opts.tags![c])
838
+ params[at] = eids.length == 1 ? eids[0] : JSON.stringify(eids)
839
+ let rows: Row[]
840
+ try {
841
+ // A read of named components asks the tables it names: only a store
842
+ // that shows archetypes needs the descriptors for it.
843
+ rows = driver.query({ ...statement, params })
844
+ if (!wanted || vocab.comp('archetype')) rows = kinded(driver, rows)
845
+ } catch (err) {
846
+ // A raw schema edit can remove a table from the previous shape. Read the
847
+ // current descriptor before deciding which remaining tables to gather.
848
+ if (err instanceof Error && /no such (table|column):/i.test(err.message)) {
849
+ return
850
+ }
851
+ throw err
852
+ }
853
+ let found = new Map<string, Bundle>()
854
+ let numbered = !!vocab.prop('entity', 'num')
855
+ let typed = !!vocab.comp('archetype')
856
+ let covered = new Set(names)
857
+ for (let row of rows) {
858
+ let entity = {
859
+ eid: String(row.eid),
860
+ ...numbered ? numberOf(row) : {},
861
+ ...!typed || row.archetype == null
862
+ ? {}
863
+ : { archetype: String(row.archetype) },
864
+ }
865
+ let bundle: Bundle = row.dead == null ? { entity } : tombstoned(entity)
866
+ found.set(entity.eid, bundle)
867
+ if (row.dead != null) continue
868
+ let current = row['@tables'] == null || unsettled?.wrote(entity.eid)
869
+ ? undefined
870
+ : descriptor(driver, String(row['@tables'])).tables
871
+ if (
872
+ wanted == null &&
873
+ (!current ||
874
+ current.some((name) => readable(vocab).has(name) && !covered.has(name)))
875
+ ) return { spine: rows }
876
+ for (let [i, name] of names.entries()) {
877
+ if (row[`@${i}`] == null || current && !current.includes(name)) continue
878
+ let values = JSON.parse(String(row[`@${i}`])) as unknown[]
879
+ bundle[name] = decoded(
880
+ vocab,
881
+ name,
882
+ Object.fromEntries(
883
+ plan.props[i].map((prop, j) => [prop, values[j + 1]]),
884
+ ),
885
+ ) as Comp
886
+ }
887
+ }
888
+ backedGet(
889
+ driver,
890
+ vocab,
891
+ eids.filter((eid) => !found.has(eid)),
892
+ opts,
893
+ wanted,
894
+ )
895
+ .forEach((b) => found.set(b.entity.eid, b))
896
+ return eids.flatMap((eid) => found.get(eid) ?? [])
897
+ }
898
+
899
+ /**
900
+ * Identity, not search: these entities as they stand. A tombstoned one comes
901
+ * back carrying `tombstone` (it is still an identity, just a deleted one); an
902
+ * eid no entity has is simply absent. Each carries the components `comps`
903
+ * names, and no other table is read; left out, it carries every one. This is
904
+ * the read `apply()` uses for its precondition guard, where a query would be
905
+ * the wrong question.
906
+ *
907
+ * Each entity is read from the tables its archetype names, and no table is
908
+ * asked whether it holds one. `unsettled` speaks for the entities whose
909
+ * pointer does not say what they hold ({@link Unsettled}); an entity it cannot
910
+ * speak for either is a failure, and the read throws {@link Unpointed}.
911
+ */
912
+ export type ReadCache = {
913
+ fetch: (eids: string[], comps?: string[]) => Bundle[]
914
+ /** the eids a scope admits, and where `graves` asks, the deleted it sees
915
+ * (@yaks/sql `ghostly`), which only `run`'s statement judges */
916
+ permit: (
917
+ eids: string[],
918
+ components: string[],
919
+ run: () => Row[],
920
+ graves?: boolean,
921
+ ) => Row[]
922
+ }
923
+
924
+ /**
925
+ * Who says what an entity holds where its stored pointer does not: the
926
+ * store's open transaction, which wrote rows the pointer has not been moved
927
+ * for yet (./archetype.ts `ledger`), or a connection reading another time than
928
+ * the pointer speaks of (./mode.ts).
929
+ */
930
+ export type Unsettled = {
931
+ /** Whether `eid`'s pointer is behind what the entity holds. */
932
+ wrote: (eid: string) => boolean
933
+ /** The tables each of these entities holds among `names`, by its id, given
934
+ * the ones its pointer names (null where it names none). One it cannot
935
+ * speak for is left out. */
936
+ held: (
937
+ rows: { eid: string; id: number; pointed: readonly string[] | null }[],
938
+ names: readonly string[],
939
+ ) => Map<number, readonly string[]>
940
+ }
941
+
942
+ export { Unpointed } from './error.js'
943
+
944
+ /** The eids, of `eids`, whose entities a scope's `screen` admits. Each
945
+ * requested row is tested against the screen by its id, so the statement reads
946
+ * the rows asked about and never lists everything the scope sees: `id in
947
+ * (screen)` builds that list on every call, at the cost of a scan. */
948
+ export let admitted = (eids: string[], screen: Raw | null): Select =>
949
+ select({
950
+ cols: [col('eid', '__requested')],
951
+ from: table('entity', '__requested'),
952
+ where: and(
953
+ oneOf(col('eid', '__requested'), eids),
954
+ screen
955
+ ? exists(select({
956
+ cols: [lit(1)],
957
+ from: from(screen, '__allowed'),
958
+ where: eq(col('id', '__allowed'), col('id', '__requested')),
959
+ }))
960
+ : lit(true),
961
+ ),
962
+ })
963
+
964
+ // `answered`: the eids are what a query under `opts.visibility` answered, in
965
+ // this same snapshot, so the scope has admitted each one already. Their
966
+ // aspects and the entities they reference are still put to it.
967
+ export let get = (
968
+ driver: Driver,
969
+ vocab: Vocab,
970
+ eids: string[],
971
+ opts: BindOpts = {},
972
+ comps?: string[],
973
+ unsettled?: Unsettled,
974
+ cache?: ReadCache,
975
+ answered = false,
976
+ ): Bundle[] => {
977
+ if (!eids.length) return []
978
+ // The tables this read may touch: every component's, or the named ones',
979
+ // less any the file does not hold yet, which no entity can wear: those a
980
+ // reader was told of, else the ones no write has raised (./raise.ts). A
981
+ // caller's own read overrides read those as worn by nobody too.
982
+ let absent = opts.absent ?? unraised(driver, vocab)
983
+ if (absent.length) {
984
+ opts = {
985
+ ...opts,
986
+ derived: absentDerived(vocab, derivedOf(vocab, opts.derived), absent),
987
+ }
988
+ }
989
+ if (opts.visibility) {
990
+ let { visibility, ...plain } = opts
991
+ // A backed entity has no entity row: it is seen when its backing, as the
992
+ // scope sees it, holds its row, whatever components are asked about.
993
+ let tags = Object.values(plain.tags ?? {})
994
+ let tagged = (eid: string) => tags.some((tag) => idOf(tag, eid) != null)
995
+ let seen = (ids: string[]) =>
996
+ backedGet(
997
+ driver,
998
+ vocab,
999
+ ids,
1000
+ { ...plain, backed: visibleBacked(vocab, opts) },
1001
+ [],
1002
+ ).map((b) => b.entity.eid)
1003
+ // A getter's eids are physical identities. Query addressing may interpret
1004
+ // a human id such as history-1 as number 1, which cannot decide ownership.
1005
+ // A deleted entity the scope sees (@yaks/sql `ghostly`) is admitted: it
1006
+ // is gotten as its tombstone, as without a scope, and a reference names
1007
+ // it, as a query's reference operand does (./mod.ts `resolved`).
1008
+ let permitted = (all: string[], components: string[] = []): Set<string> => {
1009
+ let backed = tags.length ? all.filter(tagged) : []
1010
+ let ids = backed.length ? all.filter((eid) => !tagged(eid)) : all
1011
+ let out = new Set(seen(backed))
1012
+ if (!ids.length) return out
1013
+ if (
1014
+ !visibility.entity &&
1015
+ !components.some((name) => visibility.components?.[name])
1016
+ ) {
1017
+ for (let eid of ids) out.add(eid)
1018
+ return out
1019
+ }
1020
+ let run = () =>
1021
+ driver.query(
1022
+ admitted(
1023
+ ids,
1024
+ sourceScreen(
1025
+ readingVocab(driver, vocab),
1026
+ { ...opts, graves: true },
1027
+ components,
1028
+ ),
1029
+ ),
1030
+ )
1031
+ for (
1032
+ let r of cache ? cache.permit(ids, components, run, true) : run()
1033
+ ) {
1034
+ out.add(String(r.eid))
1035
+ }
1036
+ return out
1037
+ }
1038
+ // The payload cache answers first, so only what is there is put to the
1039
+ // scope: an id no entity has (most an address asks about, @yaks/alias)
1040
+ // costs no screen.
1041
+ let held = cache?.fetch(eids, comps)
1042
+ let allowed = answered
1043
+ ? new Set(eids)
1044
+ : permitted(held ? held.map((b) => b.entity.eid) : eids)
1045
+ let ids = eids.filter((eid) => allowed.has(eid))
1046
+ let scoped = () => ({ ...plain, derived: visibleDerived(vocab, opts) })
1047
+ let found = held
1048
+ ? held.filter((b) => allowed.has(b.entity.eid))
1049
+ : get(driver, vocab, ids, scoped(), comps, unsettled)
1050
+ if (cache) {
1051
+ // The payload cache holds authoritative rows. Every derived component
1052
+ // is read again through scoped sources before the payload is exposed.
1053
+ let names = new Set(
1054
+ Object.entries(derivedOf(vocab, opts.derived)).filter(([, d]) =>
1055
+ !storedOnly(d, vocab)
1056
+ ).map(([p]) => p.split('.')[0]),
1057
+ )
1058
+ let dynamic = [...names].filter((name) => found.some((b) => b[name]))
1059
+ if (dynamic.length) {
1060
+ let current = new Map(
1061
+ get(driver, vocab, ids, scoped(), dynamic, unsettled).map((
1062
+ b,
1063
+ ) => [b.entity.eid, b]),
1064
+ )
1065
+ found = found.map((b) => {
1066
+ let out = { ...b }
1067
+ for (let name of dynamic) delete out[name]
1068
+ return { ...out, ...current.get(b.entity.eid) }
1069
+ })
1070
+ }
1071
+ }
1072
+ let described = found.some((b) => b.entity.archetype)
1073
+ // A component the file holds no table for is worn by nobody, so it hides
1074
+ // nothing and no statement names its table.
1075
+ let aspects = Object.keys(visibility.components ?? {})
1076
+ .filter((name) => !setOf(absent).has(name))
1077
+ .filter((name) => described || found.some((b) => b[name]))
1078
+ .map((name) => [name, permitted(eids, [name])] as const)
1079
+ let hidden = new Set<string>()
1080
+ if (described) {
1081
+ for (let [name, owners] of aspects) {
1082
+ let wearing = comps && !comps.includes(name)
1083
+ ? driver.query(select({
1084
+ cols: [col('eid', '__requested')],
1085
+ from: table('entity', '__requested'),
1086
+ joins: [
1087
+ join(
1088
+ table(name, '__aspect'),
1089
+ eq(col('entity', '__aspect'), col('id', '__requested')),
1090
+ ),
1091
+ ],
1092
+ where: oneOf(col('eid', '__requested'), eids),
1093
+ }))
1094
+ .map((r) => String(r.eid))
1095
+ : found.filter((b) => !!b[name]).map((b) => b.entity.eid)
1096
+ for (let eid of wearing) {
1097
+ if (!owners.has(eid)) hidden.add(eid)
1098
+ }
1099
+ }
1100
+ }
1101
+ let targets = new Set<string>()
1102
+ for (let b of found) {
1103
+ for (let [name, value] of Object.entries(b)) {
1104
+ if (name == 'entity' || !value || typeof value != 'object') continue
1105
+ for (let prop of vocab.props(name)) {
1106
+ let v = (value as Comp)[prop]
1107
+ if (
1108
+ vocab.prop(name, prop)?.category == 'ref' && typeof v == 'string'
1109
+ ) targets.add(v)
1110
+ }
1111
+ }
1112
+ }
1113
+ let references = visibility.entity && targets.size
1114
+ ? permitted([...targets])
1115
+ : targets
1116
+ return found.map((b) => {
1117
+ let out: Bundle = { ...b, entity: { ...b.entity } }
1118
+ if (hidden.has(b.entity.eid)) delete out.entity.archetype
1119
+ for (let [name, owners] of aspects) {
1120
+ if (!owners.has(b.entity.eid)) delete out[name]
1121
+ }
1122
+ for (let [name, value] of Object.entries(out)) {
1123
+ if (name == 'entity' || !value || typeof value != 'object') continue
1124
+ let component = value as Comp
1125
+ for (let prop of vocab.props(name)) {
1126
+ if (
1127
+ vocab.prop(name, prop)?.category == 'ref' &&
1128
+ typeof component[prop] == 'string' &&
1129
+ !references.has(component[prop] as string)
1130
+ ) {
1131
+ component = { ...component, [prop]: null }
1132
+ }
1133
+ }
1134
+ out[name] = component
1135
+ }
1136
+ return out
1137
+ })
1138
+ }
1139
+ let pending = eids.filter((eid) => unsettled?.wrote(eid))
1140
+ let names =
1141
+ (comps
1142
+ ? [...new Set(comps)].filter((c) => readable(vocab).has(c))
1143
+ : tables(vocab)).filter((c) => !setOf(absent).has(c))
1144
+ let remembered = at(
1145
+ at(shapes, driver, () => new WeakMap()),
1146
+ logicalVocab(vocab),
1147
+ () => new Map(),
1148
+ )
1149
+ let initial: Row[] | undefined
1150
+ // Small, repeated identity reads benefit from one statement. Large gathers
1151
+ // still read each worn table once for all its owners, rather than joining
1152
+ // the union of every different entity's facets.
1153
+ if (
1154
+ eids.length && eids.length <= 32 && !comps && !pending.length &&
1155
+ eids.every((eid) => remembered.has(eid))
1156
+ ) {
1157
+ let descriptors = eids.filter((eid) => {
1158
+ let names = remembered.get(eid)!
1159
+ return names.length == 1 && names[0] == 'archetype'
1160
+ })
1161
+ if (descriptors.length && descriptors.length < eids.length) {
1162
+ let owners = eids.filter((eid) => !descriptors.includes(eid))
1163
+ let a = joinedGet(
1164
+ driver,
1165
+ vocab,
1166
+ descriptors,
1167
+ opts,
1168
+ ['archetype'],
1169
+ undefined,
1170
+ unsettled,
1171
+ )
1172
+ let names = [
1173
+ ...new Set(owners.flatMap((eid) => [...remembered.get(eid)!])),
1174
+ ].sort()
1175
+ let b = joinedGet(
1176
+ driver,
1177
+ vocab,
1178
+ owners,
1179
+ opts,
1180
+ names,
1181
+ undefined,
1182
+ unsettled,
1183
+ )
1184
+ if (Array.isArray(a) && Array.isArray(b)) {
1185
+ let at = new Map([...a, ...b].map((row) => [row.entity.eid, row]))
1186
+ return eids.flatMap((eid) => at.get(eid) ?? [])
1187
+ }
1188
+ }
1189
+ }
1190
+ if (eids.length && eids.length <= 32) {
1191
+ let guess = comps
1192
+ ? names
1193
+ : eids.every((eid) => remembered.has(eid))
1194
+ ? [...new Set(eids.flatMap((eid) => [...remembered.get(eid)!]))].sort()
1195
+ : undefined
1196
+ if (guess) {
1197
+ let rows = joinedGet(driver, vocab, eids, opts, guess, comps, unsettled)
1198
+ if (Array.isArray(rows)) return rows
1199
+ initial = rows?.spine
1200
+ }
1201
+ }
1202
+ let asked = new Set(names)
1203
+ let found = new Map<string, Bundle>()
1204
+ // Whether a number is this store's to show. The spine table holds the column
1205
+ // in every layout, but the number is @yaks/id's word and a store that never
1206
+ // loaded it has none to speak of — including one that was numbered before the
1207
+ // plugin was opt in, whose old rows still carry the value. Read off the
1208
+ // vocabulary, as the archetype is: every file keeps the pointer, and a store
1209
+ // shows it where its vocabulary declares archetypes (@yaks/archetype).
1210
+ let numbered = !!vocab.prop('entity', 'num')
1211
+ let typed = !!vocab.comp('archetype')
1212
+ // Bound parameter count and SQL-cache size; gather a component per set,
1213
+ // never every component per entity (a 1,000-entry transcript is otherwise
1214
+ // tens of thousands of queries). A set of owners is a collection (@yaks/sql
1215
+ // `each`), written the way the host reads one cheapest.
1216
+ // Materialize the selected ids once: re-running a window subquery
1217
+ // for each component could select different owners under a concurrent writer.
1218
+ // Keep caller order and duplicate semantics.
1219
+ // Entities nothing says the tables of, across every part of the read.
1220
+ let lost: string[] = []
1221
+ for (let i = 0; i < eids.length; i += 4096) {
1222
+ let ids = eids.slice(i, i + 4096)
1223
+ let byId = new Map<number, Bundle>()
1224
+ let groups = new Map<string, { tables: readonly string[]; ids: number[] }>()
1225
+ let grouped = (key: string, tables: readonly string[], id: number) => {
1226
+ let group = groups.get(key)
1227
+ if (!group) groups.set(key, group = { tables, ids: [] })
1228
+ group.ids.push(id)
1229
+ }
1230
+ // The entities whose pointer does not say what they hold.
1231
+ let open: { eid: string; id: number; pointed: readonly string[] | null }[] =
1232
+ []
1233
+ let spines = initial ?? driver.query(namedSpine(vocab, ids))
1234
+ // A projection onto one private facet already knows its table. Wider
1235
+ // projections use the stored shapes even when readers cannot see them.
1236
+ if (!initial && (typed || !comps || names.length > 1)) {
1237
+ kinded(driver, spines)
1238
+ }
1239
+ for (let row of spines) {
1240
+ let eid = String(row.eid)
1241
+ let entity = {
1242
+ eid,
1243
+ ...numbered ? numberOf(row) : {},
1244
+ ...(!typed || row.archetype == null
1245
+ ? {}
1246
+ : { archetype: String(row.archetype) }),
1247
+ }
1248
+ let bundle = row.dead == null ? { entity } : tombstoned(entity)
1249
+ found.set(eid, bundle)
1250
+ byId.set(Number(row.id), bundle)
1251
+ if (row.dead != null) {
1252
+ bounded(remembered, eid, [], 2048)
1253
+ continue
1254
+ }
1255
+ // What an entity holds is what its archetype names. No table is asked.
1256
+ let pointed = row['@tables'] == null
1257
+ ? null
1258
+ : descriptor(driver, String(row['@tables'])).tables
1259
+ if (!pointed || unsettled?.wrote(eid)) {
1260
+ open.push({ eid, id: Number(row.id), pointed })
1261
+ continue
1262
+ }
1263
+ bounded(
1264
+ remembered,
1265
+ eid,
1266
+ pointed.filter((c) => names.includes(c)),
1267
+ 2048,
1268
+ )
1269
+ // Grouped by the set's names, as an entity nothing points for is: a
1270
+ // set described in two forms (identities, and labels from before) is
1271
+ // read once.
1272
+ grouped(JSON.stringify(pointed), pointed, Number(row.id))
1273
+ }
1274
+ if (open.length) {
1275
+ // The one that knows better says (`unsettled`). A read of named
1276
+ // components asks the tables it names, which is its own question; a
1277
+ // whole read of an entity nothing speaks for has no table to ask.
1278
+ let held = unsettled?.held(open, names)
1279
+ for (let { eid, id } of open) {
1280
+ let tables = held?.get(id) ?? (comps ? names : undefined)
1281
+ if (tables) grouped(JSON.stringify(tables), tables, id)
1282
+ else lost.push(eid)
1283
+ }
1284
+ if (lost.length) continue
1285
+ }
1286
+ let compOwners = new Map<string, number[]>()
1287
+ // Group once per table set, then read each present table once across all
1288
+ // its owner groups.
1289
+ for (let { tables, ids } of groups.values()) {
1290
+ for (let comp of tables) {
1291
+ if (!asked.has(comp)) continue
1292
+ let held = compOwners.get(comp)
1293
+ if (held) held.push(...ids)
1294
+ else compOwners.set(comp, [...ids])
1295
+ }
1296
+ }
1297
+ // The spine pass already resolved every owner's storage id. Do not join
1298
+ // it again for each component just to recover the eid we already hold;
1299
+ // the references every component's rows hold are named once, together.
1300
+ let read: [Bundle, string, Row, string[] | undefined][] = []
1301
+ for (let [comp, ids] of compOwners) {
1302
+ let p = project(
1303
+ vocab,
1304
+ comp,
1305
+ opts.derived,
1306
+ opts.backed,
1307
+ opts.tags,
1308
+ true,
1309
+ )
1310
+ let { sel, joins, refs } = p
1311
+ let owners = owning(ids, table(comp), col('entity', comp))
1312
+ for (
1313
+ let row of driver.query(select({
1314
+ with: tagging(p, opts.tags),
1315
+ cols: [as(col('entity', comp), '@id'), ...sel],
1316
+ ...owners,
1317
+ joins: [...owners.joins, ...joins],
1318
+ }))
1319
+ ) {
1320
+ let { '@id': owner, ...value } = row
1321
+ let b = byId.get(Number(owner))!
1322
+ if ('tombstone' in b) continue
1323
+ read.push([b, comp, value, refs])
1324
+ }
1325
+ }
1326
+ let refNames = naming(
1327
+ driver,
1328
+ read.flatMap(([, , value, refs]) => refs?.map((p) => value[p]) ?? []),
1329
+ )
1330
+ for (let [b, comp, value, refs] of read) {
1331
+ b[comp] = decoded(vocab, comp, named(value, refs, refNames)) as Comp
1332
+ }
1333
+ }
1334
+ if (lost.length) throw new Unpointed(lost)
1335
+ backedGet(driver, vocab, eids.filter((e) => !found.has(e)), opts, comps)
1336
+ .forEach((b) => found.set(b.entity.eid, b))
1337
+ for (let eid of eids) {
1338
+ if (!found.has(eid)) bounded(remembered, eid, [], 2048)
1339
+ }
1340
+ return eids.flatMap((eid) => found.has(eid) ? [found.get(eid)!] : [])
1341
+ }
1342
+
1343
+ // The entities a computed component's rows hold, among eids the entity table
1344
+ // does not: each backing's own, read back out of the eid and gathered from its
1345
+ // rows (@yaks/sql `Backing`). An eid no backing's tag names is left out, as an
1346
+ // unknown one is; one whose row is gone is absent too.
1347
+ let backedGet = (
1348
+ driver: Driver,
1349
+ vocab: Vocab,
1350
+ eids: string[],
1351
+ opts: BindOpts,
1352
+ comps?: string[],
1353
+ ): Bundle[] =>
1354
+ Object.entries(opts.backed ?? {}).flatMap(([comp, b]) => {
1355
+ let tag = opts.tags?.[comp]
1356
+ let ids = tag
1357
+ ? eids.map((e) => idOf(tag, e)).filter((id) => id != null)
1358
+ : []
1359
+ if (!tag || !ids.length) return []
1360
+ let asked = !comps || comps.includes(comp)
1361
+ let p: Projection = asked
1362
+ ? project(vocab, comp, opts.derived, opts.backed, opts.tags)
1363
+ : { sel: [], joins: [] }
1364
+ return driver.query(select({
1365
+ with: tagging(p, opts.tags),
1366
+ cols: [as(col('entity', comp), '@id'), ...p.sel],
1367
+ from: from(b.rows, comp),
1368
+ joins: p.joins,
1369
+ where: oneOf(col('entity', comp), ids),
1370
+ })).map(({ '@id': id, ...value }): Bundle => ({
1371
+ entity: { eid: eidOf(tag, Number(id)) },
1372
+ ...asked ? { [comp]: decoded(vocab, comp, value) as Comp } : {},
1373
+ }))
1374
+ })
1375
+
1376
+ /** The tag a computed component's eids end with in a store: the store's epoch
1377
+ * and the component, hashed (@yaks/sql `eidOf`) — so a record's eid names it
1378
+ * in this store and no other. */
1379
+ export let tagOf = (epoch: string, comp: string): string =>
1380
+ sha256(`${epoch}|${comp}`).slice(0, 32)
1381
+
1382
+ // The matched entities, with only `comps` when named. A membership query
1383
+ // returns entities; an aggregate query wants `rows()` instead.
1384
+ // An explicit property query opts into a derived value omitted by a whole
1385
+ // gather. Registries keep their identity so the projection caches still hit.
1386
+ let explicit = new WeakMap<Derived, Map<string, Derived>>()
1387
+ let requestedDerived = (query: And, derived: Derived): Derived => {
1388
+ let wanted = new Set<string>()
1389
+ let path = (segments: string[]) => {
1390
+ let key = segments.join('.')
1391
+ if (derived[key]?.whole === false) wanted.add(key)
1392
+ }
1393
+ map(query, (clause) => {
1394
+ if ('path' in clause) path(clause.path)
1395
+ if (clause.kind == 'order') path(clause.value.replace(/^-/, '').split('.'))
1396
+ if (clause.kind == 'fields') clause.fields.forEach((f) => path(f.path))
1397
+ return clause
1398
+ })
1399
+ if (!wanted.size) return derived
1400
+ let key = [...wanted].sort().join(',')
1401
+ let cache = at(explicit, derived, () => new Map())
1402
+ return at(cache, key, () => ({
1403
+ ...derived,
1404
+ ...Object.fromEntries(
1405
+ [...wanted].map((p) => [p, { ...derived[p], whole: true }]),
1406
+ ),
1407
+ }))
1408
+ }
1409
+
1410
+ export let read = (
1411
+ driver: Driver,
1412
+ vocab: Vocab,
1413
+ query: Query,
1414
+ opts: BindOpts = {},
1415
+ comps?: string[],
1416
+ ask: (query: And) => Row[] = (q) => rows(driver, vocab, q, opts),
1417
+ fetch?: (eids: string[], comps?: string[], answered?: boolean) => Bundle[],
1418
+ unsettled?: Unsettled,
1419
+ ): Bundle[] => {
1420
+ let parsed = ast(query)
1421
+ let eids = ask(parsed).filter((r) => r.eid != null).map((r) => String(r.eid))
1422
+ if (!eids.length) return []
1423
+ let derived = opts.derived ?? NONE
1424
+ // What the filter pinned it computed once already: the rows are filled in
1425
+ // with that value (@yaks/sql `pinned`).
1426
+ let asked = pinned(parsed, vocab, requestedDerived(parsed, derived))
1427
+ // A query asking for no derived value a whole read leaves out, and pinning
1428
+ // none, reads its entities as the store's own get does, through `fetch`
1429
+ // where one is given. Either way, the entities are the query's own answer,
1430
+ // which its scope admitted.
1431
+ return fetch && asked == derived ? fetch(eids, comps, true) : get(
1432
+ driver,
1433
+ vocab,
1434
+ eids,
1435
+ { ...opts, derived: asked },
1436
+ comps,
1437
+ unsettled,
1438
+ undefined,
1439
+ true,
1440
+ )
1441
+ }