@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
@@ -0,0 +1,240 @@
1
+ /// <reference lib="deno.ns" />
2
+ // Storage's byte contract, exercised unchanged by RAM and SQLite.
3
+ import { test } from 'jsr:@yaks/testing@0.2.36'
4
+ import { assertEquals, assertRejects, assertThrows } from 'jsr:@std/assert@^1.0.0'
5
+ import type { Binding, Bundle, Match } from 'jsr:@yaks/graph@0.2.36'
6
+ import { match, reads } from 'jsr:@yaks/graph@0.2.36/declared'
7
+ import { loadVocab } from 'jsr:@yaks/vocab@0.2.36'
8
+
9
+ export let binaryVocab = loadVocab({
10
+ $defs: {
11
+ document: {
12
+ component: true,
13
+ type: 'object',
14
+ properties: {
15
+ bytes: { type: 'string', contentEncoding: 'base64' },
16
+ title: { type: 'string' },
17
+ },
18
+ },
19
+ },
20
+ })
21
+
22
+ type Tx = {
23
+ patch: (bundles: Bundle[]) => unknown
24
+ get: (eids: string[]) => Bundle[]
25
+ read: (query: string) => Bundle[]
26
+ bindings: (
27
+ matches: Match[],
28
+ bundles: Bundle[],
29
+ covers: string[],
30
+ ) => Binding[][]
31
+ }
32
+ type Store = {
33
+ get: (eids: string[]) => Bundle[]
34
+ read: (query: string) => Bundle[]
35
+ rows: (query: string) => Record<string, unknown>[]
36
+ tx: <R>(body: (tx: Tx) => R) => R | Promise<Awaited<R>>
37
+ }
38
+ let bytes = (b: Bundle): Uint8Array | undefined =>
39
+ (b.document as { bytes?: Uint8Array }).bytes
40
+ let put = async (
41
+ s: Store,
42
+ eid: string,
43
+ value: Uint8Array | null,
44
+ ) => (await s.tx((tx) =>
45
+ tx.patch([{ entity: { eid }, document: { bytes: value } }])
46
+ ))
47
+ let ids = (s: Store, query: string) => s.read(query).map((b) => b.entity.eid)
48
+
49
+ export let binaryCases = async (make: () => Store): Promise<void> => {
50
+ let roundtrip = make()
51
+ let input = Uint8Array.of(99, 0, 255, 128, 42, 99).subarray(1, 5)
52
+ await put(roundtrip, 'bytes', input)
53
+ input.fill(17)
54
+ test('binary storage copies the byte view, not its surrounding buffer', () => {
55
+ assertEquals(
56
+ bytes(roundtrip.get(['bytes'])[0]),
57
+ Uint8Array.of(0, 255, 128, 42),
58
+ )
59
+ assertEquals(
60
+ bytes(roundtrip.read('.document')[0]),
61
+ Uint8Array.of(0, 255, 128, 42),
62
+ )
63
+ assertEquals(roundtrip.rows('.document .fields=document.bytes'), [
64
+ { eid: 'bytes', 'document.bytes': Uint8Array.of(0, 255, 128, 42) },
65
+ ])
66
+ })
67
+
68
+ let changed = make()
69
+ await put(changed, 'bytes', Uint8Array.of(1, 2))
70
+ test('binary patches replace the value and preserve it when omitted', async () => {
71
+ await put(changed, 'bytes', Uint8Array.of(255, 0, 128))
72
+ await changed.tx((tx) =>
73
+ tx.patch([{
74
+ entity: { eid: 'bytes' },
75
+ document: { title: 'kept' },
76
+ }])
77
+ )
78
+ assertEquals(bytes(changed.get(['bytes'])[0]), Uint8Array.of(255, 0, 128))
79
+ })
80
+
81
+ let cleared = make()
82
+ await put(cleared, 'bytes', Uint8Array.of(0, 255))
83
+ test('a null patch clears previously stored bytes', async () => {
84
+ await put(cleared, 'bytes', null)
85
+ assertEquals(bytes(cleared.get(['bytes'])[0]), undefined)
86
+ assertEquals(ids(cleared, '.document.bytes'), [])
87
+ })
88
+
89
+ let empty = make()
90
+ await put(empty, 'empty', new Uint8Array())
91
+ await put(empty, 'null', null)
92
+ await put(empty, 'full', Uint8Array.of(0, 255, 128))
93
+ test('zero bytes remain a BLOB, distinct from a cleared property', () => {
94
+ assertEquals(bytes(empty.get(['empty'])[0]), new Uint8Array())
95
+ assertEquals(bytes(empty.get(['null'])[0]), undefined)
96
+ assertEquals(ids(empty, '.document.bytes'), ['empty', 'full'])
97
+ assertEquals(ids(empty, '!document.bytes'), ['empty', 'null'])
98
+ })
99
+
100
+ let filters = make()
101
+ await put(filters, 'a', Uint8Array.of(0, 255, 128))
102
+ await put(filters, 'b', Uint8Array.of(0, 255))
103
+ await put(filters, 'c', Uint8Array.of(255))
104
+ await put(filters, 'empty', new Uint8Array())
105
+ await put(filters, 'null', null)
106
+ for (
107
+ let [operand, expected] of [
108
+ ['AP+A', ['a']],
109
+ ['AP8=', ['b']],
110
+ ['AP8', ['b']],
111
+ ['AP+A,/w==', ['a', 'c']],
112
+ ] as const
113
+ ) {
114
+ test(`binary equality and lists compare ${operand} by bytes`, () => {
115
+ assertEquals(ids(filters, `.document.bytes=${operand}`), [...expected])
116
+ })
117
+ }
118
+ test('binary inequality compares base64 operands by bytes', () => {
119
+ assertEquals(ids(filters, '.document.bytes!=AP8='), [
120
+ 'a',
121
+ 'c',
122
+ 'empty',
123
+ 'null',
124
+ ])
125
+ })
126
+ for (let operand of ['%', 'A', 'AP9=', 'AP8===']) {
127
+ test(`binary query operands refuse malformed base64 ${operand}`, () => {
128
+ assertThrows(
129
+ () => filters.read(`.document.bytes=${operand}`),
130
+ Error,
131
+ 'base64',
132
+ )
133
+ })
134
+ }
135
+ for (
136
+ let query of [
137
+ '.document.bytes~=AP8=',
138
+ '.document.bytes<AP8=',
139
+ '.document.bytes=AA==..AQ==',
140
+ ]
141
+ ) {
142
+ test(`binary query operands refuse text operation ${query}`, () => {
143
+ assertThrows(() => filters.read(query), Error, 'cannot compile')
144
+ })
145
+ }
146
+
147
+ let aggregates = make()
148
+ await put(aggregates, 'a', Uint8Array.of(255))
149
+ await put(aggregates, 'b', Uint8Array.of(0, 255))
150
+ await put(aggregates, 'c', Uint8Array.of(0, 255))
151
+ await put(aggregates, 'empty', new Uint8Array())
152
+ await put(aggregates, 'null', null)
153
+ test('binary ordering retains byte values and content identity', () => {
154
+ assertEquals(ids(aggregates, '.document .order=document.bytes'), [
155
+ 'null',
156
+ 'empty',
157
+ 'c',
158
+ 'b',
159
+ 'a',
160
+ ])
161
+ })
162
+ test('binary distinct retains byte values and content identity', () => {
163
+ assertEquals(aggregates.rows('.document .distinct=document.bytes'), [
164
+ { value: new Uint8Array() },
165
+ { value: Uint8Array.of(0, 255) },
166
+ { value: Uint8Array.of(255) },
167
+ ])
168
+ })
169
+ test('binary tally retains byte values and content identity', () => {
170
+ assertEquals(aggregates.rows('.document .tally=document.bytes'), [
171
+ { value: new Uint8Array(), n: 1 },
172
+ { value: Uint8Array.of(0, 255), n: 2 },
173
+ { value: Uint8Array.of(255), n: 1 },
174
+ ])
175
+ })
176
+
177
+ let isolated = make()
178
+ await put(isolated, 'a', Uint8Array.of(0, 255))
179
+ test('mutating bytes returned by get, read or projection cannot change storage', () => {
180
+ bytes(isolated.get(['a'])[0])!.fill(1)
181
+ bytes(isolated.read('.document')[0])!.fill(2)
182
+ let row = isolated.rows('.document .fields=document.bytes')[0]
183
+ ;(row['document.bytes'] as Uint8Array).fill(3)
184
+ assertEquals(bytes(isolated.get(['a'])[0]), Uint8Array.of(0, 255))
185
+ })
186
+
187
+ let joins = make()
188
+ await put(joins, 'a', Uint8Array.of(0, 255))
189
+ await put(joins, 'b', Uint8Array.of(0, 255))
190
+ await put(joins, 'c', Uint8Array.of(255, 0))
191
+ let joined = match(
192
+ '$left .document.bytes=$bytes; $right .document.bytes=$bytes',
193
+ )
194
+ test('rule joins compare independently held bytes by content', async () => {
195
+ let [found] = await joins.tx((tx) =>
196
+ tx.bindings([joined], [], reads(joined, binaryVocab))
197
+ )
198
+ assertEquals(found.map((b) => b.entities.join(':')).sort(), [
199
+ 'a:a',
200
+ 'a:b',
201
+ 'b:a',
202
+ 'b:b',
203
+ 'c:c',
204
+ ])
205
+ assertEquals(
206
+ found.find((b) => b.entities[0] == 'a')?.vars.bytes,
207
+ Uint8Array.of(0, 255),
208
+ )
209
+ })
210
+
211
+ let visible = make()
212
+ await put(visible, 'a', Uint8Array.of(0, 255))
213
+ test('binary writes are visible in their transaction', async () => {
214
+ await visible.tx((tx) => {
215
+ tx.patch([{
216
+ entity: { eid: 'a' },
217
+ document: { bytes: Uint8Array.of(128) },
218
+ }])
219
+ assertEquals(bytes(tx.get(['a'])[0]), Uint8Array.of(128))
220
+ assertEquals(bytes(tx.read('.document')[0]), Uint8Array.of(128))
221
+ })
222
+ })
223
+
224
+ let rollback = make()
225
+ await put(rollback, 'a', Uint8Array.of(0, 255))
226
+ test('binary writes roll back on failure', async () => {
227
+ await assertRejects(
228
+ async () => (await rollback.tx((tx) => {
229
+ tx.patch([{
230
+ entity: { eid: 'a' },
231
+ document: { bytes: Uint8Array.of(128) },
232
+ }])
233
+ throw new Error('rollback bytes')
234
+ })),
235
+ Error,
236
+ 'rollback bytes',
237
+ )
238
+ assertEquals(bytes(rollback.get(['a'])[0]), Uint8Array.of(0, 255))
239
+ })
240
+ }
package/branches.js ADDED
@@ -0,0 +1,195 @@
1
+ // A store's branches (D-395): rows of its branch table. Making one writes a
2
+ // row and copies nothing; a branch's rows live beside the live tables, in
3
+ // `<comp>$versions` and the archetypes' versions, under its id, and dropping
4
+ // it keeps them in trash. Reading and writing on one is a driver of its own
5
+ // (./mode.ts), which its host opens.
6
+ //
7
+ // What a branch changed is read on main's own connection, from those rows:
8
+ // for each entity's component the branch holds a row of, its open row (or
9
+ // none, where the branch removed it), main's version as of the fork, and the
10
+ // live row. Merging them is the history plugin's (@yaks/journal).
11
+ import { and, as, col, eq, isNull, left, lit, not, oneOf, op, or, select, sub, table, val } from "@yaks/sql";
12
+ import { eidOf } from "@yaks/archetype/sets";
13
+ import { beside, BRANCH, BRANCH_TRASH, BRANCHES, covered, FROM, keeps, SEEDING, TO } from "./history.js";
14
+ import { described } from "./archetype.js";
15
+ import { rowsOf } from "./read.js";
16
+ import { unraised } from "./raise.js";
17
+ import { meta } from "./meta.js";
18
+ import { Refused } from "@yaks/graph/errors";
19
+ /** Whether the store over `driver` is still taking its live rows as their
20
+ * first versions (`Opts.paced`): what maintain() owes it. */ export let seeding = (driver)=>meta(driver).get(SEEDING) != null;
21
+ /** A store still taking its live rows as their first versions (`Opts.paced`)
22
+ * makes no branch yet: one would read main as of a fork that misses every
23
+ * row not taken. Asked again once maintain() has taken the last page. */ export class Unseeded extends Refused {
24
+ constructor(){
25
+ super('this store is still keeping its rows as their first versions; ' + 'make the branch again in a moment');
26
+ this.name = 'Unseeded';
27
+ }
28
+ }
29
+ // The branch table's rows, oldest first; trashed ones stay beside them.
30
+ let rows = (driver, where, trash = false)=>driver.query(select({
31
+ cols: [
32
+ col('id', 'b'),
33
+ col('fork', 'b'),
34
+ col('at', 'b'),
35
+ as(col('at', 't'), 'trashed')
36
+ ],
37
+ from: table(BRANCHES, 'b'),
38
+ joins: [
39
+ left(table(BRANCH_TRASH, 't'), eq(col('id', 'b'), col('id', 't')))
40
+ ],
41
+ where: and(trash ? not(isNull(col('at', 't'))) : isNull(col('at', 't')), ...where ? [
42
+ where
43
+ ] : []),
44
+ order: [
45
+ col('id', 'b')
46
+ ]
47
+ })).map((row)=>({
48
+ id: Number(row.id),
49
+ fork: Number(row.fork),
50
+ at: String(row.at),
51
+ ...row.trashed == null ? {} : {
52
+ trashed: String(row.trashed)
53
+ }
54
+ }));
55
+ /** Make a branch of main at its newest transaction: one row, nothing copied.
56
+ * Answers its id and the transaction it forked at. */ export let branch = (driver, history)=>{
57
+ let fork = Number(driver.query(history.tip)[0]?.id ?? 0);
58
+ let [row] = driver.query({
59
+ t: 'insert',
60
+ into: BRANCHES,
61
+ cols: [
62
+ 'parent',
63
+ 'fork',
64
+ 'at'
65
+ ],
66
+ rows: [
67
+ [
68
+ lit(0),
69
+ val(fork),
70
+ val(new Date().toISOString())
71
+ ]
72
+ ],
73
+ returning: [
74
+ col('id')
75
+ ]
76
+ });
77
+ return {
78
+ branch: Number(row.id),
79
+ fork
80
+ };
81
+ };
82
+ /** The branch `id`, as a mode: where it forked. Undefined for none. */ export let branchOf = (driver, id)=>{
83
+ let [b] = rows(driver, eq(col('id', 'b'), val(id)));
84
+ return b ? {
85
+ branch: id,
86
+ fork: b.fork
87
+ } : undefined;
88
+ };
89
+ /**
90
+ * What branch `b` changed since its fork, read with `opts` as any read is:
91
+ * each entity's component it holds a row of, at the fork, on the branch and on
92
+ * main now. A component main keeps no versions of is left out, and so is the
93
+ * archetype, which is the store's own.
94
+ */ export let changes = (driver, vocab, b, opts = {})=>{
95
+ let absent = new Set(unraised(driver, vocab));
96
+ let out = [];
97
+ for (let comp of covered(vocab)){
98
+ if (comp == 'archetype' || !keeps(vocab, comp)) continue;
99
+ let to = beside(comp);
100
+ let ids = driver.query(select({
101
+ distinct: true,
102
+ cols: [
103
+ col('entity')
104
+ ],
105
+ from: table(to),
106
+ where: eq(col(BRANCH), val(b.id))
107
+ })).map((r)=>Number(r.entity));
108
+ if (!ids.length) continue;
109
+ let open = rowsOf(driver, vocab, comp, to, and(eq(col(BRANCH, comp), val(b.id)), eq(col(TO, comp), lit(0)), oneOf(col('entity', comp), ids)), opts);
110
+ let fork = rowsOf(driver, vocab, comp, to, and(eq(col(BRANCH, comp), lit(0)), or(isNull(col(FROM, comp)), op('<=', col(FROM, comp), val(b.fork))), or(eq(col(TO, comp), lit(0)), op('>', col(TO, comp), val(b.fork))), oneOf(col('entity', comp), ids)), opts);
111
+ let main = absent.has(comp) ? new Map() : rowsOf(driver, vocab, comp, comp, oneOf(col('entity', comp), ids), opts);
112
+ let eids = new Map(driver.query(select({
113
+ cols: [
114
+ col('id'),
115
+ col('eid')
116
+ ],
117
+ from: table('entity'),
118
+ where: oneOf(col('id'), ids)
119
+ })).map((r)=>[
120
+ Number(r.id),
121
+ String(r.eid)
122
+ ]));
123
+ for (let id of ids){
124
+ out.push({
125
+ eid: eids.get(id),
126
+ comp,
127
+ fork: fork.get(id) ?? null,
128
+ branch: open.get(id) ?? null,
129
+ main: main.get(id) ?? null
130
+ });
131
+ }
132
+ }
133
+ return out;
134
+ };
135
+ /** The branches of the store with history over `driver`, its changes read
136
+ * with `opts` as its reads are. Making one makes sure main has the archetype
137
+ * of an entity holding nothing, which an entity the branch makes is on main. */ export let branching = (driver, vocab, history, opts = ()=>({}))=>({
138
+ make: ()=>{
139
+ if (seeding(driver)) throw new Unseeded();
140
+ described(driver, []);
141
+ return rows(driver, eq(col('id', 'b'), val(branch(driver, history).branch)))[0];
142
+ },
143
+ list: (trash)=>rows(driver, undefined, trash),
144
+ drop: (id)=>{
145
+ driver.query({
146
+ t: 'insert',
147
+ into: BRANCH_TRASH,
148
+ cols: [
149
+ 'id',
150
+ 'at'
151
+ ],
152
+ q: select({
153
+ cols: [
154
+ col('id'),
155
+ val(new Date().toISOString())
156
+ ],
157
+ from: table(BRANCHES),
158
+ where: eq(col('id'), val(id))
159
+ }),
160
+ or: 'ignore'
161
+ });
162
+ },
163
+ restore: (id)=>{
164
+ driver.query({
165
+ t: 'delete',
166
+ from: BRANCH_TRASH,
167
+ where: eq(col('id'), val(id))
168
+ });
169
+ },
170
+ changes: (id)=>{
171
+ let [b] = rows(driver, eq(col('id', 'b'), val(id)));
172
+ if (!b) throw new Error(`no branch ${id}`);
173
+ return changes(driver, vocab, b, opts());
174
+ }
175
+ });
176
+ /** The entities a branch just made, pointed at main's archetype of nothing:
177
+ * a pointer says what an entity holds on main, and on main each holds
178
+ * nothing. Main keeps that archetype from the branch's making (`branching`). */ export let unborn = (driver, eids)=>{
179
+ if (!eids.length) return;
180
+ driver.query({
181
+ t: 'update',
182
+ table: 'entity',
183
+ set: {
184
+ archetype: sub(select({
185
+ cols: [
186
+ col('id')
187
+ ],
188
+ from: table('entity'),
189
+ where: eq(col('eid'), val(eidOf([])))
190
+ }))
191
+ },
192
+ where: and(oneOf(col('eid'), eids), isNull(col('archetype')))
193
+ });
194
+ };
195
+ //# sourceMappingURL=branches.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"branches.js","sources":["./branches.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,0EAA0E;AAC1E,6EAA6E;AAC7E,4EAA4E;AAC5E,qCAAqC;AACrC,EAAE;AACF,2EAA2E;AAC3E,0EAA0E;AAC1E,6EAA6E;AAC7E,kEAAkE;AAElE,SACE,GAAG,EACH,EAAE,EACF,GAAG,EAEH,EAAE,EAEF,MAAM,EACN,IAAI,EACJ,GAAG,EACH,GAAG,EACH,KAAK,EACL,EAAE,EACF,EAAE,EACF,MAAM,EACN,GAAG,EACH,KAAK,EACL,GAAG,yBACwB;AAG7B,SAAS,KAAK,oCAAyC;AAEvD,SACE,MAAM,EACN,MAAM,EACN,YAAY,EACZ,QAAQ,EACR,OAAO,EACP,IAAI,EAEJ,KAAK,EAEL,OAAO,EACP,EAAE,uBACiB;AACrB,SAAS,SAAS,yBAAwB;AAC1C,SAAS,MAAM,oBAAmB;AAClC,SAAS,QAAQ,qBAAoB;AACrC,SAAS,IAAI,oBAAmB;AAChC,SAAS,OAAO,kCAAuC;AAEvD;2DAC2D,GAC3D,OAAO,IAAI,UAAU,CAAC,SACpB,KAAK,QAAQ,GAAG,CAAC,YAAY,KAAI;AAEnC;;uEAEuE,GACvE,OAAO,MAAM,iBAAiB;EAC5B,aAAc;IACZ,KAAK,CACH,mEACE;IAEJ,IAAI,CAAC,IAAI,GAAG;EACd;AACF;AAEA,wEAAwE;AACxE,IAAI,OAAO,CAAC,QAAgB,OAAc,QAAQ,KAAK,GACrD,OAAO,KAAK,CAAC,OAAO;IAClB,MAAM;MACJ,IAAI,MAAM;MACV,IAAI,QAAQ;MACZ,IAAI,MAAM;MACV,GAAG,IAAI,MAAM,MAAM;KACpB;IACD,MAAM,MAAM,UAAU;IACtB,OAAO;MAAC,KAAK,MAAM,cAAc,MAAM,GAAG,IAA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AI;SAAM;QACjB,MAAM,MAAM;QACZ,OAAO,GAAG,IAAI,QAAQ,IAAI,MAAM,EAAE;MACpC;IACF;IACA,OAAO,IAAI,MAAM,IAAI,QAAQ,OAAO,OAAO,IAAI;EACjD;AACF,EAAC"}
package/branches.ts ADDED
@@ -0,0 +1,257 @@
1
+ // A store's branches (D-395): rows of its branch table. Making one writes a
2
+ // row and copies nothing; a branch's rows live beside the live tables, in
3
+ // `<comp>$versions` and the archetypes' versions, under its id, and dropping
4
+ // it keeps them in trash. Reading and writing on one is a driver of its own
5
+ // (./mode.ts), which its host opens.
6
+ //
7
+ // What a branch changed is read on main's own connection, from those rows:
8
+ // for each entity's component the branch holds a row of, its open row (or
9
+ // none, where the branch removed it), main's version as of the fork, and the
10
+ // live row. Merging them is the history plugin's (@yaks/journal).
11
+
12
+ import {
13
+ and,
14
+ as,
15
+ col,
16
+ type Driver,
17
+ eq,
18
+ type Expr,
19
+ isNull,
20
+ left,
21
+ lit,
22
+ not,
23
+ oneOf,
24
+ op,
25
+ or,
26
+ select,
27
+ sub,
28
+ table,
29
+ val,
30
+ } from '@yaks/sql'
31
+ import type { BindOpts } from 'jsr:@yaks/sql@0.2.36/query'
32
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
33
+ import { eidOf } from '@yaks/archetype/sets'
34
+ import type { Branch, Branches, Change } from 'jsr:@yaks/graph@0.2.36/storage'
35
+ import {
36
+ beside,
37
+ BRANCH,
38
+ BRANCH_TRASH,
39
+ BRANCHES,
40
+ covered,
41
+ FROM,
42
+ type History,
43
+ keeps,
44
+ type Mode,
45
+ SEEDING,
46
+ TO,
47
+ } from './history.js'
48
+ import { described } from './archetype.js'
49
+ import { rowsOf } from './read.js'
50
+ import { unraised } from './raise.js'
51
+ import { meta } from './meta.js'
52
+ import { Refused } from '@yaks/graph/errors'
53
+
54
+ /** Whether the store over `driver` is still taking its live rows as their
55
+ * first versions (`Opts.paced`): what maintain() owes it. */
56
+ export let seeding = (driver: Driver): boolean =>
57
+ meta(driver).get(SEEDING) != null
58
+
59
+ /** A store still taking its live rows as their first versions (`Opts.paced`)
60
+ * makes no branch yet: one would read main as of a fork that misses every
61
+ * row not taken. Asked again once maintain() has taken the last page. */
62
+ export class Unseeded extends Refused {
63
+ constructor() {
64
+ super(
65
+ 'this store is still keeping its rows as their first versions; ' +
66
+ 'make the branch again in a moment',
67
+ )
68
+ this.name = 'Unseeded'
69
+ }
70
+ }
71
+
72
+ // The branch table's rows, oldest first; trashed ones stay beside them.
73
+ let rows = (driver: Driver, where?: Expr, trash = false): Branch[] =>
74
+ driver.query(select({
75
+ cols: [
76
+ col('id', 'b'),
77
+ col('fork', 'b'),
78
+ col('at', 'b'),
79
+ as(col('at', 't'), 'trashed'),
80
+ ],
81
+ from: table(BRANCHES, 'b'),
82
+ joins: [left(table(BRANCH_TRASH, 't'), eq(col('id', 'b'), col('id', 't')))],
83
+ where: and(
84
+ trash ? not(isNull(col('at', 't'))) : isNull(col('at', 't')),
85
+ ...(where ? [where] : []),
86
+ ),
87
+ order: [col('id', 'b')],
88
+ })).map((row) => ({
89
+ id: Number(row.id),
90
+ fork: Number(row.fork),
91
+ at: String(row.at),
92
+ ...(row.trashed == null ? {} : { trashed: String(row.trashed) }),
93
+ }))
94
+
95
+ /** Make a branch of main at its newest transaction: one row, nothing copied.
96
+ * Answers its id and the transaction it forked at. */
97
+ export let branch = (
98
+ driver: Driver,
99
+ history: History,
100
+ ): { branch: number; fork: number } => {
101
+ let fork = Number(driver.query(history.tip)[0]?.id ?? 0)
102
+ let [row] = driver.query({
103
+ t: 'insert',
104
+ into: BRANCHES,
105
+ cols: ['parent', 'fork', 'at'],
106
+ rows: [[lit(0), val(fork), val(new Date().toISOString())]],
107
+ returning: [col('id')],
108
+ })
109
+ return { branch: Number(row.id), fork }
110
+ }
111
+
112
+ /** The branch `id`, as a mode: where it forked. Undefined for none. */
113
+ export let branchOf = (driver: Driver, id: number): Mode | undefined => {
114
+ let [b] = rows(driver, eq(col('id', 'b'), val(id)))
115
+ return b ? { branch: id, fork: b.fork } : undefined
116
+ }
117
+
118
+ /**
119
+ * What branch `b` changed since its fork, read with `opts` as any read is:
120
+ * each entity's component it holds a row of, at the fork, on the branch and on
121
+ * main now. A component main keeps no versions of is left out, and so is the
122
+ * archetype, which is the store's own.
123
+ */
124
+ export let changes = (
125
+ driver: Driver,
126
+ vocab: Vocab,
127
+ b: Branch,
128
+ opts: BindOpts = {},
129
+ ): Change[] => {
130
+ let absent = new Set(unraised(driver, vocab))
131
+ let out: Change[] = []
132
+ for (let comp of covered(vocab)) {
133
+ if (comp == 'archetype' || !keeps(vocab, comp)) continue
134
+ let to = beside(comp)
135
+ let ids = driver.query(select({
136
+ distinct: true,
137
+ cols: [col('entity')],
138
+ from: table(to),
139
+ where: eq(col(BRANCH), val(b.id)),
140
+ })).map((r) => Number(r.entity))
141
+ if (!ids.length) continue
142
+ let open = rowsOf(
143
+ driver,
144
+ vocab,
145
+ comp,
146
+ to,
147
+ and(
148
+ eq(col(BRANCH, comp), val(b.id)),
149
+ eq(col(TO, comp), lit(0)),
150
+ oneOf(col('entity', comp), ids),
151
+ ),
152
+ opts,
153
+ )
154
+ let fork = rowsOf(
155
+ driver,
156
+ vocab,
157
+ comp,
158
+ to,
159
+ and(
160
+ eq(col(BRANCH, comp), lit(0)),
161
+ or(isNull(col(FROM, comp)), op('<=', col(FROM, comp), val(b.fork))),
162
+ or(eq(col(TO, comp), lit(0)), op('>', col(TO, comp), val(b.fork))),
163
+ oneOf(col('entity', comp), ids),
164
+ ),
165
+ opts,
166
+ )
167
+ let main = absent.has(comp) ? new Map() : rowsOf(
168
+ driver,
169
+ vocab,
170
+ comp,
171
+ comp,
172
+ oneOf(col('entity', comp), ids),
173
+ opts,
174
+ )
175
+ let eids = new Map(
176
+ driver.query(select({
177
+ cols: [col('id'), col('eid')],
178
+ from: table('entity'),
179
+ where: oneOf(col('id'), ids),
180
+ })).map((r) => [Number(r.id), String(r.eid)]),
181
+ )
182
+ for (let id of ids) {
183
+ out.push({
184
+ eid: eids.get(id)!,
185
+ comp,
186
+ fork: fork.get(id) ?? null,
187
+ branch: open.get(id) ?? null,
188
+ main: main.get(id) ?? null,
189
+ })
190
+ }
191
+ }
192
+ return out
193
+ }
194
+
195
+ /** The branches of the store with history over `driver`, its changes read
196
+ * with `opts` as its reads are. Making one makes sure main has the archetype
197
+ * of an entity holding nothing, which an entity the branch makes is on main. */
198
+ export let branching = (
199
+ driver: Driver,
200
+ vocab: Vocab,
201
+ history: History,
202
+ opts: () => BindOpts = () => ({}),
203
+ ): Branches => ({
204
+ make: () => {
205
+ if (seeding(driver)) throw new Unseeded()
206
+ described(driver, [])
207
+ return rows(
208
+ driver,
209
+ eq(col('id', 'b'), val(branch(driver, history).branch)),
210
+ )[0]
211
+ },
212
+ list: (trash) => rows(driver, undefined, trash),
213
+ drop: (id) => {
214
+ driver.query({
215
+ t: 'insert',
216
+ into: BRANCH_TRASH,
217
+ cols: ['id', 'at'],
218
+ q: select({
219
+ cols: [col('id'), val(new Date().toISOString())],
220
+ from: table(BRANCHES),
221
+ where: eq(col('id'), val(id)),
222
+ }),
223
+ or: 'ignore',
224
+ })
225
+ },
226
+ restore: (id) => {
227
+ driver.query({
228
+ t: 'delete',
229
+ from: BRANCH_TRASH,
230
+ where: eq(col('id'), val(id)),
231
+ })
232
+ },
233
+ changes: (id) => {
234
+ let [b] = rows(driver, eq(col('id', 'b'), val(id)))
235
+ if (!b) throw new Error(`no branch ${id}`)
236
+ return changes(driver, vocab, b, opts())
237
+ },
238
+ })
239
+
240
+ /** The entities a branch just made, pointed at main's archetype of nothing:
241
+ * a pointer says what an entity holds on main, and on main each holds
242
+ * nothing. Main keeps that archetype from the branch's making (`branching`). */
243
+ export let unborn = (driver: Driver, eids: string[]): void => {
244
+ if (!eids.length) return
245
+ driver.query({
246
+ t: 'update',
247
+ table: 'entity',
248
+ set: {
249
+ archetype: sub(select({
250
+ cols: [col('id')],
251
+ from: table('entity'),
252
+ where: eq(col('eid'), val(eidOf([]))),
253
+ })),
254
+ },
255
+ where: and(oneOf(col('eid'), eids), isNull(col('archetype'))),
256
+ })
257
+ }