@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/overlay.ts ADDED
@@ -0,0 +1,485 @@
1
+ // The batch as a set of tables. A rule is a query, and a query reads tables —
2
+ // so for a rule to be evaluated against a batch that has not been written yet,
3
+ // the batch has to be a table. This file makes it one: a `with` prefix of common
4
+ // table expressions, one per component the batch moved, each selecting
5
+ //
6
+ // the committed rows the batch did not touch + the batch's own rows
7
+ //
8
+ // and a rule's statement reads those names instead of the real ones. Nothing
9
+ // is created, nothing is dropped, and nothing outside the statement can see
10
+ // it: the overlay is part of the query, not a state the database is left in.
11
+ //
12
+ // This used to be temp tables shadowing the real ones, which was neater to read
13
+ // and wrong in the one place it had to work: a Durable Object's SQLite rejects
14
+ // a temp object outright (`not authorized: SQLITE_AUTH`), and a rule that only
15
+ // runs on a server is not the rule this graph wanted. A CTE runs everywhere
16
+ // SQL does, and it removed the shadowing hazard along with it — while a temp
17
+ // table stood, an unqualified INSERT would have landed in it.
18
+ //
19
+ // A patch is a PATCH, so a touched row is the committed row with the patch
20
+ // folded in — merged here, once, rather than by every rule. A `null` component
21
+ // drops it: the row is excluded from the committed arm and carries no row of
22
+ // its own. A deleted entity leaves the spine the same way, so every membership
23
+ // loses it.
24
+ //
25
+ // What the batch dropped is a second reading of the same batch, and it needs
26
+ // its own table: once a row is out of the overlay, "it is not there" and "the
27
+ // batch removed it" look identical, and `-comp` (@yaks/query) asks the second.
28
+ // So each dropped component gets a list of the entities it was removed from —
29
+ // the only question here a committed table can never answer, since the answer
30
+ // is exactly what is no longer in one. A tombstoned entity's own components are
31
+ // not enumerated: nothing matches a deleted entity anyway (every statement here
32
+ // is `live()`-guarded), and which components a bare tombstone carried is known
33
+ // to whoever read it before the batch, not to the batch.
34
+ //
35
+ // The SPINE is overlaid too, because a batch mints entities that have no
36
+ // integer id yet. They get a negative one here — the id space storage hands
37
+ // out is positive, so the two can never collide — and every reference to a
38
+ // fresh entity resolves to it, which is what lets a rule join across two
39
+ // entities the same batch created.
40
+ //
41
+ // Cost is a property of the batch, never of the database: the CTE names the
42
+ // committed table for everything it did not touch, so nothing is copied. Two
43
+ // statements and a handful of bound parameters, whatever is already in the
44
+ // file. See overlay_test.ts, which measures it.
45
+ //
46
+ // That holds only while SQLite reads the CTE in place, which takes two things.
47
+ // Each CTE is `not materialized`, or SQLite copies one a statement names twice
48
+ // whole. And each column of the batch's arm has its committed column's
49
+ // affinity (`typed`): SQLite flattens a `union all` into the statement that
50
+ // joins it only when its arms' columns agree in affinity, and a value read
51
+ // out of JSON has none. Flattened, a join on the owner is a primary-key lookup
52
+ // into the committed table; left whole, it is a scan of the committed table,
53
+ // on every write, whatever the batch.
54
+ //
55
+ // A possible client-side extension, unbuilt on purpose: this is all just a
56
+ // query, so a browser that keeps its cache as tables could run the same
57
+ // compiled rule against the same overlay. Nothing here assumes a server — but
58
+ // nothing here builds that either.
59
+
60
+ import { field } from '@yaks/sql'
61
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
62
+ import type { Bundle, Eid } from 'jsr:@yaks/graph@0.2.36'
63
+ import { comps, dead } from '@yaks/graph/bundle'
64
+ import {
65
+ and,
66
+ as,
67
+ call,
68
+ cast,
69
+ col,
70
+ type Cte,
71
+ type Driver,
72
+ each,
73
+ eq,
74
+ type Expr,
75
+ fn,
76
+ from,
77
+ isNull,
78
+ lit,
79
+ not,
80
+ notNull,
81
+ oneOf,
82
+ op,
83
+ type Param,
84
+ type Query,
85
+ select,
86
+ sub,
87
+ table,
88
+ unionAll,
89
+ val,
90
+ } from '@yaks/sql'
91
+ import { isJsonb, jsonIn, jsonOut } from './jsonb.js'
92
+ import { spines } from './write.js'
93
+ import { unraised } from './raise.js'
94
+
95
+ /** What an overlaid component's CTE is called. */
96
+ export let OVER = '_over_'
97
+ /** What the list of entities a batch dropped a component from is called. */
98
+ export let GONE = '_gone_'
99
+
100
+ /**
101
+ * A batch, made readable. `with` is the common table expressions a statement
102
+ * carries, and `at` names the source each component reads from — the
103
+ * overlay's where there is one, the committed table where the batch touched
104
+ * nothing.
105
+ */
106
+ export type Overlay = {
107
+ /** the CTEs, ready to put on a select (none when the batch moved nothing
108
+ * the caller asked about) */
109
+ with: Cte[]
110
+ /** the name of the source a component reads from */
111
+ at: (comp: string) => string
112
+ /** Read one overlay row by its owner without enumerating the batch. */
113
+ owned: (comp: string, owner: Expr) => Query | undefined
114
+ /** Read the owner ids matching an indexed reference. */
115
+ referring: (comp: string, column: string, target: Expr) => Query | undefined
116
+ /** the name of the list of entities this batch removed a component from —
117
+ * `null` where the batch removed none */
118
+ gone: (comp: string) => string | null
119
+ /** the components this overlay covers */
120
+ covers: string[]
121
+ /** the integer id each eid reads as inside it */
122
+ ids: Map<Eid, number>
123
+ }
124
+
125
+ // A list the batch supplies rides as one bound JSON array rather than a
126
+ // parameter per item (@yaks/sql `each`): a Durable Object binds at most 100 per
127
+ // statement, and a batch is as long as its writer made it. The batch's own
128
+ // rows ride the same way.
129
+
130
+ // A component's stored columns, in the order the table carries them.
131
+ let stored = (v: Vocab, comp: string): string[] =>
132
+ v.props(comp).map((p) => v.prop(comp, p)!).filter((c) => !c.computed)
133
+ .map((c) => c.prop)
134
+
135
+ // The spine's own columns. Fixed, because the identity table is fixed (ddl.ts
136
+ // SPINE); `archetype` rides with it where the vocabulary knows one.
137
+ let SPINE = ['id', 'eid', 'num', 'prefix', 'archetype']
138
+ // Their affinities, as ddl.ts declares them.
139
+ let SPINED: Record<string, Affinity> = {
140
+ id: 'integer',
141
+ eid: 'text',
142
+ num: 'integer',
143
+ prefix: 'text',
144
+ archetype: 'integer',
145
+ }
146
+
147
+ type Affinity = 'text' | 'real' | 'integer' | 'blob'
148
+
149
+ // A batch value read out of its JSON row, with the affinity of the committed
150
+ // column it stands beside. Every value here was lowered for that column
151
+ // (`lower`), so the cast changes no value the column would have kept: a JSON
152
+ // value's text becomes the binary JSON the column holds, which `json()` reads
153
+ // the same.
154
+ let typed = (e: Expr, affinity: Affinity, json: boolean): Expr =>
155
+ cast(json ? fn('jsonb', e) : e, affinity)
156
+
157
+ let fromRow = (value: Expr) => from(select({ cols: [as(value, 'value')] }))
158
+ let idPath = (id: Expr) => op('||', lit('$."'), id, lit('"'))
159
+
160
+ // What a property stores, the way ./write.ts lowers it: a boolean is 0/1, a
161
+ // reference is its target's integer id, a JSON value is its JSON text (which
162
+ // `json()` reads the way it reads the stored binary form), everything else
163
+ // passes through.
164
+ let lower = (
165
+ v: Vocab,
166
+ comp: string,
167
+ prop: string,
168
+ value: unknown,
169
+ ids: Map<Eid, number>,
170
+ ): Param => {
171
+ if (value == null) return null
172
+ if (v.prop(comp, prop)?.category == 'ref') {
173
+ return ids.get(String(value)) ?? null
174
+ }
175
+ if (isJsonb(v, comp, prop)) return jsonIn(value)
176
+ return typeof value == 'boolean' ? Number(value) : value as Param
177
+ }
178
+
179
+ // Every eid a batch names: the entities it is about, and the entities its
180
+ // reference properties point at. Both need an id, because a rule reads them the
181
+ // same way.
182
+ let named = (v: Vocab, bundles: Bundle[]): Eid[] => {
183
+ let out = new Set<Eid>()
184
+ for (let b of bundles) {
185
+ out.add(b.entity.eid)
186
+ for (let [comp, patch] of comps(b)) {
187
+ if (!patch) continue
188
+ for (let [prop, value] of Object.entries(patch)) {
189
+ if (
190
+ v.prop(comp, prop)?.category == 'ref' && typeof value == 'string'
191
+ ) {
192
+ out.add(value)
193
+ }
194
+ }
195
+ }
196
+ }
197
+ return [...out]
198
+ }
199
+
200
+ /**
201
+ * Read a batch as tables.
202
+ *
203
+ * ```ts ignore
204
+ * let over = overlay(driver, vocab, batch, ['product'])
205
+ * driver.query({ ...statement, with: over.with })
206
+ * ```
207
+ */
208
+ export let overlay = (
209
+ driver: Driver,
210
+ vocab: Vocab,
211
+ bundles: Bundle[],
212
+ only?: readonly string[],
213
+ ): Overlay => {
214
+ let wanted = only && new Set(only)
215
+ // Which components the batch moved. A component nobody touched needs no
216
+ // overlay: the committed table is already the whole result.
217
+ let touched = new Map<string, Map<Eid, Record<string, unknown> | null>>()
218
+ let dropped = new Map<string, Set<Eid>>()
219
+ let killed = new Set<Eid>()
220
+ let about = new Set<Eid>()
221
+ for (let b of bundles) {
222
+ about.add(b.entity.eid)
223
+ if (dead(b)) killed.add(b.entity.eid)
224
+ for (let [comp, patch] of comps(b)) {
225
+ if (!vocab.comp(comp) || (wanted && !wanted.has(comp))) continue
226
+ let rows = touched.get(comp) ?? new Map()
227
+ let held = rows.get(b.entity.eid)
228
+ // Dropped, and dropped last: a batch that removes a component and then
229
+ // writes it again has not removed it, so the second patch takes the
230
+ // entity back off the list the same way it puts the row back.
231
+ if (patch == null) {
232
+ dropped.set(comp, (dropped.get(comp) ?? new Set()).add(b.entity.eid))
233
+ } else dropped.get(comp)?.delete(b.entity.eid)
234
+ // Two patches for one entity in one batch compose, latest property wins.
235
+ rows.set(
236
+ b.entity.eid,
237
+ patch == null ? null : { ...(held ?? {}), ...patch },
238
+ )
239
+ touched.set(comp, rows)
240
+ }
241
+ }
242
+
243
+ // Every id the overlay speaks in. A committed entity keeps the one storage
244
+ // gave it, as the connection knows its spine; a fresh one is numbered
245
+ // downward from zero, where nothing else ever is.
246
+ let eids = named(vocab, bundles)
247
+ let ids = new Map(
248
+ [...spines(driver, eids)].map(([eid, spine]) => [eid, spine.id]),
249
+ )
250
+ let next = 0
251
+ let fresh: Eid[] = []
252
+ for (let eid of eids) {
253
+ if (ids.has(eid)) continue
254
+ ids.set(eid, --next)
255
+ if (about.has(eid)) fresh.push(eid)
256
+ }
257
+
258
+ let parts: Cte[] = []
259
+ let covers: string[] = []
260
+ let owners = new Map<string, (id: Expr) => Query>()
261
+ let references = new Map<
262
+ string,
263
+ (column: string, target: Expr) => Query | undefined
264
+ >()
265
+ let document = (name: string, value: unknown) => {
266
+ parts.push({
267
+ name,
268
+ q: select({
269
+ cols: [as(fn('jsonb', val(JSON.stringify(value))), 'rows')],
270
+ }),
271
+ })
272
+ return sub(select({ cols: [col('rows')], from: table(name) }))
273
+ }
274
+ // A component nothing has written has no table yet (./raise.ts): nothing
275
+ // of it is committed.
276
+ let unwritten = new Set(unraised(driver, vocab))
277
+ // One component's arm: the committed rows it did not touch, then its own.
278
+ // `kinds` is each column's affinity, the key's first, and whether it holds
279
+ // JSON.
280
+ let arm = (
281
+ comp: string,
282
+ key: string,
283
+ cols: string[],
284
+ kinds: [Affinity, boolean][],
285
+ from: string,
286
+ out: number[],
287
+ rows: Param[][],
288
+ ) => {
289
+ let names = [key, ...cols.map(field)]
290
+ let columns = names.map((c, i) =>
291
+ as(
292
+ typed(fn('json_extract', col('value'), lit(`$[${i}]`)), ...kinds[i]),
293
+ c,
294
+ )
295
+ )
296
+ // A keyed value is a replacement row. A JSON null hides a removed row
297
+ // and a missing key leaves the stored row visible.
298
+ let pending = out.length || rows.length
299
+ ? document(
300
+ '_pending_' + comp,
301
+ Object.fromEntries([
302
+ ...out.map((id) => [id, null]),
303
+ ...rows.map((row) => [row[0], row]),
304
+ ]),
305
+ )
306
+ : undefined
307
+ let mine = rows.length && pending
308
+ ? select({
309
+ cols: columns,
310
+ from: call('json_each', [pending]),
311
+ where: notNull(col('value')),
312
+ })
313
+ : undefined
314
+ let committed = (where?: Expr): Query =>
315
+ select({
316
+ cols: names.map((c) => col(c)),
317
+ from: table(from),
318
+ where,
319
+ })
320
+ let excluded = out.length ? not(oneOf(col(key), out)) : undefined
321
+ // A table nothing has raised holds no committed rows: the batch's are
322
+ // the whole of it.
323
+ let q: Query = unwritten.has(from)
324
+ ? mine ??
325
+ select({ cols: names.map((c) => as(lit(null), c)), where: lit(0) })
326
+ : mine
327
+ ? unionAll(committed(excluded), mine)
328
+ : committed(excluded)
329
+ parts.push({ name: OVER + comp, q, materialized: false })
330
+ covers.push(comp)
331
+
332
+ if (!pending) return
333
+ let stored = !unwritten.has(from)
334
+ let untouched = (id: Expr) => isNull(fn('json_type', pending, idPath(id)))
335
+ owners.set(comp, (id) => {
336
+ let replacement = select({
337
+ cols: columns,
338
+ from: fromRow(fn('jsonb_extract', pending, idPath(id))),
339
+ where: notNull(col('value')),
340
+ })
341
+ return stored
342
+ ? unionAll(
343
+ replacement,
344
+ committed(and(eq(col(key), id), untouched(id))),
345
+ )
346
+ : replacement
347
+ })
348
+ // A reference index returns only the owners that point at its target.
349
+ // Give the pending rows the same access path, including newly minted
350
+ // targets. Build buckets only for reference columns a match seeks.
351
+ let indexed = new Map<string, Expr>()
352
+ references.set(comp, (column, target) => {
353
+ let i = names.indexOf(column)
354
+ if (i < 1 || vocab.prop(comp, cols[i - 1])?.category != 'ref') return
355
+ let buckets = indexed.get(column)
356
+ if (!buckets) {
357
+ let grouped = new Map<number, Param[]>()
358
+ for (let row of rows) {
359
+ let ref = row[i]
360
+ if (typeof ref != 'number') continue
361
+ let ids = grouped.get(ref)
362
+ if (ids) ids.push(row[0])
363
+ else grouped.set(ref, [row[0]])
364
+ }
365
+ buckets = document(
366
+ '_pending_ref:' + comp + ':' + column,
367
+ Object.fromEntries(grouped),
368
+ )
369
+ indexed.set(column, buckets)
370
+ }
371
+ let replacement = select({
372
+ cols: [as(cast(col('value'), 'integer'), 'owner')],
373
+ from: call('json_each', [fn('jsonb_extract', buckets, idPath(target))]),
374
+ })
375
+ return stored
376
+ ? unionAll(
377
+ select({
378
+ cols: [as(col(key), 'owner')],
379
+ from: table(from),
380
+ where: and(eq(col(column), target), untouched(col(key))),
381
+ }),
382
+ replacement,
383
+ )
384
+ : replacement
385
+ })
386
+ }
387
+ // What a component's columns store as, its owner first.
388
+ let kinds = (comp: string, cols: string[]): [Affinity, boolean][] => [
389
+ ['integer', false],
390
+ ...cols.map((c): [Affinity, boolean] => [
391
+ vocab.prop(comp, c)!.affinity,
392
+ isJsonb(vocab, comp, c),
393
+ ]),
394
+ ]
395
+
396
+ for (let [comp, rows] of touched) {
397
+ let cols = stored(vocab, comp)
398
+ let owners = [...rows.keys()].map((e) => ids.get(e)!).filter((id) => id > 0)
399
+ // The committed row a patch folds into, read once per component.
400
+ let held = new Map<number, Record<string, unknown>>()
401
+ if (owners.length && !unwritten.has(comp)) {
402
+ // A JSON value is read as its text, to ride in the rows' JSON array.
403
+ let read = cols.map((c) =>
404
+ isJsonb(vocab, comp, c)
405
+ ? as(jsonOut(col(field(c))), c)
406
+ : as(col(field(c)), c)
407
+ )
408
+ for (
409
+ let row of driver.query(select({
410
+ cols: [col('entity'), ...read],
411
+ from: table(comp),
412
+ where: oneOf(col('entity'), owners),
413
+ }))
414
+ ) held.set(Number(row.entity), row)
415
+ }
416
+ arm(
417
+ comp,
418
+ 'entity',
419
+ cols,
420
+ kinds(comp, cols),
421
+ comp,
422
+ [...rows.keys()].map((e) => ids.get(e)!),
423
+ [...rows].flatMap(([eid, patch]) => {
424
+ if (!patch) return []
425
+ let id = ids.get(eid)!
426
+ let was = held.get(id) ?? {}
427
+ return [[
428
+ id,
429
+ ...cols.map((c) =>
430
+ c in patch
431
+ ? lower(vocab, comp, c, patch[c], ids)
432
+ : (was[c] ?? null) as Param
433
+ ),
434
+ ]]
435
+ }),
436
+ )
437
+ }
438
+
439
+ // The spine, where the batch moved it: a batch that patches entities that
440
+ // all exist already leaves the identity table alone.
441
+ if (fresh.length || killed.size) {
442
+ let cols = (vocab.comp('archetype') ? SPINE : SPINE.slice(0, 4)).slice(1)
443
+ arm(
444
+ 'entity',
445
+ 'id',
446
+ cols,
447
+ ['id', ...cols].map((c): [Affinity, boolean] => [SPINED[c], false]),
448
+ 'entity',
449
+ [...killed].map((e) => ids.get(e)!),
450
+ fresh.map((
451
+ eid,
452
+ ) => [ids.get(eid)!, eid, null, ...cols.slice(2).map(() => null)]),
453
+ )
454
+ }
455
+
456
+ // What the batch took, one list per component. A literal `values` list, not
457
+ // a select: these rows are the batch's own, and there is nothing committed
458
+ // left to read them from.
459
+ let took = new Set<string>()
460
+ for (let [comp, eids] of dropped) {
461
+ let rows = [...eids].map((e) => ids.get(e)!).filter((id) => id != null)
462
+ if (!rows.length) continue
463
+ parts.push({ name: GONE + comp, cols: ['entity'], q: each(rows) })
464
+ took.add(comp)
465
+ }
466
+
467
+ // A component the rules read that has no table, and the batch did not
468
+ // touch, reads as one nobody wears.
469
+ for (let comp of only ?? []) {
470
+ if (unwritten.has(comp) && !touched.has(comp)) {
471
+ let cols = stored(vocab, comp)
472
+ arm(comp, 'entity', cols, kinds(comp, cols), comp, [], [])
473
+ }
474
+ }
475
+ let over = new Set(covers)
476
+ return {
477
+ with: parts,
478
+ at: (comp) => over.has(comp) ? OVER + comp : comp,
479
+ owned: (comp, id) => owners.get(comp)?.(id),
480
+ referring: (comp, column, target) => references.get(comp)?.(column, target),
481
+ gone: (comp) => took.has(comp) ? GONE + comp : null,
482
+ covers,
483
+ ids,
484
+ }
485
+ }