@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/README.md CHANGED
@@ -1,3 +1,1597 @@
1
- # Temporary Holding Version
1
+ # @yaks/sqlite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ SQLite storage for [@yaks/graph](../graph/README.md). It builds a schema from a
4
+ [vocabulary](../vocab/README.md#vocabulary), reads
5
+ [queries](../query/README.md#query-model) as
6
+ [bundles](../graph/README.md#data-model), and applies transactional
7
+ [patches](../graph/README.md#data-model).
8
+
9
+ A **store** (`Store`) is the SQLite implementation of
10
+ [Storage](../graph/README.md#data-model), bound to a
11
+ [driver](../sql/README.md#driver) and a vocabulary by `storage()`. The **spine**
12
+ is the `entity` table's identity for an entity: its integer `id`, public `eid`,
13
+ optional `num`, and [archetype](../archetype/README.md) pointer. Component
14
+ tables refer to that integer `id`; bundles carry the public eid.
15
+
16
+ **server_meta** is the table of text key/value metadata kept outside graph
17
+ entities. `meta(driver)` reads, writes, and clears it. An **epoch** is the
18
+ store's persisted lineage identity, minted once by `epoch(driver)`; a client
19
+ cursor from a different epoch cannot resume against this store.
20
+
21
+ The application supplies the connection. The package owns the schema, reads,
22
+ writes, and transactions; the [graph](../graph/README.md#data-model) owns
23
+ admission, preconditions, plugins, and deletion decisions.
24
+
25
+ A retained reader follows the physical schema in each read snapshot. If another
26
+ connection drops a declared column, that property reads as never given; if it
27
+ drops an index, queries continue without forcing that index. Read options are
28
+ rebound when the schema changes, including when a missing column returns. Reads
29
+ do not recreate retired columns or indexes. Writes that explicitly name a
30
+ retired property still require code that understands the migration.
31
+
32
+ ## Usage
33
+
34
+ ```sh
35
+ deno add jsr:@yaks/sqlite jsr:@yaks/graph jsr:@yaks/vocab
36
+ ```
37
+
38
+ This Deno example opens an in-memory database. Use a file path for persistence.
39
+ `open(path)` from `@yaks/sqlite/db` returns a driver over the database there,
40
+ with a prepared-statement cache, and a `close()`.
41
+
42
+ The complete example opens and installs its own database. Its checks run in
43
+ [`readme_test.ts`](./readme_test.ts), with private stores prepared before each
44
+ scenario's timed checks.
45
+
46
+ ```ts ignore
47
+ import { open } from '@yaks/sqlite/db'
48
+ import { storage } from '@yaks/sqlite'
49
+ import { graph } from '@yaks/graph'
50
+ import { loadVocab } from '@yaks/vocab'
51
+ import { equal } from '@yaks/testing'
52
+
53
+ let vocab = loadVocab({
54
+ $defs: {
55
+ doc: {
56
+ component: true,
57
+ type: 'object',
58
+ kind: true,
59
+ properties: {
60
+ title: { type: 'string' },
61
+ body: { type: 'string' },
62
+ },
63
+ },
64
+ post: {
65
+ component: true,
66
+ type: 'object',
67
+ kind: true,
68
+ before: ['doc'],
69
+ properties: {
70
+ published: { type: 'boolean' },
71
+ author: { type: 'string', ref: 'entity', death: 'detach' },
72
+ },
73
+ },
74
+ },
75
+ })
76
+ let sql = open(':memory:')
77
+ try {
78
+ let store = storage(sql, vocab)
79
+ store.install()
80
+ let g = graph({ storage: store, vocab })
81
+
82
+ await g.apply([
83
+ { entity: { eid: 'kate' }, doc: { title: 'Kate' } },
84
+ {
85
+ entity: { eid: 'p1' },
86
+ doc: { title: 'Hello world', body: 'first post' },
87
+ post: { published: true, author: 'kate' },
88
+ },
89
+ ])
90
+ equal((await g.read('.post.published=1')).map((b) => b.entity.eid), ['p1'])
91
+ equal((await g.read('.post'))[0].post, { published: true, author: 'kate' })
92
+ equal((await store.tx((tx) => tx.doom(['kate']))).loose, [{
93
+ eid: 'p1',
94
+ comp: 'post',
95
+ prop: 'author',
96
+ }])
97
+ await g.apply([{ entity: { eid: 'kate' }, $delete: true }])
98
+ equal((await g.read('.post'))[0].post, { published: true })
99
+ } finally {
100
+ sql.close()
101
+ }
102
+ ```
103
+
104
+ ## Exports
105
+
106
+ | Import path | Purpose |
107
+ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
108
+ | `@yaks/sqlite` | Storage, schema/read/write helpers, [overlays](#querying-pending-changes-with-an-overlay), archetype helpers, metadata, and migrations |
109
+ | `@yaks/sqlite/db` | `open(path)`: an embedded Deno database as a cached driver |
110
+ | `@yaks/sqlite/read-db` | `open(path)`: an existing file as a cached read-only driver, without loading the native writer |
111
+ | `@yaks/sqlite/budget` | `metered(read, {what?, limits?})`: what one read may materialize, and the `meter` both engines count each decoded row against |
112
+ | `@yaks/sqlite/reader` | Committed reads of an installed database |
113
+ | `@yaks/sqlite/read-store` | Read-only storage with index, diagnostic and revision capabilities |
114
+ | `@yaks/sqlite/physical` | Inspection of installed tables, columns and schema objects |
115
+ | `@yaks/sqlite/migration` | Migration readiness, monitoring and explicit installation control |
116
+ | `@yaks/sqlite/meta` | The store's own key/value and the plugins its data requires, without loading storage |
117
+ | `@yaks/sqlite/survey` | `survey` and `surveyed`: what a writer found of the file's schema, kept until the schema moves ([below](#following-a-composed-schema)) |
118
+ | `@yaks/sqlite/vocab` | `sqliteDoc` and `docs`, declaring storage and archetype diagnostic tools |
119
+ | `@yaks/sqlite/tools` | `runs({ storage: storage(sql, vocab) }, options?)`, implementing those checks on the application's connection |
120
+
121
+ The vocabulary export declares [tools](../tools/README.md), not graph
122
+ components. The checks inspect foreign-key enforcement/violations, SQLite
123
+ integrity, and archetype consistency; `sample` limits reported archetype
124
+ examples. See [mod.ts](./mod.ts) for the root export list.
125
+
126
+ ## Write
127
+
128
+ Applications normally write through `graph.apply()`, which checks admission and
129
+ preconditions, runs plugins, and plans cascading deletion. The storage adapter
130
+ implements the resulting row changes and transaction. Low-level callers can use
131
+ `await store.tx(tx => tx.patch(bundles))`, but that bypasses graph validation
132
+ and plugins.
133
+
134
+ Reads are synchronous. Transactions return synchronously when uncontended, or
135
+ wait asynchronously for another writer, including an independent transaction on
136
+ the same connection. `tx(body, { wait: false })` refuses another connection's
137
+ lock immediately with `retryable: true`. Errors from the body are never retried.
138
+ An asynchronous body retains its transaction until it settles. Only calls in
139
+ that body's async context can nest savepoints; unrelated writes take turns. Keep
140
+ external work before the transaction so its write lock stays short.
141
+
142
+ The complete example opens and installs its own database. Its checks run in
143
+ [`readme_test.ts`](./readme_test.ts), with private stores prepared before each
144
+ scenario's timed checks.
145
+
146
+ ```ts ignore
147
+ import { open } from '@yaks/sqlite/db'
148
+ import { storage } from '@yaks/sqlite'
149
+ import { loadVocab } from '@yaks/vocab'
150
+ import { docDoc } from '@yaks/doc'
151
+ import { equal, throws } from '@yaks/testing'
152
+
153
+ let sql = open(':memory:')
154
+ try {
155
+ let store = storage(sql, loadVocab(docDoc))
156
+ store.tx((tx) =>
157
+ tx.patch([
158
+ { entity: { eid: 'p1' }, doc: { title: 'Hello', body: 'First' } },
159
+ ])
160
+ )
161
+ store.tx((tx) => tx.patch([{ entity: { eid: 'p1' }, doc: { title: null } }]))
162
+ equal(store.get(['p1'])[0].doc, { body: 'First' })
163
+ await throws(() =>
164
+ store.tx((tx) => {
165
+ tx.patch([{ entity: { eid: 'p1' }, doc: null }])
166
+ throw new Error('abort')
167
+ })
168
+ )
169
+ equal(store.read('.doc').length, 1)
170
+ store.tx((tx) => tx.remove([{ eid: 'p1' }]))
171
+ equal(store.read('.doc'), [])
172
+ equal('tombstone' in store.get(['p1'])[0], true)
173
+ store.tx((tx) => {
174
+ tx.revive(['p1'])
175
+ tx.patch([{ entity: { eid: 'p1' }, doc: { title: 'Again' } }])
176
+ })
177
+ equal(store.get(['p1'])[0].doc, { title: 'Again' })
178
+ } finally {
179
+ sql.close()
180
+ }
181
+ ```
182
+
183
+ A patch writes in bulk: the identities it mints, and the whole rows it gives
184
+ entities that did not hold the component, are one statement per table, each row
185
+ a member of one bound JSON array (`@yaks/sql` `parts`), however many entities
186
+ the patch names. Inside a transaction SQLite opens a savepoint for every write
187
+ statement, copies each page the statement changes into its statement journal,
188
+ and FTS5 writes what it holds pending as a new segment, so a statement per row
189
+ paid all three per row. A partial patch of a row the store holds is still a
190
+ statement of its own, as is a row holding a value JSON does not carry as a bind
191
+ would (a blob, a bigint).
192
+
193
+ A deleted entity keeps its identity row and gains a tombstone. `tx.revive()`
194
+ removes the tombstone, and the identity keeps its eid, number and integer id;
195
+ which writes bring an entity back is @yaks/graph's to decide. Reference
196
+ properties declare [death behavior](../vocab/README.md#routing-and-references).
197
+ `tx.remove()` removes exactly the entities passed to it; the graph determines
198
+ the full cascade. Where the store keeps archetypes, it clears only the tables
199
+ each entity's archetype names, with any rows the open transactions wrote since
200
+ its pointer (`heldBy`); an entity with no pointer, or one naming no descriptor,
201
+ has every component table cleared. The transaction points each one no tracker
202
+ has pointed at the tombstone set as it closes (`entomb`), so a presence lookup
203
+ passes the dead by however they were removed.
204
+
205
+ `store.measure(signal)` says what the file keeps (./measure.ts), as SQLite's
206
+ page statistics (`dbstat`) count it: the file's bytes and free bytes, and each
207
+ table's bytes with its indexes folded in, and its rows. `dbstat` reads every
208
+ page, and one b-tree of a file of gigabytes is a statement that reads for half a
209
+ minute, so a file is measured in a Worker over a read-only connection of its own
210
+ (./measure_worker.ts) and the caller's thread never waits on it; a database in
211
+ memory is walked a b-tree at a time, each in a read unit. `store.file` is where
212
+ the file is, as SQLite opened it (`PRAGMA database_list`), and absent for one in
213
+ memory and for a driver that owns no file, such as a Durable Object's.
214
+
215
+ `store.buried(before, { after, limit })` offers the graves a retention sweep may
216
+ prune (./buried.ts): tombstones laid before `before` that no column in the file
217
+ names, whichever package keyed it to `entity` (the journal's, an embedding's)
218
+ and every `keep` reference, which carries no key. It walks them by integer id,
219
+ so a page's `next` still marks the place once that page is pruned. `tx.prune()`
220
+ erases a whole page in three statements (`pruneSql`), checking each identity
221
+ against its archetype and incoming references, in the write's transaction.
222
+
223
+ ## Read
224
+
225
+ `@yaks/sqlite/reader` exports `reader(driver, vocab, options)`, a read-only
226
+ storage interface for an already-installed database. It exposes `read`, `rows`
227
+ and `get`, uses the same query compiler and snapshot rules as `storage()`, and
228
+ accepts the same derived and backed read bindings. It loads no schema installer
229
+ or mutation pipeline. `@yaks/sqlite/read-store` exports
230
+ `storage(driver, vocab, options)` with statements, diagnostics, migrations,
231
+ revision, computed-property presence and schema descriptions. It refuses
232
+ `install` and write-transaction callbacks before they run. Open the file with
233
+ `open(path, {readOnly: true})` from `@yaks/sqlite/db` when writes must also be
234
+ prevented at the database boundary. The same read-only driver is available as
235
+ `open(path)` from `@yaks/sqlite/read-db`, which binds the native reading and
236
+ extension-loading APIs. Extensions can read installed indexes; SQLite refuses
237
+ metadata writes. Both readers leave the database and WAL untouched when they
238
+ close.
239
+
240
+ A read can ask for more than a process can hold. Every read a store answers
241
+ (`read`, `rows` and `get`, on the writer's connection and on the read-only one
242
+ alike) runs under a **budget** (`@yaks/sqlite/budget`): both engines `meter`
243
+ each row they decode against the read running, and a read past `LIMITS` (a
244
+ million rows or 256 MiB, each row costing its text and blobs plus a little for
245
+ the row and each value) is refused where it stands, as a `Refused` error its
246
+ caller hears that names the read by its masked query. So a query that matches
247
+ most of the graph is refused to whoever asked, through any door, and the process
248
+ stays up for everyone else. Reads over SQLite are synchronous, so a thread runs
249
+ one at a time: `metered` is the frame a read's rows count against, `what` names
250
+ it, and a read inside another counts against the outer one.
251
+
252
+ ```ts ignore
253
+ import { metered, named } from '@yaks/sqlite/budget'
254
+
255
+ metered(() => sql.query(scan('big')), {
256
+ what: named('.big'),
257
+ limits: { rows: 1_000, bytes: 1024 * 1024 },
258
+ })
259
+ ```
260
+
261
+ `read` accepts a query string or [query AST](../query/README.md#query-model) and
262
+ returns whole bundles, resolving stored integer references back to public ids.
263
+ Use `rows` for aggregate and field-projection results. See
264
+ [@yaks/query](../query/README.md) for operators, lists, ranges, time phrases,
265
+ kind filters, ordering, pagination, and aggregates.
266
+
267
+ The complete example opens and installs its own database. Its checks run in
268
+ [`readme_test.ts`](./readme_test.ts), with private stores prepared before each
269
+ scenario's timed checks.
270
+
271
+ ```ts ignore
272
+ import { open } from '@yaks/sqlite/db'
273
+ import { storage } from '@yaks/sqlite'
274
+ import { loadVocab } from '@yaks/vocab'
275
+ import { docDoc } from '@yaks/doc'
276
+ import { equal } from '@yaks/testing'
277
+
278
+ let sql = open(':memory:')
279
+ try {
280
+ let store = storage(sql, loadVocab(docDoc))
281
+ store.tx((tx) =>
282
+ tx.patch([
283
+ { entity: { eid: 'a' }, doc: { title: 'A' } },
284
+ { entity: { eid: 'b' }, doc: { title: 'B' } },
285
+ ])
286
+ )
287
+ equal(store.rows('.doc .count'), [{ value: '', n: 2 }])
288
+ equal(store.rows('.doc.title=A .fields=doc.title'), [{
289
+ eid: 'a',
290
+ 'doc.title': 'A',
291
+ }])
292
+ equal(store.get(['b'], ['doc'])[0].doc, { title: 'B' })
293
+ equal(sql.query(store.screen('.doc.title=A')!).length, 1)
294
+ } finally {
295
+ sql.close()
296
+ }
297
+ ```
298
+
299
+ A whole entity `get` reads is kept in memory until a write names it, so an
300
+ entity read again costs no row, whole or cut to the components a `get` names. A
301
+ `get` naming components keeps what it read too, beside what other `get`s read of
302
+ the entity, for a later `get` naming no others; a `read` takes the entities it
303
+ found from the same memory, unless it asks for a derived value a whole read
304
+ leaves out. A statement that writes a component table without naming its
305
+ entities lets go of every one, as do schema changes; nothing a transaction has
306
+ written is kept until that transaction ends. Transactions are seen where the
307
+ driver says them: a `begin` or savepoint through `query`, or the driver's own
308
+ `tx`, so a host that opens one some other way must not read through the store
309
+ inside it. Drivers naming one `connection` (@yaks/sql `Driver`), as every driver
310
+ over a Durable Object's storage does, keep one memory between them.
311
+
312
+ A file keeps a log of which entity each write named, `entity_written`, so
313
+ another connection's commit lets go of just the entities it wrote: a model turn
314
+ reading the same thousand lines of a transcript each step reads again only the
315
+ ones that changed, while other processes commit to the file. Triggers on the
316
+ spine, the graves and every component's table write it, in the same transaction
317
+ as the rows, whoever wrote them, raw SQL included; it keeps about its newest
318
+ 65,536 rows. Where it can't say what moved, every entity is let go, as before:
319
+ for a connection that fell further behind, over a file whose tables lack those
320
+ triggers (one an older install made), and for a store reading a stored value
321
+ through a table other than its own and @yaks/blob's, whose text no write changes
322
+ under an address. A store in memory has no other connection and keeps no log.
323
+
324
+ Memory keeps up to 4 MiB of entities, and an entity for every 2 KiB of that;
325
+ `base.memory` gives a store more, as the box's host gives each of its stores 32
326
+ MiB. A read of more than a quarter of those entities is a scan, read through and
327
+ not kept, so it pushes out nothing read again and again.
328
+
329
+ An entity a `patch` writes is not read back to be known: what it held before and
330
+ what the patch said make what it holds after, kept once the transaction commits.
331
+ A value storage could return differently than it was given (a number into a text
332
+ column, a derived property, a default the clock fills) leaves that entity to be
333
+ read, as does a transaction that rolls back or a number a patch takes away. What
334
+ memory knows an entity lacks, a patch writes in one statement, as it does a new
335
+ entity's components, rather than updating first and inserting after.
336
+
337
+ The spines a patch asks about (an eid's integer id, number and grave) are kept
338
+ the same way, so the patches one transaction makes read each entity's once. A
339
+ statement that may move a spine lets them all go, unless the write it belongs to
340
+ names its entities (a patch, a removal, a revival): then theirs go and no
341
+ others. Those kept inside a transaction that rolls back go with it.
342
+
343
+ A query's rows are kept as well, once it is asked a second time (most of what a
344
+ write asks, it asks once), while no table its answer stands on has been written:
345
+ every write statement moves its table's count, and an answer is good while the
346
+ counts of the tables it reads (and the graves, and the archetype catalog) stand
347
+ where they were. A query that requires no component row (`!doc`) stands on every
348
+ entity. Text, nearness, edges, walks, backlinks, computed and derived properties
349
+ and time phrases are read every time, as is anything a transaction that still
350
+ owes archetype pointers asks of the catalog.
351
+
352
+ An answer also stands through a patch that moved nothing it selects: where the
353
+ query asks about each entity alone (no path through a reference, no `.after`
354
+ cursor) and memory knows what each entity the patch wrote held before and after,
355
+ an entity selected neither before nor after leaves the answer as it was. So does
356
+ a removal of an entity the answer selected neither alive nor buried. A write the
357
+ store does not see whole (raw SQL) moves the counts alone.
358
+
359
+ ## API
360
+
361
+ `storage(driver, vocab, base?)` returns a synchronous `Store`:
362
+
363
+ | Method | Result |
364
+ | ---------------------------- | ------------------------------------------------------------------------ |
365
+ | `worn(comp, prop)` | Whether a property value implies component presence |
366
+ | `ddl()` | Schema statements derived from the vocabulary |
367
+ | `grown()` | Statements adding columns missing from existing tables |
368
+ | `install()` | Creates/updates schema, indexes, metadata, and archetype classification |
369
+ | `raise(comps?)` | Makes components' tables as their first write would, for raw SQL writers |
370
+ | `read(query, opts?, comps?)` | Matching bundles, read as one snapshot without taking the write lock |
371
+ | `rows(query, opts?)` | Raw result rows |
372
+ | `screen(query, opts?)` | A statement selecting the ids a query admits, compiled as reads are |
373
+ | `get(eids, comps?)` | Those entities as stored, read without taking the write lock |
374
+ | `tx(body)` | Runs the callback in a transaction and returns its result |
375
+ | `watch(comp, heard)` | Hears each new `comp` row another connection adds; answers a stop |
376
+
377
+ A component's table is made by the first write that names it, not by
378
+ `install()`: an empty store holds the spine, the graves, the archetype
379
+ descriptors and what its host keeps of its own, and a table only for each word
380
+ written to it (./raise.ts). The write makes the table, its indexes, the
381
+ `doc_value` view for `doc`, the log's triggers in a file, and each statement
382
+ `base.over` gives that rests on it, in its own transaction and before its rows,
383
+ so a trigger sees them. A statement **rests on** the component tables it is on,
384
+ reads or writes, and on whatever the objects it names rest on (a search index on
385
+ the text view it reads), and is made once every one of them stands. A read of a
386
+ component with no table answers as one worn by no entity, through the dialect
387
+ and through every derived expression that names its table (@yaks/sql
388
+ `absentDialect`, `absentDerived`). The `server_meta` row `tables` lists the
389
+ component tables the file holds, recorded by each install and kept by each write
390
+ that makes one, so a reader knows from one row; a file no install of this code
391
+ recorded holds every table, as the install that made it did. A writer that fills
392
+ a table in raw SQL makes it first with `store.raise(comps)`.
393
+
394
+ `install()` preserves existing data, adds missing columns, and rebuilds a table
395
+ whose foreign keys or checks (a reference's death word, an enum) no longer match
396
+ the vocabulary, then retires obsolete vocabulary indexes and creates the
397
+ declared ones. When a text property becomes a reference, including a `keep`
398
+ reference with no foreign key, it resolves each stored eid to the entity spine's
399
+ integer id during the rebuild. A reference with a foreign key can resolve back
400
+ to eid text when its declaration reverses. A `keep` reference has no physical
401
+ key identifying its old interpretation, so a code rollback must retain its
402
+ current declaration. A value that cannot resolve leaves the old table untouched
403
+ and reports an error. A table whose rows the new shape would refuse, such as a
404
+ value an enum no longer lists, is left as it stood and reported through
405
+ `base.report` (the console by default): its rows need an application migration
406
+ that prepares them. It initializes the store epoch and number sequence and runs
407
+ bounded `PRAGMA optimize` for file-backed drivers, so the planner can use table
408
+ statistics. A database in memory that nothing has installed into is made from a
409
+ template: the first one a process makes for a vocabulary is kept, and each later
410
+ one is a copy of it, since copying a schema is a page copy and making one is
411
+ hundreds of statements (@yaks/sql `Driver.template`).
412
+
413
+ A file-backed store reads and writes only the schema already installed. Bind it
414
+ with `storage()` to query an existing graph; call `install()` explicitly when
415
+ creating or upgrading that graph. Opening a store does not install schema, run
416
+ migrations, inspect every table, analyze indexes, or repair objects another
417
+ connection removed. A query needing a missing table or column fails rather than
418
+ changing the file. An explicit install over a current file changes no schema,
419
+ but may update planner statistics. Installation belongs to the graph's
420
+ installer, not to commands opening it.
421
+
422
+ In-memory stores belong to their caller alone and install automatically at the
423
+ first operation unless a schema readiness check asserts they are prepared.
424
+
425
+ A **schema readiness check** is a single-owner host's assertion that the bound
426
+ vocabulary's schema, derived columns, metadata and archetypes already stand.
427
+ `base.schemaReady` runs at the first graph operation, not at binding. True skips
428
+ installation and schema inspection; false falls back to installation. The host
429
+ must bind a new store when its schema changes. File drivers ignore the check:
430
+ only an explicit `install()` changes their schema. Explicit `install()` always
431
+ validates.
432
+
433
+ ```ts
434
+ import { storage } from '@yaks/sqlite'
435
+ import { open } from '@yaks/sqlite/db'
436
+ import { loadVocab } from '@yaks/vocab'
437
+ import { equal } from '@yaks/testing'
438
+
439
+ let sql = open(':memory:')
440
+ try {
441
+ let vocab = loadVocab({ $defs: {} })
442
+ storage(sql, vocab).install()
443
+ // A single-owner host can also verify a persisted schema stamp here.
444
+ let store = storage(sql, vocab, { schemaReady: () => true })
445
+ equal(store.get(['absent']), [])
446
+ } finally {
447
+ sql.close()
448
+ }
449
+ ```
450
+
451
+ A transaction provides `read`, `get(eids, comps?)`, `patch`, `remove`, `revive`,
452
+ `doom`, and `bindings`. `get` retrieves entities including tombstones, whole or
453
+ carrying only the components `comps` names, and reads no other table. `patch`
454
+ returns newly created identities, with `num` when numbering is enabled. `doom`
455
+ resolves cascading deletion, and `bindings` evaluates rules against pending
456
+ changes.
457
+
458
+ SQL transactions commit on callback completion and roll back on failure; a
459
+ promise-returning callback is awaited. Nested calls use savepoints. A driver
460
+ with `file: true` starts the outer transaction with `BEGIN IMMEDIATE`, acquiring
461
+ the write lock before reads. A driver supplying its own `tx` controls
462
+ transaction behavior; Durable Object callbacks must remain synchronous. A read
463
+ on its own (`get`, `read`) opens a transaction only on a `file: true` driver,
464
+ where it begins deferred for one snapshot; on any other connection nothing else
465
+ commits between its statements, and a read has nothing to roll back.
466
+
467
+ `base` includes `@yaks/sql` bind options (`derived`, `backed`, `extend`, `now`,
468
+ and a custom dialect), merged with per-read options. A `derived` entry's `text`
469
+ expression also resolves its column in the `doc_value` view.
470
+
471
+ A component declared `computed: true` gets no table: it is read through the
472
+ [backing](../sql/README.md#computed-components) another package supplies
473
+ (`Backing`), as @yaks/journal's `_tx` and `_change` are. The store tags each
474
+ backing with `tagOf(epoch, comp)` once the first install has minted its epoch
475
+ (read from metadata without minting), so a backed entity's eid names it in this
476
+ store and no other. `read` and `get` return such entities like any other;
477
+ `patch` refuses one, since nothing writes it. `number` controls human numbering,
478
+ and a patch stating `entity.num` sets, changes or clears (`null`) an entity's
479
+ number.
480
+
481
+ ### Read options
482
+
483
+ [Derived properties](../sql/README.md#derived-properties) and
484
+ [backings](../sql/README.md#computed-components) use the same expressions in
485
+ filters and gathered bundles. This example reads a computed property from an
486
+ expression and a computed component from rows owned outside the spine:
487
+
488
+ ```ts
489
+ import { open } from '@yaks/sqlite/db'
490
+ import { columns, storage } from '@yaks/sqlite'
491
+ import { as, col, fn, lit, select } from '@yaks/sql'
492
+ import { loadVocab } from '@yaks/vocab'
493
+ import { equal, throws } from '@yaks/testing'
494
+
495
+ let vocab = loadVocab({
496
+ $defs: {
497
+ note: {
498
+ component: true,
499
+ type: 'object',
500
+ properties: {
501
+ title: { type: 'string' },
502
+ data: { type: 'object' },
503
+ loud: { type: 'string', computed: true },
504
+ },
505
+ },
506
+ event: {
507
+ component: true,
508
+ computed: true,
509
+ type: 'object',
510
+ properties: {
511
+ title: { type: 'string' },
512
+ },
513
+ },
514
+ },
515
+ })
516
+ let sql = open(':memory:')
517
+ try {
518
+ let store = storage(sql, vocab, {
519
+ derived: {
520
+ 'note.loud': {
521
+ tag: 'text',
522
+ expr: () => fn('upper', col('title', 'note')),
523
+ },
524
+ },
525
+ backed: {
526
+ event: {
527
+ rows: select({
528
+ cols: [as(lit(1), 'entity'), as(lit('Started'), 'title')],
529
+ }),
530
+ },
531
+ },
532
+ })
533
+ store.tx((tx) =>
534
+ tx.patch([{
535
+ entity: { eid: 'a' },
536
+ note: { title: 'Hello', data: { colors: ['blue'] } },
537
+ }])
538
+ )
539
+ equal(store.read('.note.loud=HELLO')[0].note, {
540
+ title: 'Hello',
541
+ data: { colors: ['blue'] },
542
+ loud: 'HELLO',
543
+ })
544
+ equal(columns(sql, 'note'), ['entity', 'title', 'data'])
545
+ equal(store.worn('note', 'loud'), true)
546
+ let event = store.read('.event')[0]
547
+ equal(store.get([event.entity.eid])[0].event, { title: 'Started' })
548
+ await throws(() =>
549
+ store.tx((tx) =>
550
+ tx.patch([
551
+ { entity: { eid: event.entity.eid }, event: { title: 'Changed' } },
552
+ ])
553
+ ), 'computed')
554
+ } finally {
555
+ sql.close()
556
+ }
557
+ ```
558
+
559
+ ### The driver
560
+
561
+ The root package does not open connections. It runs on `@yaks/sql`'s synchronous
562
+ `Driver`, which takes a statement as a node of `@yaks/sql`'s AST, renders it and
563
+ returns the rows. Every statement this package sends is built as a node.
564
+
565
+ `run` optionally executes writes without materializing rows. `tx` is for engines
566
+ such as a Durable Object that provide a transaction API instead of accepting
567
+ transaction SQL; it must support nesting. `arms` sets the compound-query group
568
+ size, defaulting to `@yaks/sql`'s conservative `ARMS`; the embedded driver uses
569
+ `STOCK`. Query values use bound parameters.
570
+
571
+ `@yaks/sqlite/db` exports `open(path)` and nothing of the embedded driver
572
+ itself, so a driver swap touches only this package. `open` creates a missing
573
+ directory and turns on foreign keys; a file also runs in WAL mode with
574
+ `synchronous = normal`, a 64 MiB WAL, a 64 MiB page cache, and a one-minute busy
575
+ timeout. A WAL that starts over is cut back to the commit that starts it, so
576
+ every later frame is appended: kept whole, it is written over in place, and
577
+ since a frame never fills a file page, each write reads the page it covers back
578
+ from the disk wherever memory pressure dropped it, on the committing thread. No
579
+ commit checkpoints: once a commit leaves the WAL at 64 MiB, a hook asks the
580
+ process's checkpoint thread (./checkpoint.ts), which runs a `PASSIVE` checkpoint
581
+ on a connection of its own, so the sync it waits for holds neither the
582
+ committing thread nor any other writer. The thread holds no process open; one
583
+ that exits mid-checkpoint leaves the WAL for the next commit past the mark to
584
+ ask again. The busy timeout sleeps the thread that asked, so a graph's write
585
+ asks the store's `tx` with `wait: false`: a lock another connection holds
586
+ refuses at once, `retryable: true`, and @yaks/graph waits for that writer
587
+ between tries, the same minute, with the thread free. Closing a connection
588
+ cancels its queued checkpoints immediately and waits only for a checkpoint
589
+ already running to close its own handle. Close starts no checkpoint, so the next
590
+ command appends to the log it left. A copy of the file takes its `-wal` beside
591
+ it, or is a `.backup` inside one read transaction (`bin/copy-db`): a bare
592
+ `.backup` starts over whenever another connection commits, and on a busy file
593
+ never ends. A new file starts in incremental auto-vacuum mode, so the pages a
594
+ delete frees can be given back (`reclaim`, under Owed work). A file made before
595
+ keeps its mode until a `VACUUM`. The driver uses `DENO_SQLITE_PATH` when set,
596
+ then the checkout pin in `YAK_SQLITE_PATH`, then the platform's system library.
597
+ This module uses Deno environment/FFI APIs. The root adapter can instead receive
598
+ another runtime's synchronous SQLite driver.
599
+
600
+ A file driver also has `watch`: every 5 ms it reads the file's `data_version`,
601
+ which moves when another connection commits, and calls back when it moved. A
602
+ look costs a few microseconds, and its timer holds no process open.
603
+ `Store.watch(comp, heard)` builds on it: on each call it reads the component
604
+ table's newest id, one seek, and calls `heard` only when it grew, which is a row
605
+ added since, as an entity's id is never reused. A store in memory has no
606
+ `watch`, since only its own connection writes it.
607
+
608
+ The embedded driver emits one `sql` span per statement while
609
+ [@yaks/trace](../trace/README.md) observes it or an enclosing graph operation.
610
+ Names contain the logical table and verb, such as `doc select` or
611
+ `entity
612
+ update`; transaction names omit savepoint identifiers, and pragma names
613
+ omit arguments and values. SQL text and bound values never enter the trace. A
614
+ successful span counts returned rows for reads and affected rows for writes,
615
+ including writes without `returning`. Each attempted statement also charges
616
+ `statements`, `rowsRead` and `rowsWritten` to its span and open ancestors;
617
+ failed statements count once without charging a stale affected-row count. These
618
+ inclusive metrics use the returned rows and native changes count, with no
619
+ additional SQL. SQL nests under the current phase, hook, rule, read or
620
+ transaction. No subscriber means no statement metadata, spans, clocks or counts
621
+ are allocated.
622
+
623
+ ```ts
624
+ import { open } from '@yaks/sqlite/db'
625
+ import { insert } from '@yaks/sql'
626
+ import { record } from '@yaks/trace'
627
+ import { equal } from '@yaks/testing'
628
+
629
+ let sql = open(':memory:')
630
+ try {
631
+ sql.query({ t: 'create table', name: 'note', cols: [{ name: 'title' }] })
632
+ let captured = record(
633
+ sql,
634
+ () => sql.query(insert('note', { title: 'Hello' })),
635
+ )
636
+ equal(captured.spans[0].name, 'note insert')
637
+ equal(captured.spans[0].counts, {
638
+ rows: 1,
639
+ statements: 1,
640
+ rowsRead: 0,
641
+ rowsWritten: 1,
642
+ })
643
+ } finally {
644
+ sql.close()
645
+ }
646
+ ```
647
+
648
+ ## Schema installation
649
+
650
+ `schema(vocab, reads?, file?)` builds statements for a fresh database. Set
651
+ `file` for a database other connections can write: archetype triggers keep a
652
+ table token so an unrelated peer commit need not reread its descriptors.
653
+ Single-owner stores observe their connection's writes without persistent tokens.
654
+ `retabled(driver, vocab, reads?)` keeps an identical document view and replaces
655
+ only a changed one, and installs or retires those triggers according to
656
+ `driver.file`. `standing(driver,
657
+ vocab)` reads existing tables;
658
+ `grown(vocab, standing)` builds missing-column statements, and
659
+ `refit(vocab, standing)` builds table-rebuild statements. `fit(driver, vocab)`
660
+ executes growth and rebuilds, returning errors for tables whose existing values
661
+ cannot fit. `Store.install()` also maintains indexes, metadata, and archetypes.
662
+ Drivers with `statistics` enabled keep planner statistics at installation:
663
+ `sampled` (a file's) permits bounded analysis; a full-analysis engine supplies a
664
+ `bytes` getter without a row scan. Installation analyzes nothing, since one
665
+ table's analysis holds the write lock while it reads that table: it writes the
666
+ tables owed an analysis into its receipt beside the schema fingerprint, and
667
+ `analyze(tables?)` works off up to that many, each in its own unit, answering
668
+ how many stay owed. A host calls it away from the request that installed (a
669
+ Durable Object, from its alarm); on a file, `work` does a table a window. A
670
+ table is owed when it held no rows at its last analysis and holds some now, when
671
+ a schema change leaves a populated table or index without statistics, and every
672
+ table holding rows is owed when stored bytes grow tenfold. Empty tables are
673
+ remembered; their bounded presence probes cost zero billed rows while they stay
674
+ empty. This measures byte growth, not row density. A store with existing
675
+ statistics adopts them once without reanalysis. Reads and writes do not refresh
676
+ statistics; a host calls `install()` at deployment. Optimize decides none of it:
677
+ empty tables retain no statistics row, and a table whose size it guesses wrong
678
+ from one page is named on every run and counted end to end.
679
+
680
+ ```ts
681
+ import { open } from '@yaks/sqlite/db'
682
+ import { columns, storage } from '@yaks/sqlite'
683
+ import { loadVocab } from '@yaks/vocab'
684
+ import { equal, throws } from '@yaks/testing'
685
+
686
+ let sql = open(':memory:')
687
+ try {
688
+ let first = loadVocab({
689
+ $defs: {
690
+ note: {
691
+ component: true,
692
+ type: 'object',
693
+ properties: { title: { type: 'string' } },
694
+ },
695
+ },
696
+ })
697
+ let old = storage(sql, first)
698
+ old.tx((tx) => tx.patch([{ entity: { eid: 'a' }, note: { title: 'Kept' } }]))
699
+ let next = loadVocab({
700
+ $defs: {
701
+ note: {
702
+ component: true,
703
+ type: 'object',
704
+ properties: {
705
+ title: { type: 'string' },
706
+ summary: { type: 'string', default: 'Empty' },
707
+ },
708
+ },
709
+ },
710
+ })
711
+ let store = storage(sql, next)
712
+ equal(store.grown().length, 1)
713
+ store.install()
714
+ equal(columns(sql, 'note'), ['entity', 'title', 'summary'])
715
+ equal(store.get(['a'])[0].note, { title: 'Kept', summary: 'Empty' })
716
+ equal(store.grown(), [])
717
+ let constrained = loadVocab({
718
+ $defs: {
719
+ note: {
720
+ component: true,
721
+ type: 'object',
722
+ properties: {
723
+ title: { type: 'string', enum: ['Kept', 'Other'] },
724
+ summary: { type: 'string', default: 'Empty' },
725
+ },
726
+ },
727
+ },
728
+ })
729
+ let checked = storage(sql, constrained)
730
+ checked.install()
731
+ await throws(() =>
732
+ checked.tx((tx) =>
733
+ tx.patch([
734
+ { entity: { eid: 'a' }, note: { title: 'Refused' } },
735
+ ])
736
+ ), 'CHECK')
737
+ equal(checked.get(['a'])[0].note, { title: 'Kept', summary: 'Empty' })
738
+ } finally {
739
+ sql.close()
740
+ }
741
+ ```
742
+
743
+ ### Following a composed schema
744
+
745
+ A host that writes a file brings it to everything the file needs as it opens:
746
+ the store's own statements and every statement beside them (blob storage,
747
+ migration control, a plugin's tables, the full-text indexes). Their **print** is
748
+ `printOf(store.print(), beside)`; `printFor(vocab, derived?, file?)` says what
749
+ `store.print()` would, for a host that composes its print before it binds a
750
+ store. `follow(driver, print, pass)` runs nothing where the file has recorded
751
+ the print (`printed(driver, print)`, a `server_meta` row `schema:<print>`), and
752
+ otherwise runs `pass` and records the print, unless `pass` answers false for
753
+ something it left undone. `add(driver, stmts)` is the pass for statements that
754
+ only add. `forget(driver, print)` makes the next opener run the pass again, for
755
+ a host whose file something that keeps no print may have changed; the store's
756
+ install receipt goes with it, so `install()` looks at the file again too.
757
+
758
+ A host whose vocabulary is the whole of what its file holds also gives `follow`
759
+ what the schema names, `follow(driver, print, pass, { vocab, beside })`. Before
760
+ the pass, the file then sheds what it holds beyond that (`shed`): a component
761
+ table that neither `vocab` nor a statement of `beside` makes, once it holds no
762
+ rows, and a column the statement making its table lacks, once no row holds a
763
+ value in it, with each index, trigger and view that names the column. A column
764
+ SQLite will not drop (a key, a unique column, one a check names) stands. The
765
+ pass makes such an index, trigger or view again where the schema still wants it.
766
+ A host that decided a column goes, whatever it holds, drops it the same way with
767
+ `unseat(driver, [[table, column]])`, and the next `install()` makes again what
768
+ went with it. A file that shed something forgets every other print it recorded,
769
+ so an opener of a vocabulary that still named it runs its pass again and adds it
770
+ back. A host whose vocabulary may shrink for a while and grow back, such as an
771
+ application whose older release is a rollback away, gives nothing, and its file
772
+ keeps everything.
773
+
774
+ A table that still holds rows is never dropped. It stands as it was, rows,
775
+ indexes and all; nothing the vocabulary declares reads it, and an entity that
776
+ wears it keeps the archetype that says so. Once a migration has moved or deleted
777
+ its rows, the next pass drops it: the first print the file follows after that,
778
+ or sooner where the host forgets the print it stands at. A column that still
779
+ holds a value stays the same way, and fitting keeps it through a rebuild.
780
+
781
+ A reader binds `lacking(driver, vocab)`: its `derived` reads a column the file
782
+ does not have yet as absent properties, and its `absent` names the component
783
+ tables the file does not have yet, which read as worn by no entity (@yaks/sql's
784
+ `absent` option).
785
+
786
+ Finding that out reads the whole of `sqlite_schema`, so a writer records it.
787
+ `survey(driver, vocab, derived?)` (`@yaks/sqlite/survey`) writes what a look at
788
+ the file finds (the lacking columns, absent tables, missing indexes and tables
789
+ the log does not follow) as the `server_meta` row `surveyed:<print>`, beside the
790
+ `pragma schema_version` it was taken at. `surveyed(driver, vocab,
791
+ derived?)`
792
+ reads it back while that version stands, and is undefined once anything has
793
+ changed the schema, so a reader and memory look at the file again until a writer
794
+ records the next survey.
795
+
796
+ ## The storage layout
797
+
798
+ - `entity`: integer `id`, public `eid`, optional `num`, and
799
+ [archetype](../archetype/README.md) pointer.
800
+ - `tombstone`: deletion records excluded from normal queries.
801
+ - One table per stored component, keyed by integer `entity`, made by the first
802
+ write naming the component, and none for a computed one. References store
803
+ integer target ids; ordinary references have foreign keys, while `keep`
804
+ references can preserve historical ids. A component without properties is
805
+ represented by the existence of its row.
806
+ - Indexes from vocabulary `unique`/`index` declarations. SQLite enforces unique
807
+ constraints, including competing inserts.
808
+ - `doc_value`: a read view when the vocabulary declares `doc`.
809
+ - `server_meta`: database metadata, separate from graph entities, among it
810
+ `tables`, the component tables the file holds.
811
+ - `entity_series` and triggers: each series' human-number high-water mark, by
812
+ its letter.
813
+ - `entity_written` and triggers, in a file: which entity each write named, in
814
+ commit order, for the other connections' memory (under Read).
815
+
816
+ Required properties become NOT NULL, enums become CHECK constraints, and
817
+ declared defaults fill omitted values. A `{ "now": true }` default uses the
818
+ current time for new writes. Added columns preserve literal defaults and CHECK
819
+ constraints; time defaults do not backdate existing rows. Declared partial
820
+ unique indexes apply only where their `present` properties have values.
821
+
822
+ <a id="the-batch-as-a-world-the-overlay"></a>
823
+
824
+ ### Querying pending changes with an overlay
825
+
826
+ An **overlay** represents pending patches as common table expressions in one SQL
827
+ statement. `overlay(driver, vocab, bundles, covers)` lets rules read the state
828
+ those patches would produce. It returns common table expressions in `with`, a
829
+ component source-name resolver `at`, removed-row information `gone`, covered
830
+ component names in `covers`, and eid-to-integer mappings in `ids`. Bound
831
+ parameters are carried by the common table expression nodes.
832
+
833
+ Each affected component gets a common table expression combining untouched
834
+ committed rows with merged pending rows. Component removals and deleted entities
835
+ are excluded. New entities receive temporary negative integer ids so references
836
+ within the pending changes can join correctly. The common table expression
837
+ exists only for its SQL statement; it creates no database object.
838
+
839
+ The `gone` data lets rules distinguish a component removed by this write from
840
+ one that never existed. `rules.ts` implements the `-comp` deletion clause
841
+ through an SQL extension. Against committed data without an overlay, that clause
842
+ is false.
843
+
844
+ The overlay avoids temporary tables, which Durable Object SQLite rejects and
845
+ which could redirect unqualified writes while present. It reads the committed
846
+ table directly and materializes only affected data. Pass the component names the
847
+ rules inspect; untouched components need no overlay. Dialect hooks including
848
+ `table`, `source`, and `refEqAt` keep references and correlated subqueries on
849
+ the same pending state. This package does not provide a browser cache
850
+ implementation.
851
+
852
+ ```ts
853
+ import { open } from '@yaks/sqlite/db'
854
+ import { matched, overlay, storage } from '@yaks/sqlite'
855
+ import { match } from '@yaks/graph'
856
+ import { loadVocab } from '@yaks/vocab'
857
+ import { docDoc } from '@yaks/doc'
858
+ import { equal } from '@yaks/testing'
859
+
860
+ let sql = open(':memory:')
861
+ try {
862
+ let vocab = loadVocab(docDoc)
863
+ let store = storage(sql, vocab)
864
+ store.tx((tx) =>
865
+ tx.patch([{ entity: { eid: 'a' }, doc: { title: 'Before' } }])
866
+ )
867
+ let bundles = [{ entity: { eid: 'a' }, doc: { title: 'After' } }]
868
+ let over = overlay(sql, vocab, bundles, ['doc'])
869
+ let hits = matched(
870
+ sql,
871
+ match('.doc.title=After'),
872
+ vocab,
873
+ {},
874
+ { at: over.at },
875
+ over.with,
876
+ )
877
+ equal(hits.map((b) => b.entities), [['a']])
878
+ equal(
879
+ store.tx((tx) =>
880
+ tx.bindings([match('.doc.title=After')], bundles, ['doc'])
881
+ )[0],
882
+ hits,
883
+ )
884
+ equal(store.read('.doc.title=After'), [])
885
+ } finally {
886
+ sql.close()
887
+ }
888
+ ```
889
+
890
+ ### The store's own key/value
891
+
892
+ `meta(driver)` reads, writes, and clears server_meta. These values have no
893
+ entity identity and do not appear in bundles or graph queries.
894
+
895
+ ```ts
896
+ import { open } from '@yaks/sqlite/db'
897
+ import { EPOCH, epoch, epochAt, META, meta } from '@yaks/sqlite'
898
+ import type { Column } from '@yaks/sql'
899
+ import { equal } from '@yaks/testing'
900
+ let sql = open(':memory:'), m = meta(sql)
901
+ try {
902
+ equal(epochAt(sql), undefined)
903
+ let key: Column = { name: 'k', type: 'text', pk: true }
904
+ let value: Column = { name: 'v', type: 'text', notNull: true }
905
+ sql.query({ t: 'create table', name: META, cols: [key, value] })
906
+ m.set('sweep', '42')
907
+ equal(m.get('sweep'), '42')
908
+ m.del('sweep')
909
+ equal(m.get('sweep'), undefined)
910
+ equal(epoch(sql), m.get(EPOCH))
911
+ equal(epoch(sql), epochAt(sql))
912
+ } finally {
913
+ sql.close()
914
+ }
915
+ ```
916
+
917
+ `install()` initializes the epoch. A missing epoch means an existing client
918
+ cursor cannot be validated against this store. `META` exports the table name
919
+ `server_meta`, which avoids conflict with a component named `meta`. Installation
920
+ can reuse an existing table with the expected shape.
921
+
922
+ Whole-entity reads bind identity sets through `json_each(?)`, requiring SQLite
923
+ JSON support. The selected ids are fixed before components are gathered, so a
924
+ concurrent writer cannot change window membership partway through the read.
925
+
926
+ ### The plugins a store requires
927
+
928
+ A **requirement** is a plugin a store's data needs: one that shaped how its rows
929
+ are written, so a host without it would read or write them wrongly
930
+ ([@yaks/host](../host/README.md#required-plugins)). `requires(driver, plugins)`
931
+ records each as the `server_meta` row `required:<plugin>`, and
932
+ `requirements(driver)` reads them back in one read.
933
+
934
+ ```ts
935
+ import { open } from '@yaks/sqlite/db'
936
+ import { META, requirements, requires } from '@yaks/sqlite'
937
+ import { equal } from '@yaks/testing'
938
+ let sql = open(':memory:')
939
+ try {
940
+ equal(requirements(sql), [])
941
+ sql.query({
942
+ t: 'create table',
943
+ name: META,
944
+ cols: [{ name: 'k', type: 'text', pk: true }, { name: 'v', type: 'text' }],
945
+ })
946
+ requires(sql, ['@yaks/blob'])
947
+ equal(requirements(sql), ['@yaks/blob'])
948
+ } finally {
949
+ sql.close()
950
+ }
951
+ ```
952
+
953
+ A plugin removed from a store on purpose drops its requirement with one
954
+ statement:
955
+
956
+ ```sh
957
+ sqlite3 ~/.yak/yak.db "delete from server_meta where k = 'required:@yaks/journal'"
958
+ ```
959
+
960
+ ### Archetype reads
961
+
962
+ Every file keeps each entity's component-set pointer (`entity.archetype`) and
963
+ the descriptors it names, whatever its vocabulary declares, and installation
964
+ classifies the rows a file already held. Load `archetypeDoc` and install the
965
+ `archetypes()` graph plugin from `@yaks/archetype` for a store to show them:
966
+ `entity.archetype` on what it reads, descriptors as entities, and presence and
967
+ kind queries expose their descriptors. Without them the pointer and its
968
+ descriptors are the store's own bookkeeping. Planning still uses the catalog. A
969
+ **catalog** is a lazy snapshot that maps matching archetypes to their integer
970
+ ids. Presence and kind queries load a catalog; value-only queries do not. A page
971
+ driven from its own component's table screens other components by the catalog
972
+ only while it is held in memory, and probes their tables per row otherwise.
973
+ Applications using `catalog(driver)` to compile their own queries must compile
974
+ and execute within one read transaction, as this package's read path does.
975
+
976
+ Whole-entity reads group entities by the component tables their archetype
977
+ identifies and query only owners with each component. `get` uses this
978
+ information even for single entities. Readers ignore tables outside their
979
+ vocabulary without changing the descriptor. Only table sets are cached, allowing
980
+ rollback, other writers, and schema changes to remain visible.
981
+
982
+ No read asks a table whether it holds an entity. A whole read that meets an
983
+ entity with no archetype has a broken row before it, and throws `Unpointed`; the
984
+ store tells its `report`, classifies the entity from the rows it holds, the one
985
+ place tables are asked, and reads again.
986
+
987
+ Every `Store.tx(body)` maintains archetype pointers for patches, removals, and
988
+ revivals made through its `Tx`. The connection's **ledger** (`ledger(driver)`)
989
+ hears each component row that came or went since an entity's pointer was
990
+ written, and follows savepoints and rollbacks; `owed()` names the entities still
991
+ needing classification when the callback finishes, and `held(eid, pointed)` says
992
+ what one holds: its pointer's tables, amended by the rows that moved. Within the
993
+ transaction, `Tx.get` and a removal go by that, and the settlement classifies
994
+ what is owed from it, so none of them asks a table. `Tx.read` overlays those
995
+ pending table sets on the catalog without writing an intermediate archetype.
996
+
997
+ A raw SQL writer, past the store, must call `reclassify(driver, eids)` inside
998
+ its transaction after changing component rows: whole reads, presence filters and
999
+ deletes all go by the pointer. It returns changed pointers and new descriptors
1000
+ as bundles that the application can broadcast; descriptor entities and unknown
1001
+ ids are ignored. `drift(driver)` is the audit (`archetype_check`): it reads
1002
+ every owner's presence and counts the pointers that disagree, writing nothing;
1003
+ `mend(driver)` classifies every one it finds again, a few thousand to a unit. An
1004
+ incomplete catalog reports `Unpointed`; a store repairs it before planning
1005
+ again.
1006
+
1007
+ The same diagnostic sequence is exercised by `inspect_test.ts`; installation and
1008
+ repair are outside its measured assertions.
1009
+
1010
+ ```ts ignore
1011
+ import { open } from '@yaks/sqlite/db'
1012
+ import {
1013
+ drift,
1014
+ identity,
1015
+ inspect,
1016
+ mend,
1017
+ reclassify,
1018
+ storage,
1019
+ } from '@yaks/sqlite'
1020
+ import { archetypeDoc } from '@yaks/archetype'
1021
+ import { docDoc } from '@yaks/doc'
1022
+ import { loadVocab } from '@yaks/vocab'
1023
+ import { by, lit } from '@yaks/sql'
1024
+ import { equal } from '@yaks/testing'
1025
+
1026
+ let sql = open(':memory:')
1027
+ try {
1028
+ // Inspection needs exact component populations before its first report.
1029
+ let store = storage(sql, loadVocab([archetypeDoc, docDoc]), {
1030
+ counts: 'eager',
1031
+ })
1032
+ store.tx((tx) => tx.patch([{ entity: { eid: 'a' }, doc: { title: 'A' } }]))
1033
+ equal(drift(sql).drifted, 0)
1034
+ equal(identity(sql, 'a').tables, ['doc'])
1035
+ equal(inspect(sql).shown.find((t) => t.name == 'doc')?.rows, 1)
1036
+ sql.query({
1037
+ t: 'update',
1038
+ table: 'entity',
1039
+ set: { archetype: lit(null) },
1040
+ where: by({ eid: 'a' }),
1041
+ })
1042
+ equal(drift(sql).sample, ['a'])
1043
+ equal(mend(sql), 1)
1044
+ store.tx(() => {
1045
+ sql.query({ t: 'delete', from: 'doc' })
1046
+ reclassify(sql, ['a'])
1047
+ })
1048
+ equal(drift(sql).drifted, 0)
1049
+ equal(store.read('.doc'), [])
1050
+ } finally {
1051
+ sql.close()
1052
+ }
1053
+ ```
1054
+
1055
+ ### Exact global counts
1056
+
1057
+ A **population** is the number of live entities wearing one archetype. The
1058
+ adapter keeps populations in `_yaks_population`, with `_yaks_membership` mapping
1059
+ component names to the archetypes a live entity wears. Entity archetype and
1060
+ tombstone triggers update populations in the same transaction as the owner; an
1061
+ archetype's membership rows come with its first wearer and go with its last.
1062
+ Updating an ordinary property without changing its archetype does not write
1063
+ either metadata table.
1064
+
1065
+ The first unscoped global aggregate seeds populations by reading existing
1066
+ entities once, inside a transaction with its triggers. A rollback leaves neither
1067
+ behind. Stores that never ask for a global count incur no population upkeep;
1068
+ once activated, later openers keep persisted populations and triggers without
1069
+ recounting owners. This lazy activation is the default on both local and metered
1070
+ hosts. A caller that will count immediately can request `counts: 'eager'` to
1071
+ seed during installation instead. A local writer serving read-only readers can
1072
+ use that eager option so those readers find persisted populations without
1073
+ migrating on a read.
1074
+
1075
+ Unfiltered `.count`, `.component&.count` and `.tally=entity.archetype` read
1076
+ these metadata tables rather than scanning component or entity tables. Component
1077
+ counts seek only the worn archetypes containing that component, however many an
1078
+ entity wore before; tally work scales with the number of archetypes, not the
1079
+ number of entities. The contracts in `population_test.ts` check the live counts,
1080
+ rollback and reopen behavior with private fixtures; this example includes
1081
+ opening and installing the whole store.
1082
+
1083
+ ```ts ignore
1084
+ import { equal } from '@yaks/testing'
1085
+ import { archetypeDoc, archetypes } from '@yaks/archetype'
1086
+ import { graph } from '@yaks/graph'
1087
+ import { loadVocab } from '@yaks/vocab'
1088
+ import { open } from '@yaks/sqlite/db'
1089
+ import { storage } from '@yaks/sqlite'
1090
+
1091
+ let sql = open(':memory:')
1092
+ try {
1093
+ let vocab = loadVocab([archetypeDoc, {
1094
+ $defs: {
1095
+ entity: { component: true, type: 'object' },
1096
+ note: { component: true, type: 'object' },
1097
+ },
1098
+ }])
1099
+ let store = storage(sql, vocab)
1100
+ let g = graph({ storage: store, vocab, plugins: [archetypes()] })
1101
+ g.apply([{ entity: { eid: 'one' }, note: {} }])
1102
+ equal(store.rows('.note&.count'), [{ value: '', n: 1 }])
1103
+ } finally {
1104
+ sql.close()
1105
+ }
1106
+ ```
1107
+
1108
+ Filtered counts, derived components, custom backings and permission-scoped
1109
+ counts retain their ordinary query plans: their predicates inherently need to
1110
+ visit candidates. A global population cannot answer a caller-specific count
1111
+ without bypassing its permissions. Pending unclassified writes also use ordinary
1112
+ queries, so transactional reads never substitute a committed intermediate count.
1113
+
1114
+ ### Diagnostic tools
1115
+
1116
+ `inspect(driver, limit?, preferred?)` lists tables and indexes without scanning
1117
+ component rows. Component `rows` are exact live-owner counts from populations;
1118
+ infrastructure `rows` are `null` (unknown), never an implicit table count;
1119
+ `identity(driver, eid)` reports the archetype table set and tombstoning. Both
1120
+ cap inspection at 160 tables. The tools declared by `sqliteDoc` check foreign
1121
+ keys, SQLite integrity, and archetype pointers;
1122
+ `runs({ storage: storage(sql, vocab) }, { sample })` implements them on the
1123
+ application's connection. They report findings without repairing data.
1124
+
1125
+ ```ts
1126
+ import { open } from '@yaks/sqlite/db'
1127
+ import { storage } from '@yaks/sqlite'
1128
+ import { sqliteDoc } from '@yaks/sqlite/vocab'
1129
+ import { runs } from '@yaks/sqlite/tools'
1130
+ import { type Bundle, graph } from '@yaks/graph'
1131
+ import { loadVocab } from '@yaks/vocab'
1132
+ import { equal } from '@yaks/testing'
1133
+
1134
+ let sql = open(':memory:')
1135
+ try {
1136
+ let vocab = loadVocab(sqliteDoc)
1137
+ let g = graph({ vocab, storage: storage(sql, vocab) })
1138
+ await g.install()
1139
+ let checks = runs({ storage: storage(sql, vocab) }, { sample: 3 })
1140
+ let call = { entity: { eid: 'check' }, call: { args: {} } }
1141
+ let [clean] = await checks.storage_check(call, g) as Bundle[]
1142
+ equal(clean.finding, undefined)
1143
+ let [pointers] = await checks.archetype_check(call, g) as Bundle[]
1144
+ equal(pointers.finding, undefined)
1145
+ } finally {
1146
+ sql.close()
1147
+ }
1148
+ ```
1149
+
1150
+ ### Human numbering by series
1151
+
1152
+ [Human numbering](../id/README.md) is opt-in. A table of letters, component →
1153
+ letter (`{ number: { doc: 'D' } }`), numbers by series, and `{ number: true }`
1154
+ takes the table from the prefixes the vocabulary declares (@yaks/id
1155
+ `prefixes(vocab)`). An entity is numbered once, on the write that first gives it
1156
+ a component in the table, and holds `entity{prefix, num}`, so `D-1` and `M-1`
1157
+ are two entities. With two such components, the kind the vocabulary names picks
1158
+ the series (@yaks/id `seriesOf`). An entity given none is unnumbered and shows
1159
+ its short handle. Omitting `number` or setting it to false leaves new entities
1160
+ unnumbered. `@yaks/ram` accepts the same option.
1161
+
1162
+ Each series keeps its last number in `entity_series`, raised by insert/update
1163
+ triggers, and the next is the one after it, stepping over a number an entity
1164
+ already holds in the series. A spine made keeping `num` unique on its own is
1165
+ moved by `respine(driver)` without moving a row: the column keeping the old
1166
+ constraint is renamed `retired_num` and emptied, and a new `num` takes its
1167
+ numbers, so no reference to an entity is checked again. Only the numbered rows
1168
+ are written, and each trigger that stood on the spine is raised again.
1169
+
1170
+ A number given out before can stay the name of what it named once that entity is
1171
+ numbered again (@yaks/alias). `names`, `(prefix, num) => eid`, says where the
1172
+ entity keeping such a name lives (`aliasEid(format(prefix, num))`), and a series
1173
+ steps over a number kept so while the name stands. Clearing a number does not
1174
+ recycle it. A patch stating `entity{prefix, num}` gives its entity that id, born
1175
+ or not, or none for `num: null`; a `num` stated alone keeps the entity's prefix;
1176
+ an id another entity holds, a tombstone's included, is refused, since it is that
1177
+ entity's address (@yaks/graph `renumbering`).
1178
+
1179
+ ```ts
1180
+ import { open } from '@yaks/sqlite/db'
1181
+ import { storage } from '@yaks/sqlite'
1182
+ import { idDoc } from '@yaks/id/vocab'
1183
+ import { spineDoc } from '@yaks/kernel/vocab'
1184
+ import { docDoc } from '@yaks/doc'
1185
+ import { loadVocab } from '@yaks/vocab'
1186
+ import { equal } from '@yaks/testing'
1187
+
1188
+ let sql = open(':memory:')
1189
+ try {
1190
+ let vocab = loadVocab([spineDoc, idDoc, docDoc, {
1191
+ $defs: {
1192
+ entry: { component: true, type: 'object', properties: {} },
1193
+ },
1194
+ }])
1195
+ let store = storage(sql, vocab, { number: { doc: 'D', entry: 'E' } })
1196
+ let ids = (...eids: string[]) =>
1197
+ store.get(eids).map(({ entity: e }) => e.num && `${e.prefix}-${e.num}`)
1198
+ store.tx((tx) =>
1199
+ tx.patch([
1200
+ { entity: { eid: 'a', prefix: 'D', num: 40 }, doc: { title: 'Stated' } },
1201
+ { entity: { eid: 'b' }, entry: {} },
1202
+ { entity: { eid: 'c' }, doc: { title: 'Allocated' } },
1203
+ ])
1204
+ )
1205
+ equal(ids('a', 'b', 'c'), ['D-40', 'E-1', 'D-41'])
1206
+ store.tx((tx) =>
1207
+ tx.patch([{ entity: { eid: 'a', num: null } }, {
1208
+ entity: { eid: 'c', num: 7 },
1209
+ }])
1210
+ )
1211
+ equal(ids('a', 'c'), [undefined, 'D-7'])
1212
+ } finally {
1213
+ sql.close()
1214
+ }
1215
+ ```
1216
+
1217
+ ## Owed work
1218
+
1219
+ On a file, work whose cost grows with rows is written down rather than done
1220
+ while the schema pass holds the write lock (`@yaks/sqlite/owe`):
1221
+
1222
+ - `build(driver, stmts)` runs statements as `erect` does but owes each new index
1223
+ over a table of `BIG` (10,000) rows or more: one window, the index's build.
1224
+ - `filler(driver)` is the @yaks/fts `Filler` that fills a text index over more
1225
+ than `FILL` (500) rows that many a window.
1226
+ - `reshape(driver, comp, refitting, after)` takes on a refit (./ddl.ts) of a
1227
+ table of `BIG` rows or more: the table is built beside it as
1228
+ `_yaks_refit_<comp>`, `COPY` (20,000) rows a window, with triggers carrying
1229
+ each write behind the cursor across; once every row is there one window swaps
1230
+ the names and raises `after` (the indexes and triggers the composed schema
1231
+ puts on the table) on the new one, owing each big index. The old rows wait as
1232
+ `_yaks_old_<comp>` and are deleted `CLEAR` (10,000) a window.
1233
+ `install(beside)` on the store passes the rest of the composed schema for
1234
+ `after`, and a pass that no longer needs a rebuild gives it up (`forgo`).
1235
+ `_yaks_` names no component table.
1236
+
1237
+ `BIG`, `FILL`, `COPY`, `CLEAR`, `SLACK` and `RECLAIM` are one value, `SIZES`,
1238
+ which `build`, `filler`, `reshape`, `work` and the store's `sizes` option take
1239
+ in their place, so a test shrinks them to a few rows instead of building
1240
+ thousands.
1241
+
1242
+ Owed work sits in `server_meta` as `owed:<kind>:<name>`, its statements as data,
1243
+ so any process can finish it. `work(driver, now?, daily?, sizes?, chores?)` does
1244
+ one window of the first that is due (indexes, then fills, then refits, then
1245
+ clearing); a window that throws is kept with its error and tried again an hour
1246
+ later.
1247
+
1248
+ With none due, a window does the first **chore** (`Chore`, `{name, run}`) in
1249
+ `chores` that finds work: work the rows owe rather than the schema, found in
1250
+ them each time, such as the pieces of a long text's substring index (@yaks/fts
1251
+ `pieces`). `run` takes one window in one unit and answers whether it found any.
1252
+ One that throws waits an hour, kept in `server_meta` as `chore:<name>`.
1253
+
1254
+ With no chore to do, a window analyzes the first table the receipt owes
1255
+ (`analyze`); one that throws waits an hour, kept in `server_meta` as `analyze`.
1256
+
1257
+ With nothing owed or to analyze, `work` **reclaims**: on a file in incremental
1258
+ mode whose free pages pass `SLACK` (16,384, 64 MiB of 4 KiB pages), one window
1259
+ gives back up to `RECLAIM` (1,000) of the rest with
1260
+ `pragma incremental_vacuum(n)`, and the next checkpoint shortens the file. So a
1261
+ bulk delete, such as the daily expiration's, gives its space back within
1262
+ minutes, without a `VACUUM`. A window that throws waits an hour, kept in
1263
+ `server_meta` as `reclaim`.
1264
+
1265
+ With nothing owed or to reclaim, `work` does the first **upkeep** (`Daily`,
1266
+ `{name, run}`) in `daily` that is due: each runs in one unit once a day, and one
1267
+ that throws is tried again an hour later; `server_meta` keeps when each is next
1268
+ due as `daily:<name>`. `statistics` is one: it owes the analyses the tables
1269
+ lack, and is due again as soon as an owed index or a rebuilt table is in place.
1270
+ Opening a file whose print is recorded does neither.
1271
+
1272
+ `tend(driver, {signal, daily?, chores?})` works windows and the statistics, with
1273
+ the host's `daily` and `chores` beside them, until the signal aborts; on the box
1274
+ the process serving the effects role runs it under the `@yaks/sqlite/schema`
1275
+ lease, with a daily @yaks/fts `heal` that refills a drifted text index in
1276
+ windows, and @yaks/fts `pieces` as a chore. A database in memory owes nothing.
1277
+
1278
+ ## Preannounced migrations
1279
+
1280
+ A **migration control** (`MigrationControl`) coordinates an application
1281
+ migration through one `_yaks_migration` table. A **generation** is the integer
1282
+ incremented with each committed announcement. A **migration watch**
1283
+ (`MigrationWatch`) polls a migration control and calls its callback once when
1284
+ the generation changes, pending or failed work appears, or polling fails.
1285
+
1286
+ A writer adds the control table with the rest of its composed schema
1287
+ (`migrationSchema()`, `follow()`). Applications bind `migrations(driver)` and
1288
+ call `ready()` before opening their graph; binding never creates a table.
1289
+ `run(name, change)` commits an announcement, waits without holding a write
1290
+ transaction, then commits a synchronous migration and its completion record
1291
+ together. `announce`, `apply`, and `fail` expose the stages separately.
1292
+
1293
+ This example uses a zero grace period and an explicit watch check because it
1294
+ controls both sides, so it announces and applies where `run()` would also wait
1295
+ out the grace. Cooperating applications use the same maximum polling interval:
1296
+ `run()` defaults to one second plus a 100 ms margin, and `watchMigrations()`
1297
+ defaults to one second. `watchMigrations(control, changed, intervalMs, clock)`
1298
+ polls on the @yaks/fp `Clock` it is given, the runtime's by default.
1299
+
1300
+ ```ts
1301
+ import { open } from '@yaks/sqlite/db'
1302
+ import { add, columns, migrations, migrationSchema } from '@yaks/sqlite'
1303
+ import { equal, throws } from '@yaks/testing'
1304
+
1305
+ let app = open(':memory:')
1306
+ add(app, migrationSchema())
1307
+ let control = migrations(app)
1308
+ try {
1309
+ equal(control.ready(), 0)
1310
+ let claim = control.announce('add-note', 0)
1311
+ await throws(() => control.ready(), 'pending')
1312
+ control.apply(claim, (db) =>
1313
+ db.query({
1314
+ t: 'create table',
1315
+ name: 'note',
1316
+ cols: [{ name: 'title', type: 'text' }],
1317
+ }))
1318
+ equal(control.ready(), claim.generation)
1319
+ equal(columns(app, 'note'), ['title'])
1320
+ } finally {
1321
+ app.close()
1322
+ }
1323
+ ```
1324
+
1325
+ A watch tells the application that a migration has been announced or finished:
1326
+
1327
+ ```ts
1328
+ import { open } from '@yaks/sqlite/db'
1329
+ import { add, migrations, migrationSchema, watchMigrations } from '@yaks/sqlite'
1330
+ import { equal } from '@yaks/testing'
1331
+
1332
+ let app = open(':memory:')
1333
+ add(app, migrationSchema())
1334
+ let control = migrations(app)
1335
+ let notices: Error[] = []
1336
+ let watch = watchMigrations(control, (reason) => notices.push(reason))
1337
+ try {
1338
+ let claim = control.announce('add-note', 0)
1339
+ watch.check()
1340
+ equal(notices.length, 1)
1341
+ control.apply(claim, () => {})
1342
+ watch.check()
1343
+ equal(notices.length, 1)
1344
+ } finally {
1345
+ watch.stop()
1346
+ app.close()
1347
+ }
1348
+ ```
1349
+
1350
+ A callback that throws is recorded as failed, and the control refuses to be
1351
+ ready until someone has inspected the work and acknowledged it:
1352
+
1353
+ ```ts
1354
+ import { open } from '@yaks/sqlite/db'
1355
+ import { add, migrations, migrationSchema } from '@yaks/sqlite'
1356
+ import { equal, throws } from '@yaks/testing'
1357
+
1358
+ let app = open(':memory:')
1359
+ add(app, migrationSchema())
1360
+ let control = migrations(app)
1361
+ try {
1362
+ let failed = control.announce('abort', 0)
1363
+ await throws(() =>
1364
+ control.apply(failed, () => {
1365
+ throw new Error('abort')
1366
+ }), 'abort')
1367
+ equal(control.read()?.state, 'failed')
1368
+ // After inspecting and repairing failed or abandoned work:
1369
+ control.acknowledge(failed.generation)
1370
+ equal(control.ready(), failed.generation)
1371
+ } finally {
1372
+ app.close()
1373
+ }
1374
+ ```
1375
+
1376
+ The single row retains a generation, migration name, pending/applied/failed
1377
+ state, announcement/deadline timestamps, and completion/error information. It is
1378
+ not a migration history or a replacement for application migration markers.
1379
+ Concurrent announcements serialize through `BEGIN IMMEDIATE`; a pending or
1380
+ failed migration cannot be silently replaced. A failed callback rolls back its
1381
+ DDL/data changes, then records failure separately. A crash may leave `pending`;
1382
+ it requires operator investigation. `acknowledge(generation)` explicitly
1383
+ releases a failed or abandoned announcement **after** repair/inspection; it does
1384
+ not undo changes or determine whether replay is safe. All migration callbacks
1385
+ must be synchronous and must not start external side effects or manage their own
1386
+ transactions.
1387
+
1388
+ This is best-effort cooperation, not a corruption-prevention guarantee. A
1389
+ suspended process, delayed timer, or long-running callback can outlast the grace
1390
+ period. There are no peer acknowledgments. SQLite serializes write transactions,
1391
+ but that does not establish application-level schema compatibility. Stop peers
1392
+ explicitly for migrations that require guaranteed quiescence. A crash between
1393
+ rollback and recording failure can also leave a pending announcement.
1394
+
1395
+ Deploy this protocol to all participating writers before depending on it.
1396
+ Unaware clients, raw SQL, and migrations outside this API do not participate.
1397
+ The control table must be initialized during that rollout. On a fresh open,
1398
+ `ready()` cannot determine whether older application code understands a
1399
+ migration that already completed; version compatibility still belongs to the
1400
+ application. Data-only transformations are announced just like DDL when
1401
+ performed via this API.
1402
+
1403
+ ## History
1404
+
1405
+ A store opened with `history` (`storage(driver, vocab, { history })`) keeps
1406
+ every version of every component row. Its live tables are exactly the ones a
1407
+ store without history has. Beside each one, `<comp>$versions` holds its
1408
+ versions, each the span of transactions it was true for, `[$from, $to)`: the
1409
+ open one (`$to = 0`) is a copy of the live row, and a write closes it and opens
1410
+ the next. The table beside keeps the live table's column types and its
1411
+ vocabulary indexes, none of them unique. Current reads, their plans and every
1412
+ trigger on a live table are unchanged. A component declared `journal: false`
1413
+ keeps no versions on main, and the tombstones always do. A store that begins to
1414
+ keep history takes its live rows as their first versions, open from no
1415
+ transaction: in its install, or, opened `paced`, a page of entities at a time
1416
+ through `maintain()`, for a host whose writes are bounded by the minute (a
1417
+ Durable Object). History is kept from the beginning on, so a row a write changed
1418
+ before its page was taken keeps only what that write made. Until the last page
1419
+ the store makes no branch (`Unseeded`; `seeding(driver)` says whether pages are
1420
+ owed).
1421
+
1422
+ The store does not mint transaction ids. `History` is two statements its history
1423
+ plugin hands it (@yaks/journal's `history(options)`): `clock` takes the id of
1424
+ the transaction a unit's versions name, run by the unit's first versioned write,
1425
+ and `tip` reads the newest. So a unit writing only exempt components takes none.
1426
+
1427
+ A **mode** reads the past or a branch, through a driver of its own:
1428
+ `moded(driver, vocab, { history }, mode)` with `{ at }`, main as of a
1429
+ transaction, which refuses every write; or a branch from
1430
+ `branch(driver, history)`, main as of its fork under the branch's own rows,
1431
+ whose writes go to `<comp>$versions` rows of that branch and never reach main.
1432
+ Each statement the mode's driver runs is given, for each component table it
1433
+ names, a common table expression of that name holding the mode's rows, which
1434
+ stands in front of the table everywhere in the statement. Nothing is made in the
1435
+ database, so a mode needs no temporary object (a Durable Object refuses them)
1436
+ and reads over any connection, the one its main store writes through included.
1437
+ Binding the same driver to another mode answers the same store, reading the new
1438
+ one, and a mode's store installs nothing: its schema is its main store's. Each
1439
+ relation is one select over one table, which SQLite folds into any read that
1440
+ names it; a compound one it would materialize whole for a left join. A branch's
1441
+ exempt components are the exception, a compound of its rows and the live ones.
1442
+ The historical archetype index (`$archetype$versions`) keeps membership spans
1443
+ from the version writes. A mode reads its table sets there, with live exempt
1444
+ components from the owner's current archetype and branch membership overlaid. It
1445
+ asks no component's relation which entities it holds. Property edits keep the
1446
+ same membership span. Installation repairs a missing historical index from the
1447
+ versions already held. Text search reads the live text. An entity's spine is not
1448
+ versioned: one minted after the transaction a mode reads reads as an empty
1449
+ identity.
1450
+
1451
+ A store with history has `branches` (./branches.ts): `make()` writes a row of
1452
+ the branch table and copies nothing, `list()` answers active branches,
1453
+ `list(true)` answers trash, `drop(id)` trashes the branch while keeping all its
1454
+ versions, `restore(id)` returns it from trash, and `changes(id)` answers what
1455
+ the branch changed since its fork: each entity's component it holds a row of, as
1456
+ main held it at the fork, as the branch holds it, and as main holds it now, read
1457
+ as any read is, so @yaks/journal can merge them. A component declared
1458
+ `journal: false` is left out, since main keeps no value of it at the fork. An
1459
+ entity a branch makes has a spine on main, pointed at the archetype of nothing,
1460
+ since on main it holds nothing; `make()` makes sure main keeps that archetype.
1461
+ Reading and writing on a branch is its host's: @yaks/cli composes a host on each
1462
+ branch a call names, so every plugin binds to the branch's connection
1463
+ (@yaks/graph `GraphBranches`). [history_test.ts](./history_test.ts) shows each.
1464
+
1465
+ ## Limits
1466
+
1467
+ Graph admission, preconditions, plugins, and deletion decisions belong to
1468
+ [@yaks/graph](../graph/README.md). Query parsing and SQL compilation belong to
1469
+ [@yaks/query](../query/README.md) and [@yaks/sql](../sql/README.md). Full-text
1470
+ indexes belong to [@yaks/fts](../fts/README.md); pass its extension in
1471
+ `base.extend`. The root adapter accepts synchronous drivers; only `./db` uses
1472
+ Deno environment and FFI APIs. Whole-entity reads require SQLite JSON support.
1473
+
1474
+ ## License
1475
+
1476
+ Apache-2.0
1477
+
1478
+ ## Statement capability
1479
+
1480
+ `storage(driver, vocab).statements` is the adapter's stable
1481
+ [statement capability](../sql/README.md#statement-capability).
1482
+ `statements(driver)` binds the same capability for an index without a graph
1483
+ store. Both participate in the driver's current transaction; `atomic` uses the
1484
+ same nested units as graph writes. Transaction-control statements are refused at
1485
+ this door. The adapter loads its named vector facility, never a path supplied by
1486
+ a plugin.
1487
+
1488
+ `await sql.atomic(body)` retries a busy file before entering `body`, with its
1489
+ busy timeout disabled for that entry. The wait uses timers; the body and an
1490
+ uncertain commit are never retried. Complete external work before entering it.
1491
+
1492
+ ```ts
1493
+ import { open } from '@yaks/sqlite/db'
1494
+ import { statements } from '@yaks/sqlite'
1495
+ import { equal, throws } from '@yaks/testing'
1496
+
1497
+ let driver = open(':memory:')
1498
+ try {
1499
+ let sql = statements(driver)
1500
+ equal(statements(driver), sql)
1501
+ equal(sql.ownership, 'exclusive')
1502
+ await throws(() => sql.query({ t: 'begin' }), 'storage owns transactions')
1503
+ } finally {
1504
+ driver.close()
1505
+ }
1506
+ ```
1507
+
1508
+ The repository's unpublished [testing.ts](./testing.ts) offers
1509
+ `preparedStore(vocab, options?)`: a disposable store made from a **schema
1510
+ snapshot**, the empty database after that vocabulary's schema was installed.
1511
+ `snapshot(vocab, options?, extra?)` keeps that snapshot once per fitting
1512
+ revision, rendered vocabulary schema, and auxiliary statements; `extra` lets a
1513
+ host include its own tables, indexes, triggers, and fixed schema metadata.
1514
+ `textual()` gives an engine stand-in the same preparation. Each store restores a
1515
+ private SQLite buffer, mints its own epoch, and enforces foreign keys; writes
1516
+ and rollbacks stay in that store, and closing it releases its native buffer.
1517
+ Kernel fixtures use snapshots of the app, directory, or git vocabulary,
1518
+ including their search, embedding, journal, and write-log schema. Production
1519
+ opens and installs keep their existing behavior.
1520
+
1521
+ The store also offers `checks`, bound diagnostics used by `@yaks/sqlite/tools`,
1522
+ and `migrations`, its cooperative migration control. Hosts lend only the
1523
+ migration monitor to portable plugins; operators use the adapter's migration
1524
+ control with a dedicated connection.
1525
+
1526
+ ## Cache budgets
1527
+
1528
+ `@yaks/sqlite/service` maintains rebuildable database caches without unlinking
1529
+ an inode another process may still use. Configure its `caches` option with
1530
+ absolute database paths, byte budgets, and each rebuildable table's file-URL
1531
+ column:
1532
+
1533
+ ```json
1534
+ {
1535
+ "use": "@yaks/sqlite",
1536
+ "with": {
1537
+ "caches": {
1538
+ "/home/me/.cache/deno/v8_code_cache_v2": {
1539
+ "most": 2000000000,
1540
+ "tables": { "codecache": "specifier" }
1541
+ },
1542
+ "/home/me/.cache/deno/dep_analysis_cache_v2": {
1543
+ "most": 1000000000,
1544
+ "tables": { "moduleinfocache": "specifier" }
1545
+ }
1546
+ }
1547
+ }
1548
+ }
1549
+ ```
1550
+
1551
+ Every hour (or `every` milliseconds), a cache over budget loses entries whose
1552
+ local source files are gone, then runs `VACUUM` and a truncating WAL checkpoint.
1553
+ If it remains over budget, its declared rebuildable tables are cleared and
1554
+ compacted. Other tables, including version metadata, remain intact. A missing
1555
+ cache stays absent. Processes with open connections continue using the same
1556
+ file. Failures reach the host's telemetry and are retried on the next pass.
1557
+
1558
+ A cache is opened through the SQLite built into Deno (`node:sqlite`), never the
1559
+ package's own library. Deno keeps its caches open in the trimming process, and
1560
+ POSIX locks belong to the process: a second SQLite closing the same file would
1561
+ drop the locks Deno's copy holds and could corrupt the cache.
1562
+
1563
+ `@yaks/sqlite/cache` exposes `trim(path, cache)` for a single pass, `held(path)`
1564
+ for its database and WAL bytes, and `prune(driver, tables, gone?)` for deleting
1565
+ missing sources through an existing connection.
1566
+
1567
+ ### Trash
1568
+
1569
+ Every storage transaction retains before-images when it removes entities,
1570
+ components or property values, including direct `tx.remove()` calls. The
1571
+ `_yaks_trash` table keeps these independently of the optional journal. Its
1572
+ reference to the identity prevents orphan collection from erasing recoverable
1573
+ rows. The snapshots use the graph's JSON wire format, including binary values.
1574
+
1575
+ `store.trash(eids, {after, id, limit})` reads complete retained transactions as
1576
+ `{id, at, bundles}`; `restoreTrash(graph, entry, options)` from
1577
+ `@yaks/graph/trash` restores them through ordinary graph writes.
1578
+ `store.purgeTrash(id)` removes one archive only after the person explicitly
1579
+ chooses to purge it through the confirmation page. Neither restoring a row nor
1580
+ its age purges its archive.
1581
+
1582
+ An exact `id` reads a retained transaction without an age limit. Discovery
1583
+ continues from the previous page's last id through `after`. A composed host can
1584
+ page several stores against the same `before: {at, id}` boundary. Passing entity
1585
+ eids to `store.purgeTrash(eids)` purges only their snapshots, preserving
1586
+ unrelated members of a retained transaction.
1587
+
1588
+ `purgeEntities(graph, eids)` from `@yaks/graph/trash` is the explicit permanent
1589
+ purge of saved entity data. The caller first removes the live data through its
1590
+ confirmed purge flow. The helper erases only those entities' trash snapshots,
1591
+ every version (including branches and retired properties), and their journal
1592
+ values. Other subjects in the same trash group or recorded transaction remain.
1593
+ Plugin `purged` callbacks then release pooled content only when no live row,
1594
+ version, archive or journal value still references it. This path is reserved for
1595
+ a person's confirmed purge or intentional security redaction; housekeeping never
1596
+ calls it. `store.purgeTrash(id)` alone removes just that retained group, leaving
1597
+ ordinary edit history intact.