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