@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/write.ts ADDED
@@ -0,0 +1,1356 @@
1
+ // Writes: bundles patched into the store, and entities removed from it. This
2
+ // is the PATCH half of the adapter — the mirror image of the reads in
3
+ // ./read.ts — and it honors the rules a graph patch honors everywhere:
4
+ //
5
+ // omitted properties are untouched a patch names only what changes
6
+ // a property set to null is cleared component reads omit the property
7
+ // a component set to null is dropped the row goes, the entity stays
8
+ // a tombstoned entity takes no patch until `revive` clears its tombstone;
9
+ // it keeps its eid and number
10
+ //
11
+ // Every write here is a statement (an @yaks/sql `Write`), built before it is
12
+ // sent, and every statement is self-sufficient: an owner id is a subquery
13
+ // (`select id from entity where eid = ?`) rather than a value looked up first,
14
+ // and an insert whose owner does not exist writes nothing instead of inventing
15
+ // a row. Nothing is read between two writes.
16
+ //
17
+ // That is what lets one write path serve every SQLite-shaped adapter. An
18
+ // embedded engine could afford to query mid-write — look up an id, insert a
19
+ // row, query again — but D1 runs over the network and gives no interactive
20
+ // transaction, so a write that queried mid-flight could not be atomic there:
21
+ // whatever it learned would be learned outside the batch that commits.
22
+ // Statements that query nothing can be gathered into one list and sent as a
23
+ // single all-or-nothing unit, which is exactly what @yaks/d1 does with the ones
24
+ // built here.
25
+ //
26
+ // The one read that remains is about identity, not about ids: which of the
27
+ // named eids are already tombstoned, queried once for the whole batch. What
28
+ // numbers the new ones were given is not queried at all — every mint statement
29
+ // returns its own row, so an insert that minted returns one and an insert that
30
+ // found the eid already there returns none. That is why @yaks/d1 can mint
31
+ // without knowing a number in advance: its batch comes back statement by
32
+ // statement, and the numbers are in it.
33
+ //
34
+ // What is NOT here is which entities a delete takes with it. A reference's
35
+ // declared death behavior (`cascade`, `detach`, `release`, `keep`) is a rule
36
+ // about meaning, declared in the vocabulary, and @yaks/graph reads it — through
37
+ // the same transaction — to decide which entities go. This file removes exactly
38
+ // the entities it is given. One decision, in one place, shared by every storage
39
+ // adapter.
40
+ //
41
+ // Identity is storage's: `patch` mints a spine for every eid the batch touches
42
+ // or points at (so a reference may name a target created in the same batch, in
43
+ // any order), numbers each new one, and reports the entities it minted.
44
+
45
+ import { field, revision } from '@yaks/sql'
46
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
47
+ import type { Bundle, Comp, Entity } from 'jsr:@yaks/graph@0.2.36'
48
+ import { comps, TOMBSTONE } from '@yaks/graph/bundle'
49
+ import { stood } from './raise.js'
50
+ import { Refused } from '@yaks/graph/errors'
51
+ import {
52
+ clash,
53
+ type Pair,
54
+ renumbering,
55
+ type Series,
56
+ seriesOf,
57
+ stating,
58
+ } from '@yaks/graph/storage'
59
+ import {
60
+ among,
61
+ and,
62
+ array,
63
+ as,
64
+ call,
65
+ cell,
66
+ col,
67
+ cross,
68
+ type Delete,
69
+ type Driver,
70
+ each,
71
+ effect,
72
+ eq,
73
+ exists,
74
+ type Expr,
75
+ fn,
76
+ from,
77
+ gt,
78
+ type Insert,
79
+ isNull,
80
+ jsonable,
81
+ le,
82
+ lit,
83
+ not,
84
+ oneOf,
85
+ type Param,
86
+ parts,
87
+ type Row,
88
+ select,
89
+ sub,
90
+ table,
91
+ type Update,
92
+ val,
93
+ VARIABLES,
94
+ type Write,
95
+ } from '@yaks/sql'
96
+ import { tables } from './layout.js'
97
+ import { TRASH } from './trash.js'
98
+ import { required } from './physical.js'
99
+ import { heldBy } from './archetype.js'
100
+ import { classed, spined } from './memo.js'
101
+ import { isJsonb, jsonb, jsonIn } from './jsonb.js'
102
+ import { described, get, grave, type Unsettled } from './read.js'
103
+ import { kept } from './history.js'
104
+
105
+ // The owner's integer id, as a subquery. Every write keys to it, so an entity
106
+ // minted earlier in the same unit of work resolves without a second question.
107
+ let owner = (eid: string): Expr =>
108
+ sub(select({
109
+ cols: [col('id')],
110
+ from: table('entity'),
111
+ where: eq(col('eid'), val(eid)),
112
+ }))
113
+
114
+ // The value a column stores, coerced to what SQLite holds: a boolean becomes
115
+ // 0/1 (a bool column has integer affinity), everything else passes through. A
116
+ // reference is resolved to its target's integer id by the statement itself.
117
+ let scalar = (value: unknown): Param =>
118
+ typeof value == 'boolean' ? Number(value) : value as Param
119
+
120
+ // Whether a property is a reference — asked of the vocabulary, which knows a
121
+ // property's category.
122
+ let isRef = (v: Vocab, comp: string, prop: string): boolean =>
123
+ v.prop(comp, prop)?.category == 'ref'
124
+
125
+ // One property's value as what writes it: a reference names its target's eid
126
+ // and the statement looks up the id, a JSON value goes in through `jsonb()`
127
+ // (./jsonb.ts), and a scalar is bound as it is.
128
+ type Resolve = (eid: string) => Expr
129
+ let slot = (
130
+ v: Vocab,
131
+ comp: string,
132
+ prop: string,
133
+ raw: unknown,
134
+ resolve: Resolve = owner,
135
+ ): Expr =>
136
+ raw != null && isRef(v, comp, prop)
137
+ ? resolve(String(raw))
138
+ : isJsonb(v, comp, prop)
139
+ ? jsonb(val(jsonIn(raw)))
140
+ : val(scalar(raw))
141
+
142
+ /** What the store already knows about an eid: its number and the prefix of
143
+ * its series, and whether that identity is tombstoned. An eid with no entry
144
+ * has no entity yet. */
145
+ export type Spine = {
146
+ id: number
147
+ num: number | null
148
+ prefix?: string | null
149
+ dead: boolean
150
+ }
151
+
152
+ /** What the store knows about these eids — one statement and one bound
153
+ * parameter, whatever the batch's size (a Durable Object binds at most 100).
154
+ * An eid absent from the map has no entity; one present with `dead` is
155
+ * tombstoned, and a deleted identity is still an identity: it resolves by eid,
156
+ * and `revive` brings it back. */
157
+ export let spines = (
158
+ driver: Driver,
159
+ eids: string[],
160
+ ): Map<string, Spine> =>
161
+ eids.length
162
+ ? spined(driver).get(eids, (eids) => stored(driver, eids))
163
+ : new Map()
164
+
165
+ let stored = (driver: Driver, eids: string[]): Map<string, Spine> =>
166
+ new Map(
167
+ driver.query(select({
168
+ cols: [
169
+ col('id', 'e'),
170
+ col('eid', 'e'),
171
+ col('num', 'e'),
172
+ col('prefix', 'e'),
173
+ as(grave(col('id', 'e')), 'dead'),
174
+ ],
175
+ ...(eids.length == 1
176
+ ? {
177
+ from: table('entity', 'e'),
178
+ where: eq(col('eid', 'e'), val(eids[0])),
179
+ }
180
+ : {
181
+ from: from(each([...new Set(eids)]), '@eids'),
182
+ joins: [cross(table('entity', 'e', 'sqlite_autoindex_entity_1'))],
183
+ where: eq(col('eid', 'e'), col('value', '@eids')),
184
+ }),
185
+ })).map((r) => [String(r.eid), {
186
+ id: Number(r.id),
187
+ num: r.num == null ? null : Number(r.num),
188
+ prefix: r.prefix == null ? null : String(r.prefix),
189
+ dead: r.dead != null,
190
+ }]),
191
+ )
192
+
193
+ /** The entities that are tombstoned, of those named. */
194
+ export let buried = (driver: Driver, eids: string[]): Set<string> =>
195
+ new Set(
196
+ [...spines(driver, eids)]
197
+ .filter(([, spine]) => spine.dead)
198
+ .map(([eid]) => eid),
199
+ )
200
+
201
+ // What a mint or a numbering reports: the identity it wrote.
202
+ let IDENTITY = [col('eid'), col('num'), col('prefix')]
203
+
204
+ /**
205
+ * The statement that mints an identity, and returns what it minted.
206
+ * `do nothing` on an eid that already has an identity, so minting twice is not
207
+ * an error; RETURNING then emits no row, which is also how the caller knows
208
+ * whether this one was new. Left without a number, the spine is minted with a
209
+ * NULL one. `number` is the one the entity takes, in the series of `prefix`:
210
+ * a store seeded from another store's export adopts the ids that export
211
+ * already carries, because an entity read as `T-37574` somewhere is `T-37574`
212
+ * everywhere. The series follows — `entity_series_insert` raises its high
213
+ * water mark — so the next number given is still past it.
214
+ */
215
+ export let mintSql = (
216
+ eid: string,
217
+ number?: number,
218
+ archetype?: number,
219
+ prefix: string | null = null,
220
+ ): Insert => ({
221
+ t: 'insert',
222
+ into: 'entity',
223
+ cols: ['eid', 'num', 'prefix', ...archetype == null ? [] : ['archetype']],
224
+ rows: [[
225
+ val(eid),
226
+ number == null ? lit(null) : val(number),
227
+ number == null || prefix == null ? lit(null) : val(prefix),
228
+ ...archetype == null ? [] : [val(archetype)],
229
+ ]],
230
+ upsert: [{ on: [col('eid')] }],
231
+ returning: IDENTITY,
232
+ })
233
+
234
+ /** The statement that mints identities from a row source:
235
+ * each row an eid, the archetype's integer id it is minted in or null, and
236
+ * the number and prefix it is given or nulls. It returns what it minted, as
237
+ * {@link mintSql} does, with the id: nothing for an eid that already had
238
+ * one. */
239
+ export let mintsSql = (source: RowSource): Insert => ({
240
+ t: 'insert',
241
+ into: 'entity',
242
+ cols: ['eid', 'num', 'prefix', 'archetype'],
243
+ ...rowSource(source, (at) => [at(0), at(2), at(3), at(1)]),
244
+ upsert: [{ on: [col('eid')] }],
245
+ returning: [...IDENTITY, col('id')],
246
+ })
247
+
248
+ /** The statement that numbers a spine a reference minted, once a bundle of its
249
+ * own arrives: the number given, in the series of `prefix`. It returns what
250
+ * {@link mintSql} does, and nothing where the spine already has a number. */
251
+ export let numberSql = (
252
+ eid: string,
253
+ number: number,
254
+ prefix: string | null = null,
255
+ ): Update => ({
256
+ t: 'update',
257
+ table: 'entity',
258
+ set: {
259
+ num: val(number),
260
+ prefix: prefix == null ? lit(null) : val(prefix),
261
+ },
262
+ where: and(eq(col('eid'), val(eid)), isNull(col('num'))),
263
+ returning: IDENTITY,
264
+ })
265
+
266
+ // The entities holding each of these numbers, any letter, a tombstone
267
+ // included: its number is still its address.
268
+ let holders = (
269
+ driver: Driver,
270
+ nums: number[],
271
+ ): Map<number, ({ eid: string } & Pair)[]> =>
272
+ nums.length
273
+ ? Map.groupBy(
274
+ driver.query(select({
275
+ cols: [col('num'), col('prefix'), col('eid')],
276
+ from: table('entity'),
277
+ where: oneOf(col('num'), nums),
278
+ })).map((r) => ({
279
+ eid: String(r.eid),
280
+ num: Number(r.num),
281
+ prefix: r.prefix == null ? null : String(r.prefix),
282
+ })),
283
+ (h) => h.num,
284
+ )
285
+ : new Map()
286
+
287
+ // An entity's pair set from the one its row holds (`from`) to another, or to
288
+ // none, and the store's memory of its spine with it. Only a column that
289
+ // changes is set, so a letter given to the number an entity keeps leaves that
290
+ // number's index entries and its count as they are. The counts follow a
291
+ // number set past them (`entity_series_update`).
292
+ let renumber = (
293
+ driver: Driver,
294
+ eid: string,
295
+ spine: Spine,
296
+ from: Pair | null,
297
+ pair: Pair | null,
298
+ ) => {
299
+ let num = pair?.num ?? null, prefix = pair?.prefix ?? null
300
+ let set = {
301
+ ...num != (from?.num ?? null)
302
+ ? { num: num == null ? lit(null) : val(num) }
303
+ : {},
304
+ ...prefix != (from?.prefix ?? null)
305
+ ? { prefix: prefix == null ? lit(null) : val(prefix) }
306
+ : {},
307
+ }
308
+ effect(driver, {
309
+ t: 'update',
310
+ table: 'entity',
311
+ set,
312
+ where: eq(col('eid'), val(eid)),
313
+ })
314
+ spined(driver).learn(eid, { ...spine, num, prefix })
315
+ }
316
+
317
+ /** The identity a {@link mintSql} statement reported — the rows it returned —
318
+ * or `undefined` when the eid already had one and nothing was minted. */
319
+ export let minted = (rows: Row[]): Entity | undefined =>
320
+ rows[0]
321
+ ? {
322
+ eid: String(rows[0].eid),
323
+ num: rows[0].num == null ? null : Number(rows[0].num),
324
+ ...rows[0].prefix == null ? {} : { prefix: String(rows[0].prefix) },
325
+ }
326
+ : undefined
327
+
328
+ // The last number a series gave: this write's, or the store's.
329
+ let lastIn = (
330
+ driver: Driver,
331
+ prefix: string,
332
+ given: Map<string, number>,
333
+ ): number =>
334
+ given.get(prefix) ?? Number(
335
+ driver.query(select({
336
+ cols: [col('high')],
337
+ from: table('entity_series'),
338
+ where: eq(col('prefix'), val(prefix)),
339
+ }))[0]?.high ?? 0,
340
+ )
341
+
342
+ /**
343
+ * Where an id another entity keeps as a name lives: the eid of the entity that
344
+ * would keep `T-12` as one (@yaks/alias `aliasEid`). A number given out
345
+ * before and kept as the name of what it named, once its entity was numbered
346
+ * again, is never given out again while that name stands.
347
+ */
348
+ export type Names = (prefix: string, num: number) => string
349
+
350
+ // Of a window of numbers in a series, those kept as another entity's name: a
351
+ // living spine at the eid `names` says keeps each (a released name's is a
352
+ // tombstone).
353
+ let asNames = (
354
+ driver: Driver,
355
+ prefix: string,
356
+ nums: number[],
357
+ names: Names,
358
+ ): number[] => {
359
+ let at = new Map(nums.map((k) => [names(prefix, k), k]))
360
+ return [...spines(driver, [...at.keys()])]
361
+ .filter(([, s]) => !s.dead)
362
+ .map(([eid]) => at.get(eid)!)
363
+ }
364
+
365
+ /**
366
+ * The next number in a series, past the last it gave, stepping over one an
367
+ * entity holds in the series, and one kept as another entity's name
368
+ * (`names`). `given`
369
+ * keeps what this write has given so far, by letter, so the next asked is
370
+ * past it. Read a window of numbers at a time: a store whose old rows hold
371
+ * most of the low ones steps over them in few reads.
372
+ */
373
+ let nextIn = (
374
+ driver: Driver,
375
+ prefix: string,
376
+ given: Map<string, number>,
377
+ names?: Names,
378
+ ): number => {
379
+ let n = lastIn(driver, prefix, given)
380
+ for (let width = 64;; n += width) {
381
+ let window = Array.from({ length: width }, (_, i) => n + 1 + i)
382
+ let held = new Set([
383
+ ...driver.query(select({
384
+ cols: [col('num')],
385
+ from: table('entity'),
386
+ where: and(
387
+ gt(col('num'), val(n)),
388
+ le(col('num'), val(n + width)),
389
+ eq(col('prefix'), val(prefix)),
390
+ ),
391
+ })).map((r) => Number(r.num)),
392
+ ...names ? asNames(driver, prefix, window, names) : [],
393
+ ])
394
+ for (let k = n + 1; k <= n + width; k++) {
395
+ if (!held.has(k)) {
396
+ given.set(prefix, k)
397
+ return k
398
+ }
399
+ }
400
+ }
401
+ }
402
+
403
+ // Whether the entity `e` has no row in `comp` yet.
404
+ let lacks = (comp: string): Expr =>
405
+ not(exists(select({
406
+ cols: [lit(1)],
407
+ from: table(comp),
408
+ where: eq(col('entity', comp), col('id', 'e')),
409
+ })))
410
+
411
+ /**
412
+ * The statement that patches one component onto one entity: insert the sent
413
+ * columns, or update just them on conflict, so an omitted property keeps what
414
+ * it held. A reference property binds its target's eid and resolves to that
415
+ * target's id in the statement. A component whose patch names no stored
416
+ * property is a tag — its row's existence is the whole fact.
417
+ *
418
+ * An INSERT…select is what makes the owner a subquery: no owner row, no
419
+ * inserted row.
420
+ *
421
+ * A tag insert is `or ignore` in both forms: existence is the whole fact it
422
+ * asserts, so a component whose table requires a column the tag cannot supply
423
+ * is a no-op rather than a failed batch. That is what keeps a server-written
424
+ * audit row — one the server writes with its own columns — impossible to create
425
+ * from a client request, without a client being able to fail the batch by
426
+ * naming it.
427
+ */
428
+ export let upsertSql = (
429
+ v: Vocab,
430
+ eid: string,
431
+ comp: string,
432
+ patch: Comp,
433
+ absent = false,
434
+ resolve?: Resolve,
435
+ ): Insert => {
436
+ let cols = Object.keys(patch).filter((c) =>
437
+ v.prop(comp, c)?.computed === false
438
+ )
439
+ let id = resolve?.(eid)
440
+ let source = id ? {} : { from: table('entity', 'e') }
441
+ let where = and(
442
+ ...id ? [] : [eq(col('eid', 'e'), val(eid))],
443
+ ...(absent
444
+ ? [
445
+ id
446
+ ? not(
447
+ exists(
448
+ select({
449
+ cols: [lit(1)],
450
+ from: table(comp),
451
+ where: eq(col('entity', comp), id),
452
+ }),
453
+ ),
454
+ )
455
+ : lacks(comp),
456
+ ]
457
+ : []),
458
+ )
459
+ if (!cols.length) {
460
+ return {
461
+ t: 'insert',
462
+ or: 'ignore',
463
+ into: comp,
464
+ cols: ['entity'],
465
+ q: select({ cols: [id ?? col('id', 'e')], ...source, where }),
466
+ }
467
+ }
468
+ // The value each column takes, as a select item beside the owner id: a
469
+ // reference is another subquery, a scalar is a bound parameter.
470
+ return {
471
+ t: 'insert',
472
+ into: comp,
473
+ cols: ['entity', ...cols.map(field)],
474
+ q: select({
475
+ cols: [
476
+ id ?? col('id', 'e'),
477
+ ...cols.map((c) => slot(v, comp, c, patch[c], resolve)),
478
+ ],
479
+ ...source,
480
+ where,
481
+ }),
482
+ upsert: absent ? undefined : [{
483
+ on: [col('entity')],
484
+ set: Object.fromEntries(
485
+ cols.map((c) => [field(c), col(field(c), 'excluded')]),
486
+ ),
487
+ }],
488
+ }
489
+ }
490
+
491
+ /**
492
+ * The statement that inserts whole rows of one component from a row source:
493
+ * each row its owner's id, then a value per property in
494
+ * `cols`, a reference's already its target's id. A row already there is
495
+ * updated, as {@link upsertSql} does.
496
+ */
497
+ export let rowsSql = (
498
+ v: Vocab,
499
+ comp: string,
500
+ cols: string[],
501
+ source: RowSource,
502
+ ): Insert => ({
503
+ t: 'insert',
504
+ into: comp,
505
+ cols: ['entity', ...cols.map(field)],
506
+ ...rowSource(source, (at) => [
507
+ at(0),
508
+ ...cols.map((c, i) => isJsonb(v, comp, c) ? jsonb(at(i + 1)) : at(i + 1)),
509
+ ]),
510
+ upsert: [{
511
+ on: [col('entity')],
512
+ set: Object.fromEntries(
513
+ cols.map((c) => [field(c), col(field(c), 'excluded')]),
514
+ ),
515
+ }],
516
+ })
517
+
518
+ type RowSource = string | Param[]
519
+
520
+ // Singleton groups fit in VALUES without serializing an array for SQLite to
521
+ // unfold. Keep one JSON bind for wider rows and batches. Embedded NULs and
522
+ // ill-formed strings also keep JSON's escaping on the way into the engine.
523
+ let sources = (rows: Param[][]): RowSource[] => {
524
+ let [one] = rows
525
+ return rows.length == 1 && one.length <= VARIABLES &&
526
+ one.every((p) =>
527
+ typeof p != 'string' || !p.includes('\0') && p.isWellFormed()
528
+ )
529
+ ? [one]
530
+ : parts(rows)
531
+ }
532
+
533
+ let rowSource = (
534
+ source: RowSource,
535
+ columns: (at: (index: number) => Expr) => Expr[],
536
+ ): Pick<Insert, 'rows' | 'q'> =>
537
+ typeof source == 'string'
538
+ ? {
539
+ q: select({
540
+ cols: columns(cell),
541
+ from: call('json_each', [val(source)]),
542
+ where: and(),
543
+ }),
544
+ }
545
+ : { rows: [columns((i) => val(source[i]))] }
546
+
547
+ /** The statement that drops one component from one entity — the row goes, the
548
+ * entity stays. */
549
+ export let dropSql = (eid: string, comp: string): Delete => ({
550
+ t: 'delete',
551
+ from: comp,
552
+ where: eq(col('entity'), owner(eid)),
553
+ })
554
+
555
+ // The entities one pointer statement names, as one bound list.
556
+ let POINTED = 2048
557
+
558
+ /** The identity metadata write: the pointer and its entity by the integer ids
559
+ * `ids` holds, else by their portable eids. */
560
+ export let archetypeSql = (
561
+ b: Bundle,
562
+ ids: ReadonlyMap<string, number> = new Map(),
563
+ ): Update[] => {
564
+ let { eid, archetype } = b.entity
565
+ if (archetype === undefined) return []
566
+ let id = ids.get(eid), to = ids.get(archetype)
567
+ return [{
568
+ t: 'update',
569
+ table: 'entity',
570
+ set: { archetype: to == null ? owner(archetype) : val(to) },
571
+ where: id == null ? eq(col('eid'), val(eid)) : eq(col('id'), val(id)),
572
+ }]
573
+ }
574
+
575
+ /**
576
+ * The statements that patch one bundle in: a plan per component it names, a drop
577
+ * for each `null` one. Identity is minted separately (see {@link mintSql}),
578
+ * because a batch mints every eid it touches or points at before it writes
579
+ * anything.
580
+ */
581
+ export let patchSql = (v: Vocab, b: Bundle): Write[] => [
582
+ ...archetypeSql(b),
583
+ ...comps(b).flatMap(([name, comp]) => {
584
+ let { first, fallback } = patchOne(v, b.entity.eid, name, comp)
585
+ return fallback ? [first, fallback()] : [first]
586
+ }),
587
+ ]
588
+
589
+ // One component's plan: a drop, a bare insert, or update then absent insert.
590
+ // An interactive driver uses the UPDATE's affected-row count to omit its
591
+ // fallback. A batched driver sends both; insert's where is the same no-op.
592
+ let patchOne = (
593
+ v: Vocab,
594
+ eid: string,
595
+ name: string,
596
+ comp: Comp | null,
597
+ resolve: Resolve = owner,
598
+ ): { first: Insert | Update | Delete; fallback?: () => Insert } => {
599
+ if (comp == null) {
600
+ return {
601
+ first: { ...dropSql(eid, name), where: eq(col('entity'), resolve(eid)) },
602
+ }
603
+ }
604
+ // Insert checks NOT NULL before ON CONFLICT. Update existing rows first,
605
+ // then insert only absent ones: partial patches need no invented defaults
606
+ // or read/merge, and the same ordered statements work in a D1 batch.
607
+ let cols = Object.keys(comp).filter((c) =>
608
+ v.prop(name, c)?.computed === false
609
+ )
610
+ let fallback = () =>
611
+ upsertSql(v, eid, name, comp, true, resolve == owner ? undefined : resolve)
612
+ return cols.length
613
+ ? {
614
+ first: {
615
+ t: 'update',
616
+ table: name,
617
+ set: Object.fromEntries(
618
+ cols.map((c) => [field(c), slot(v, name, c, comp[c], resolve)]),
619
+ ),
620
+ where: eq(col('entity'), resolve(eid)),
621
+ },
622
+ fallback,
623
+ }
624
+ : { first: fallback() }
625
+ }
626
+
627
+ /** The statement that clears an entity's tombstone, so the write that follows
628
+ * lands on the identity it kept. */
629
+ export let unburySql = (eid: string): Delete => dropSql(eid, TOMBSTONE)
630
+
631
+ /** Erase empty, unreferenced identity spines, the whole set in three
632
+ * statements whatever its size. The guard runs once per identity, in the
633
+ * write's transaction, including on a deferred adapter: a reference added
634
+ * since its read prevents erasure. The tombstones go first, unguarded, since
635
+ * an identity row is erased only once nothing keys to it; the final NOT NULL
636
+ * assertion then rolls the batch back, tombstones included, when the guard
637
+ * kept an identity, instead of reporting a repair that did not happen. */
638
+ export let pruneSql = (
639
+ vocab: Vocab,
640
+ eids: string[],
641
+ held: readonly string[] = tables(vocab),
642
+ ): Write[] => {
643
+ if (!eids.length) return []
644
+ let listed = array(eids)
645
+ let named = among(col('eid'), listed)
646
+ let holds = (name: string, prop: string): Expr =>
647
+ exists(select({
648
+ cols: [lit(1)],
649
+ from: table(name, '__r'),
650
+ where: eq(col(prop, '__r'), col('id', 'entity')),
651
+ }))
652
+ // Housekeeping leaves identities held by recoverable before-images standing.
653
+ let eligible = and(named, not(holds(TRASH, 'entity')))
654
+ let stands = new Set(held)
655
+ let empty = and(
656
+ exists(select({
657
+ cols: [lit(1)],
658
+ from: table('archetype', '__shape'),
659
+ where: and(
660
+ eq(col('entity', '__shape'), col('archetype', 'entity')),
661
+ oneOf(fn('json', col('tables', '__shape')), [
662
+ '[]',
663
+ JSON.stringify([TOMBSTONE]),
664
+ ]),
665
+ ),
666
+ })),
667
+ ...vocab.refProps()
668
+ .filter(([c, p]) => stands.has(c) && !vocab.prop(c, p)?.computed)
669
+ .map(([c, p]) => not(holds(c, field(p)))),
670
+ not(holds('entity', 'archetype')),
671
+ )
672
+ return [
673
+ {
674
+ t: 'delete',
675
+ from: TOMBSTONE,
676
+ where: among(
677
+ col('entity'),
678
+ select({ cols: [col('id')], from: table('entity'), where: eligible }),
679
+ ),
680
+ },
681
+ { t: 'delete', from: 'entity', where: and(eligible, empty) },
682
+ {
683
+ t: 'insert',
684
+ into: 'entity',
685
+ cols: ['eid'],
686
+ q: select({ cols: [lit(null)], from: table('entity'), where: eligible }),
687
+ },
688
+ ]
689
+ }
690
+
691
+ /** Run an orphan repair's guarded physical erasure. */
692
+ export let prune = (driver: Driver, vocab: Vocab, eids: string[]): void => {
693
+ for (let s of pruneSql(vocab, eids, stood(driver, vocab))) effect(driver, s)
694
+ }
695
+
696
+ /**
697
+ * The statements that remove a set of entities: each component deletion and
698
+ * tombstone insert seeks one owner. An IN subquery lets small-table statistics
699
+ * choose a scan even for a single deletion; equality retains the primary-key
700
+ * plan. Tables arrive in declaration order and are cleared in reverse; an eid
701
+ * no entity uses tombstones nothing. Every statement fits the host bind limit.
702
+ */
703
+ export let removeSql = (
704
+ tables: string[],
705
+ entities: Entity[],
706
+ at: string,
707
+ ): Write[] => [
708
+ ...clearSql(tables, entities),
709
+ ...entities.map((e) => bury(e.eid, at)),
710
+ ]
711
+
712
+ /**
713
+ * The statements that erase a set of entities, a writer's own bookkeeping:
714
+ * their component rows as {@link removeSql} clears them, any before-image the
715
+ * trash kept of them (a patch that cleared a property keeps one), then their
716
+ * identity, with no tombstone and no pointer left to rewrite. Nothing else
717
+ * refers to such an entity, so its spine row goes with it.
718
+ */
719
+ export let eraseSql = (tables: string[], entities: Entity[]): Write[] => [
720
+ ...clearSql([TRASH, ...tables], entities),
721
+ ...entities.map((e): Delete => ({
722
+ t: 'delete',
723
+ from: 'entity',
724
+ where: eq(col('eid'), val(e.eid)),
725
+ })),
726
+ ]
727
+
728
+ // Each component row a set of entities holds, deleted owner by owner.
729
+ let clearSql = (tables: string[], entities: Entity[]): Delete[] =>
730
+ tables.toReversed()
731
+ .filter((comp) => comp != 'entity' && comp != TOMBSTONE)
732
+ .flatMap((comp) =>
733
+ entities.map((e): Delete => ({
734
+ t: 'delete',
735
+ from: comp,
736
+ where: eq(col('entity'), owner(e.eid)),
737
+ }))
738
+ )
739
+
740
+ // The tombstone an entity set's removal ends with.
741
+ let bury = (eid: string, at: string): Insert => ({
742
+ t: 'insert',
743
+ or: 'ignore',
744
+ into: 'tombstone',
745
+ cols: ['entity', 'deleted_at'],
746
+ q: select({
747
+ cols: [col('id'), val(at)],
748
+ from: table('entity'),
749
+ where: eq(col('eid'), val(eid)),
750
+ }),
751
+ })
752
+
753
+ /** Every eid these bundles touch or point at, in first-touch order — each
754
+ * bundle's own entity, then the targets of its reference properties. This is
755
+ * the order identity is minted in, so it is the order `num` follows. */
756
+ export let touched = (v: Vocab, bundles: Bundle[]): string[] =>
757
+ bundles.flatMap((b) => [
758
+ b.entity.eid,
759
+ ...(b.entity.archetype ? [b.entity.archetype] : []),
760
+ ...comps(b).flatMap(([name, comp]) =>
761
+ Object.entries(comp ?? {})
762
+ .filter(([prop, val]) => val != null && isRef(v, name, prop))
763
+ .map(([, val]) => String(val))
764
+ ),
765
+ ])
766
+
767
+ /**
768
+ * The classes a unit's births are minted in. An entity is first written in a
769
+ * shape (the tables its first patch gives it) and its unit points it at the
770
+ * class it finished in (@yaks/archetype's flush, after the stamps). Minted in
771
+ * that class from the start, its last pointer restates what its mint said and
772
+ * is not written: pointing an entity rewrites every index of its spine row,
773
+ * since the pointer is a key into the spine's own table. A birth of a shape
774
+ * not seen finishing yet, or one that finishes elsewhere, is pointed as before.
775
+ */
776
+ export type Births = {
777
+ /** The archetype's integer id a birth opening holding `tables` is minted
778
+ * in, where one is known. */
779
+ class: (tables: string[]) => number | undefined
780
+ /** `eid` was minted holding `tables`, in the archetype `id` if it says one. */
781
+ born: (eid: string, tables: string[], id?: number) => void
782
+ /** `eid` is pointed at the archetype `id`: whether its mint said so. */
783
+ pointed: (eid: string, id: number) => boolean
784
+ /** Whether `eid`'s mint wrote the pointer of the archetype that names
785
+ * exactly `tables`, so a birth that finished holding them owes none. */
786
+ settled: (eid: string, tables: string[]) => boolean
787
+ /** The archetype `id` names exactly `tables`, which `eid` finished in. */
788
+ finished: (eid: string, tables: string[], id: number) => void
789
+ }
790
+
791
+ /** One unit's {@link Births}, minted in what the connection learned. */
792
+ export let births = (driver: Driver): Births => {
793
+ let classes = classed(driver)
794
+ let shape = (tables: string[]) => JSON.stringify([...new Set(tables)].sort())
795
+ let open = new Map<string, { shape: string; id?: number }>()
796
+ return {
797
+ class: (tables) => classes.get(shape(tables)),
798
+ born: (eid, tables, id) => void open.set(eid, { shape: shape(tables), id }),
799
+ pointed: (eid, id) => {
800
+ let birth = open.get(eid)
801
+ if (!birth) return false
802
+ open.delete(eid)
803
+ classes.learn(birth.shape, id)
804
+ return birth.id == id
805
+ },
806
+ // A set's own archetype is kept beside the classes, under the shape no
807
+ // birth opens in.
808
+ settled: (eid, tables) => {
809
+ let id = classes.get(`=${shape(tables)}`)
810
+ if (id == null || open.get(eid)?.id != id) return false
811
+ open.delete(eid)
812
+ return true
813
+ },
814
+ finished: (eid, tables, id) => {
815
+ classes.learn(`=${shape(tables)}`, id)
816
+ let birth = open.get(eid)
817
+ if (!birth) return
818
+ open.delete(eid)
819
+ classes.learn(birth.shape, id)
820
+ },
821
+ }
822
+ }
823
+
824
+ // A patch's whole rows of components its entities did not hold, gathered by
825
+ // table and the properties they give, so each table is one statement a part
826
+ // (@yaks/sql `parts`) however many entities the patch gives it. Inside a
827
+ // transaction every write statement opens a savepoint, copies each page it
828
+ // changes into the statement journal, and FTS5 writes what it holds pending as
829
+ // a new segment: written a statement per row, a patch paid all three per row.
830
+ //
831
+ // Each entity's writes land in the order the patch gives them, since a
832
+ // trigger may read the entity's other rows (an index over two components, a
833
+ // host's own), and no one order of tables fits every entity. So the rows go in
834
+ // layers, each writing its tables in the order the patch first gave them
835
+ // there: a row joins its entity's last layer where its table comes after the
836
+ // entity's last row there, else the layer after. A write that is not gathered
837
+ // (`later`) runs at once for an entity with nothing gathered, and otherwise
838
+ // after its entity's layer, which the entity's next row then follows; a
839
+ // gathered row is told (`done`) once it is written, so what hears rows come
840
+ // and go hears each entity's in order too. A row
841
+ // whose values JSON would not carry as a bind does (@yaks/sql `jsonable`), or
842
+ // whose owner or target has no id here, is not taken and is written alone.
843
+ let wholes = (
844
+ driver: Driver,
845
+ vocab: Vocab,
846
+ ids: ReadonlyMap<string, number>,
847
+ ) => {
848
+ type Group = {
849
+ name: string
850
+ cols: string[]
851
+ rows: Param[][]
852
+ done: (() => void)[]
853
+ at: number
854
+ }
855
+ type Layer = { groups: Map<string, Group>; after: (() => void)[] }
856
+ let layers: Layer[] = []
857
+ // Where each entity's last gathered write is: its layer, and its table's
858
+ // place there, past every table for a write that runs after the layer.
859
+ let last = new Map<string, { layer: number; at: number }>()
860
+ let layer = (i: number) => layers[i] ??= { groups: new Map(), after: [] }
861
+ let flush = () => {
862
+ for (let { groups, after } of layers) {
863
+ for (let { name, cols, rows, done } of groups.values()) {
864
+ for (let part of sources(rows)) {
865
+ write(driver, rowsSql(vocab, name, cols, part))
866
+ }
867
+ for (let then of done) then()
868
+ }
869
+ for (let run of after) run()
870
+ }
871
+ layers = []
872
+ last.clear()
873
+ }
874
+ let later = (eid: string, run: () => void) => {
875
+ let at = last.get(eid)
876
+ if (!at) return run()
877
+ layer(at.layer).after.push(run)
878
+ last.set(eid, { layer: at.layer, at: Infinity })
879
+ }
880
+ let add = (
881
+ eid: string,
882
+ name: string,
883
+ comp: Comp,
884
+ done: () => void,
885
+ ): boolean => {
886
+ let id = ids.get(eid)
887
+ if (id == null) return false
888
+ let cols = Object.keys(comp).filter((c) =>
889
+ vocab.prop(name, c)?.computed === false
890
+ )
891
+ let row: Param[] = [id]
892
+ for (let c of cols) {
893
+ let raw = comp[c]
894
+ let value = raw != null && isRef(vocab, name, c)
895
+ ? ids.get(String(raw))
896
+ : isJsonb(vocab, name, c)
897
+ ? jsonIn(raw)
898
+ : scalar(raw)
899
+ if (value === undefined && raw != null || !jsonable(value)) return false
900
+ row.push(value ?? null)
901
+ }
902
+ let shape = `${name}\0${cols.join('\0')}`
903
+ let was = last.get(eid)
904
+ let i = was?.layer ?? 0
905
+ let { groups } = layer(i)
906
+ let at = groups.get(shape)?.at ?? groups.size
907
+ if (was && at <= was.at) {
908
+ groups = layer(++i).groups
909
+ at = groups.get(shape)?.at ?? groups.size
910
+ }
911
+ let group = groups.get(shape)
912
+ if (!group) {
913
+ groups.set(shape, group = { name, cols, rows: [], done: [], at })
914
+ }
915
+ group.rows.push(row)
916
+ group.done.push(done)
917
+ last.set(eid, { layer: i, at })
918
+ return true
919
+ }
920
+ return { add, later, flush }
921
+ }
922
+
923
+ /**
924
+ * How a store numbers its entities: not at all, by series given which letter
925
+ * each component numbers with ({@link Series}, @yaks/graph), or by the
926
+ * prefixes the vocabulary declares (`true`). An entity is numbered on the
927
+ * write that first gives it a component in the table, in the series
928
+ * `seriesOf` picks, and its letter never changes afterwards.
929
+ */
930
+ export type Numbering = boolean | Series
931
+
932
+ // The number an entity is minted with: none, or its own, with the letter of
933
+ // its series.
934
+ type Take = false | { num: number; prefix: string | null }
935
+
936
+ /**
937
+ * Patch a batch of bundles in, in order, and return the spines this patch
938
+ * minted or numbered — each with the `num` and `prefix` it was given, as the
939
+ * statement itself reported it. A bundle for a tombstoned entity is skipped:
940
+ * bringing one back is `revive`'s, which @yaks/graph asks for first.
941
+ *
942
+ * An eid a reference only names still gets a spine, because a reference column
943
+ * holds its target's id, but that spine takes no number: it is a pointer to
944
+ * nothing, which a yaks app pointing into another app's store makes on
945
+ * purpose, and @yaks/graph brings no entity into being for it. It is numbered
946
+ * when a bundle of its own arrives, in this batch or a later one.
947
+ *
948
+ * A number is the one after the last its series gave (`entity_series`),
949
+ * stepping over one an entity holds.
950
+ *
951
+ * `moved` hears each component row this patch brought or took away, as the
952
+ * table and whether the entity holds one now: what may have moved its
953
+ * archetype (./archetype.ts `ledger`). A value-only patch says nothing.
954
+ *
955
+ * `had` is what memory says an entity held before this patch: a component
956
+ * it does not hold is written in one statement, as a new entity's are.
957
+ *
958
+ * An entity minted here takes its pointer in its mint where one is known: the
959
+ * one its own bundle names, or the class `born` says its shape finishes in
960
+ * ({@link Births}). A pointer its mint already wrote is not written again.
961
+ *
962
+ * `unsettled` says what an entity this transaction wrote holds, where the
963
+ * patch reads one (./read.ts `Unsettled`).
964
+ *
965
+ * `names` says where an id kept as another entity's name lives, so a number
966
+ * kept so is stepped over ({@link Names}).
967
+ */
968
+ export let patch = (
969
+ driver: Driver,
970
+ vocab: Vocab,
971
+ bundles: Bundle[],
972
+ number: Numbering = false,
973
+ moved?: Moved,
974
+ had?: Known,
975
+ born?: Births,
976
+ unsettled?: Unsettled,
977
+ names?: Names,
978
+ ): Entity[] => {
979
+ // A computed component's rows are another package's (@yaks/sql `Backing`):
980
+ // there is no table here to write one to.
981
+ for (let b of bundles) {
982
+ for (let [name] of comps(b)) {
983
+ if (vocab.comp(name)?.computed) {
984
+ throw new Refused(`${name} is computed: it is read, never written`)
985
+ }
986
+ }
987
+ }
988
+ let from = revision(driver, 'descriptors')
989
+ let known = spines(driver, [...new Set(touched(vocab, bundles))])
990
+ let alive = bundles.filter((b) => !known.get(b.entity.eid)?.dead)
991
+ let ids = new Map([...known].map(([eid, row]) => [eid, row.id]))
992
+ let resolve: Resolve = (eid) => ids.has(eid) ? val(ids.get(eid)!) : owner(eid)
993
+ let pairOf = (eid: string): Pair | null | undefined => {
994
+ let k = known.get(eid)
995
+ return !k ? undefined : k.num == null ? null : {
996
+ num: k.num,
997
+ prefix: k.prefix ?? null,
998
+ }
999
+ }
1000
+
1001
+ // What each bundle states its entity's pair to be: one to take, or `null`
1002
+ // for none, born or not, checked against the pairs every other entity
1003
+ // holds, a tombstone's included (@yaks/graph `renumbering`). A
1004
+ // vocabulary that declares no number (@yaks/id) reads none back, and a
1005
+ // stated one says nothing to it.
1006
+ let stated = new Map<string, Pair | null>()
1007
+ for (let b of vocab.prop('entity', 'num') ? alive : []) {
1008
+ let pair = stating(b.entity, pairOf(b.entity.eid))
1009
+ if (pair !== undefined) stated.set(b.entity.eid, pair)
1010
+ }
1011
+ let renumbered = stated.size
1012
+ ? renumbering(
1013
+ stated,
1014
+ pairOf,
1015
+ holders(driver, [...stated.values()].flatMap((p) => p ? [p.num] : [])),
1016
+ )
1017
+ : new Map<string, Pair | null>()
1018
+ // An entity stated to hold none lets go of its pair, as does one whose
1019
+ // pair another entity of the batch takes, before any is given, so that one
1020
+ // is free for it. Every other entity moves in its one update: a number
1021
+ // taking its letter (yak/store/number-letter/1) writes its row and indexes
1022
+ // once, not twice.
1023
+ let taking = new Map<number, [string, Pair][]>()
1024
+ for (let [eid, pair] of renumbered) {
1025
+ if (pair) taking.set(pair.num, [...taking.get(pair.num) ?? [], [eid, pair]])
1026
+ }
1027
+ let moving = new Set([...renumbered.keys()].filter((eid) => {
1028
+ let held = known.get(eid)
1029
+ if (held?.num == null) return false
1030
+ if (renumbered.get(eid) == null) return true
1031
+ let was = { num: held.num, prefix: held.prefix ?? null }
1032
+ return (taking.get(was.num) ?? []).some(([other, pair]) =>
1033
+ other != eid && clash(pair, was)
1034
+ )
1035
+ }))
1036
+ for (let eid of moving) {
1037
+ renumber(driver, eid, known.get(eid)!, pairOf(eid) ?? null, null)
1038
+ }
1039
+ // The eids a bundle of their own arrives for: one giving a component, or
1040
+ // one stating the number.
1041
+ let own = new Set([
1042
+ ...alive.filter((b) => comps(b).some(([, c]) => c != null))
1043
+ .map((b) => b.entity.eid),
1044
+ ...stated.keys(),
1045
+ ])
1046
+
1047
+ // What the live bundles give each entity, and the pointer they name for
1048
+ // it: what a mint is told it opens holding, and the class it may take.
1049
+ let opening = new Map<string, string[]>()
1050
+ let named = new Map<string, string>()
1051
+ for (let b of alive) {
1052
+ let eid = b.entity.eid
1053
+ let held = opening.get(eid) ?? []
1054
+ opening.set(eid, held)
1055
+ for (let [name, comp] of comps(b)) if (comp != null) held.push(name)
1056
+ if (b.entity.archetype) named.set(eid, b.entity.archetype)
1057
+ }
1058
+ // The number an entity takes: the pair its bundle states; else none where
1059
+ // the store numbers nothing; else the next in the series its components
1060
+ // pick. `held` is what it holds besides this batch.
1061
+ let series = number
1062
+ ? seriesOf(vocab, number === true ? undefined : number)
1063
+ : undefined
1064
+ let given = new Map<string, number>()
1065
+ let take = (eid: string, held: string[] = []): Take => {
1066
+ let pair = stated.get(eid)
1067
+ if (pair?.prefix) {
1068
+ let last = lastIn(driver, pair.prefix, given)
1069
+ given.set(pair.prefix, Math.max(last, pair.num))
1070
+ }
1071
+ if (stated.has(eid)) return pair ?? false
1072
+ let prefix = series?.([...held, ...opening.get(eid) ?? []])
1073
+ if (!prefix) return false
1074
+ return { num: nextIn(driver, prefix, given, names), prefix }
1075
+ }
1076
+ // The pointer each mint wrote, so the bundle naming it writes it once.
1077
+ let pointers = new Map<string, number>()
1078
+ let made: Entity[] = []
1079
+ let seen = new Set(known.keys())
1080
+ // A mint the store learns of: its id, and the class it opened in.
1081
+ let took = (row: Row, tables: string[], pointer?: number) => {
1082
+ let id = Number(row.id)
1083
+ ids.set(String(row.eid), id)
1084
+ spined(driver).learn(String(row.eid), {
1085
+ id,
1086
+ num: row.num == null ? null : Number(row.num),
1087
+ prefix: row.prefix == null ? null : String(row.prefix),
1088
+ dead: false,
1089
+ })
1090
+ if (pointer != null) pointers.set(String(row.eid), pointer)
1091
+ born?.born(String(row.eid), tables, pointer)
1092
+ made.push(minted([row])!)
1093
+ }
1094
+ // The eids minted wait to be minted together, a statement a part
1095
+ // ({@link mintsSql}), so ids follow the batch's order.
1096
+ type Waiting = { tables: string[]; pointer?: number; take: Take }
1097
+ let waiting = new Map<string, Waiting>()
1098
+ let mint = () => {
1099
+ let rows = new Map<string, Row>()
1100
+ let list = [...waiting].map(([eid, w]) => [
1101
+ eid,
1102
+ w.pointer ?? null,
1103
+ w.take ? w.take.num : null,
1104
+ w.take ? w.take.prefix : null,
1105
+ ])
1106
+ for (let part of sources(list)) {
1107
+ for (let r of driver.query(mintsSql(part))) {
1108
+ rows.set(String(r.eid), r)
1109
+ }
1110
+ }
1111
+ for (let [eid, { tables, pointer }] of waiting) {
1112
+ let row = rows.get(eid)
1113
+ if (row) took(row, tables, pointer)
1114
+ }
1115
+ waiting.clear()
1116
+ }
1117
+ // Mint a spine for every eid the live bundles touch or point at, so a
1118
+ // reference can name a target created in the same batch, in any order. An
1119
+ // eid the store already knows is skipped here and would be a no-op anyway.
1120
+ for (let eid of touched(vocab, alive)) {
1121
+ if (seen.has(eid)) continue
1122
+ seen.add(eid)
1123
+ let tables = opening.get(eid) ?? []
1124
+ let to = named.get(eid)
1125
+ if (to != null && waiting.has(to)) mint()
1126
+ let pointer = to == null
1127
+ ? born?.class(tables)
1128
+ : to == eid
1129
+ ? undefined
1130
+ : ids.get(to)
1131
+ let t = own.has(eid) ? take(eid) : false
1132
+ waiting.set(eid, { tables, pointer, take: t })
1133
+ }
1134
+ mint()
1135
+ // A spine an earlier reference minted, or an entity numbered nothing so
1136
+ // far, is numbered now if its own bundle gives the first component in its
1137
+ // series.
1138
+ let pointed = [...own].filter((eid) => {
1139
+ let k = known.get(eid)
1140
+ return k && !k.dead && k.num == null && !stated.has(eid) && !!series &&
1141
+ !!series(opening.get(eid) ?? [])
1142
+ })
1143
+ if (pointed.length) {
1144
+ for (let b of get(driver, vocab, pointed, {}, undefined, unsettled)) {
1145
+ let held = comps(b).map(([name]) => name)
1146
+ let t = take(b.entity.eid, held)
1147
+ if (!t) continue
1148
+ let e = minted(driver.query(numberSql(b.entity.eid, t.num, t.prefix)))
1149
+ if (e) made.push(e)
1150
+ }
1151
+ }
1152
+ // Every entity the store held before the batch takes the pair stated for
1153
+ // it; one born here took it as it was minted.
1154
+ for (let [eid, pair] of renumbered) {
1155
+ let k = known.get(eid)
1156
+ let from = moving.has(eid) ? null : pairOf(eid) ?? null
1157
+ if (k && pair != null) renumber(driver, eid, k, from, pair)
1158
+ }
1159
+
1160
+ // The physical table is the last word on required columns: an older store
1161
+ // can still hold a stricter table while its vocabulary is being fitted.
1162
+ // A patch supplying every required value can use one INSERT…ON CONFLICT;
1163
+ // a partial one must UPDATE first, since SQLite checks NOT NULL before the
1164
+ // conflict handler can preserve the row's omitted values.
1165
+ let full = (name: string, comp: Comp): boolean => {
1166
+ let cols = Object.keys(comp).filter((c) =>
1167
+ vocab.prop(name, c)?.computed === false
1168
+ )
1169
+ return cols.length > 0 &&
1170
+ required(driver, name).every((prop) => comp[prop] != null)
1171
+ }
1172
+ // A spine minted here holds no row yet, nor does a component memory knows
1173
+ // an entity lacks, so a whole one is one INSERT…ON CONFLICT and certainly a
1174
+ // row that came. Anywhere else a write's own count says whether a row came
1175
+ // or went: the UPDATE hit, or the absent INSERT or the drop did something.
1176
+ let fresh = new Set(made.map((e) => e.eid))
1177
+ let lacks = (eid: string, name: string) =>
1178
+ fresh.has(eid) || had?.(eid, name) === null
1179
+ // What a patch gives a row memory knows, less what the row holds already:
1180
+ // writing a value again rewrites its row and every index over it. Memory
1181
+ // speaks of the row as this patch found it, so a row an earlier bundle of
1182
+ // the patch wrote is written as given.
1183
+ let wrote = new Set<string>()
1184
+ let news = (eid: string, name: string, comp: Comp): Comp => {
1185
+ let held = had?.(eid, name)
1186
+ if (!held || wrote.has(`${eid}\0${name}`)) return comp
1187
+ return Object.fromEntries(
1188
+ Object.entries(comp).filter(([prop, value]) =>
1189
+ !(prop in held) || !same(held[prop], value)
1190
+ ),
1191
+ )
1192
+ }
1193
+ let whole = wholes(driver, vocab, ids)
1194
+ for (let b of alive) {
1195
+ let eid = b.entity.eid
1196
+ for (let [name, given] of comps(b)) {
1197
+ let comp = given && news(eid, name, given)
1198
+ wrote.add(`${eid}\0${name}`)
1199
+ if (given != null && lacks(eid, name) && full(name, given)) {
1200
+ let came = () => moved?.(eid, name, true)
1201
+ if (!whole.add(eid, name, given, came)) {
1202
+ whole.later(eid, () => {
1203
+ write(driver, upsertSql(vocab, eid, name, given, false, resolve))
1204
+ came()
1205
+ })
1206
+ }
1207
+ continue
1208
+ }
1209
+ if (comp && Object.keys(given!).length && !Object.keys(comp).length) {
1210
+ continue
1211
+ }
1212
+ whole.later(eid, () => {
1213
+ let { first, fallback } = patchOne(vocab, eid, name, comp, resolve)
1214
+ let changes = ran(driver, first)
1215
+ // A write's own result avoids the absent INSERT when UPDATE hit. D1
1216
+ // still sends the complete plan atomically via patchSql; no read/merge.
1217
+ if (fallback && !changes) changes = ran(driver, fallback())
1218
+ else if (fallback) return
1219
+ if (changes) moved?.(eid, name, comp != null)
1220
+ })
1221
+ }
1222
+ }
1223
+ whole.flush()
1224
+
1225
+ // Metadata can classify a tombstone too; on its own it brings nothing back.
1226
+ // A pointer this entity's mint already wrote is not written again. The
1227
+ // entities pointed at one archetype both go by their integer ids are pointed
1228
+ // in one statement a part: a batch of births in a class the unit has not
1229
+ // seen finish, or of deaths, points hundreds of entities at one.
1230
+ let pointing = new Map<number, number[]>()
1231
+ for (let b of bundles) {
1232
+ let { eid, archetype } = b.entity
1233
+ let to = archetype == null ? undefined : ids.get(archetype)
1234
+ let said = to != null && born?.pointed(eid, to)
1235
+ if (to != null && (said || pointers.get(eid) == to)) continue
1236
+ let id = ids.get(eid)
1237
+ if (to == null || id == null) {
1238
+ for (let s of archetypeSql(b, ids)) effect(driver, s)
1239
+ continue
1240
+ }
1241
+ let group = pointing.get(to)
1242
+ if (!group) pointing.set(to, group = [])
1243
+ group.push(id)
1244
+ }
1245
+ for (let [to, owners] of pointing) {
1246
+ for (let i = 0; i < owners.length; i += POINTED) {
1247
+ effect(driver, {
1248
+ t: 'update',
1249
+ table: 'entity',
1250
+ set: { archetype: val(to) },
1251
+ where: oneOf(col('id'), owners.slice(i, i + POINTED)),
1252
+ })
1253
+ }
1254
+ }
1255
+ // The descriptors written here are all that moved one, unless one went.
1256
+ let defined = alive.filter((b) => b.archetype !== undefined)
1257
+ if (
1258
+ defined.length && defined.every((b) => b.archetype && ids.has(b.entity.eid))
1259
+ ) {
1260
+ described(
1261
+ driver,
1262
+ from,
1263
+ defined.map((b) => ({
1264
+ id: ids.get(b.entity.eid)!,
1265
+ eid: b.entity.eid,
1266
+ tables: String((b.archetype as Comp).tables),
1267
+ })),
1268
+ )
1269
+ }
1270
+ return made
1271
+ }
1272
+
1273
+ // How many rows a write changed: the driver's own count where it keeps one,
1274
+ // else the rows the statement returns. On a store with history a write runs
1275
+ // between the statements that keep its versions (./history.ts), those after it
1276
+ // made from the owners of the rows it returns, and the count is its own.
1277
+ let ran = (driver: Driver, w: Insert | Update | Delete): number => {
1278
+ let { before, write: one, after } = kept(driver, w)
1279
+ for (let s of before) effect(driver, s)
1280
+ if (after) return owned(driver, one, after)
1281
+ return driver.run?.(one) ??
1282
+ driver.query({ ...one, returning: [col('entity')] }).length
1283
+ }
1284
+
1285
+ // A write whose count nobody reads, kept the same way.
1286
+ let write = (driver: Driver, w: Write): void => {
1287
+ if (w.t == 'select') return void effect(driver, w)
1288
+ let { before, write: one, after } = kept(driver, w)
1289
+ for (let s of before) effect(driver, s)
1290
+ if (after) owned(driver, one, after)
1291
+ else effect(driver, one)
1292
+ }
1293
+
1294
+ // A write whose versions follow the rows it wrote: run returning their
1295
+ // owners, then what those owners need. Answers how many it wrote.
1296
+ let owned = (
1297
+ driver: Driver,
1298
+ one: Insert | Update | Delete,
1299
+ after: (owners: number[]) => Write[],
1300
+ ): number => {
1301
+ let rows = driver.query({ ...one, returning: [col('entity')] })
1302
+ for (let s of after(rows.map((r) => Number(r.entity)))) effect(driver, s)
1303
+ return rows.length
1304
+ }
1305
+
1306
+ /** What memory says an entity holds of a component, read or written before:
1307
+ * its row, with the values memory can vouch for as a read returns them,
1308
+ * `null` for none, and `undefined` where memory does not know (./memo.ts). */
1309
+ export type Known = (eid: string, name: string) => Comp | null | undefined
1310
+
1311
+ // Whether a value a patch gives is the one a row holds, as a read returns it.
1312
+ let same = (held: unknown, given: unknown): boolean =>
1313
+ held === given ||
1314
+ (typeof held == 'object' && typeof given == 'object' && held != null &&
1315
+ given != null && JSON.stringify(held) == JSON.stringify(given))
1316
+
1317
+ /** What hears a component row come (`held`) or go, entity by entity. */
1318
+ export type Moved = (eid: string, table: string, held: boolean) => void
1319
+
1320
+ /** Bring these tombstoned entities back: each tombstone row goes, and the
1321
+ * identity keeps its eid, number and integer id. No component returns; the
1322
+ * patch after it gives them. An eid with no tombstone is left alone; `moved`
1323
+ * hears each tombstone that went, as {@link patch} tells its rows. */
1324
+ export let revive = (driver: Driver, eids: string[], moved?: Moved): void => {
1325
+ for (let eid of eids) {
1326
+ if (ran(driver, unburySql(eid))) moved?.(eid, TOMBSTONE, false)
1327
+ }
1328
+ }
1329
+
1330
+ /**
1331
+ * Remove these entities: every component row they have goes, and their identity
1332
+ * is tombstoned, keeping its eid and number. Exactly the entities named —
1333
+ * @yaks/graph decided which they are. `held` is the tables they hold rows in,
1334
+ * where the caller knows (a store that keeps archetypes reads them off the
1335
+ * entities' pointers, ./archetype.ts `heldBy`); left out, it reads their
1336
+ * pointers itself. An unclassified entity is a failure, never every table.
1337
+ */
1338
+ export let remove = (
1339
+ driver: Driver,
1340
+ _vocab: Vocab,
1341
+ entities: Entity[],
1342
+ held: string[] = heldBy(driver, entities.map((e) => e.eid)),
1343
+ at: string = new Date().toISOString(),
1344
+ ): void => {
1345
+ for (let s of removeSql(held, entities, at)) write(driver, s)
1346
+ }
1347
+
1348
+ /** Erase these entities, rows and identity, leaving no tombstone
1349
+ * ({@link eraseSql}). `held` is as {@link remove} takes it. */
1350
+ export let erase = (
1351
+ driver: Driver,
1352
+ entities: Entity[],
1353
+ held: string[] = heldBy(driver, entities.map((e) => e.eid)),
1354
+ ): void => {
1355
+ for (let s of eraseSql(held, entities)) write(driver, s)
1356
+ }