@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/population.ts ADDED
@@ -0,0 +1,630 @@
1
+ // Exact entity populations by archetype. One migration reads existing owners;
2
+ // afterwards entity triggers move only the old and new buckets, in the same
3
+ // transaction as the entity. Ordinary component property writes do no work.
4
+ import { type And, bare, type Clause, parse } from '@yaks/query/core'
5
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
6
+ import { type Filter, filter } from '@yaks/match'
7
+ import {
8
+ and,
9
+ as,
10
+ type BindOpts,
11
+ call,
12
+ catalogue,
13
+ type Census,
14
+ col,
15
+ count,
16
+ type CreateTable,
17
+ type CreateTrigger,
18
+ type Delete,
19
+ derivedOf,
20
+ type Driver,
21
+ entryIs,
22
+ eq,
23
+ exists,
24
+ type Expr,
25
+ fn,
26
+ gt,
27
+ type Insert,
28
+ isNull,
29
+ le,
30
+ lit,
31
+ not,
32
+ notNull,
33
+ op,
34
+ revision,
35
+ select,
36
+ type Source,
37
+ type Stmt,
38
+ table,
39
+ } from '@yaks/sql'
40
+ import { descriptor } from './catalog.js'
41
+
42
+ export const POPULATION = '_yaks_population'
43
+ // In every store's print (./plan.ts): raised when the parts that keep the
44
+ // counts change, so each store installs once and mends them ({@link torn}).
45
+ export const POPULATION_VERSION = 2
46
+ const MEMBERSHIP = '_yaks_membership'
47
+
48
+ let increment = (which: 'new' | 'old', n: number): Stmt => ({
49
+ t: 'insert',
50
+ into: POPULATION,
51
+ cols: ['archetype', 'n'],
52
+ q: select({
53
+ cols: [col('archetype', which), lit(n)],
54
+ where: and(
55
+ notNull(col('archetype', which)),
56
+ not(exists(select({
57
+ cols: [lit(1)],
58
+ from: table('tombstone'),
59
+ where: eq(col('entity'), col('id', which)),
60
+ }))),
61
+ ),
62
+ }),
63
+ upsert: [{ on: [col('archetype')], set: { n: op('+', col('n'), lit(n)) } }],
64
+ })
65
+
66
+ /** The triggers on the spine that keep each archetype's count: one more for
67
+ * an entity born or moved into it, one fewer for one dropped or moved out. */
68
+ export let tallying: CreateTrigger[] = (['insert', 'delete', 'update'] as const)
69
+ .map((event) => ({
70
+ t: 'create trigger',
71
+ name: `${POPULATION}_${event}`,
72
+ timing: 'after',
73
+ event,
74
+ on: 'entity',
75
+ ...event == 'update'
76
+ ? {
77
+ of: ['archetype'],
78
+ when: op('is not', col('archetype', 'old'), col('archetype', 'new')),
79
+ }
80
+ : {},
81
+ body: [
82
+ ...event != 'insert' ? [increment('old', -1)] : [],
83
+ ...event != 'delete' ? [increment('new', 1)] : [],
84
+ ] as Extract<Stmt, { t: 'insert' }>[],
85
+ }))
86
+
87
+ // Which component tables each populated archetype holds: an archetype's
88
+ // rows stand while a live entity wears it, and go when its last one leaves.
89
+ // An archetype is never forgotten, so a store whose entities gain and lose
90
+ // components keeps every set they ever wore: the directory held 674 for its
91
+ // 404 apps, and a count of apps read each of them and its empty population
92
+ // (T-4230). A count reads only the archetypes worn now.
93
+ //
94
+ // Archetype `id`'s rows, one for each of the tables a descriptor names,
95
+ // read from `from`.
96
+ let enter = (
97
+ id: Expr,
98
+ tables: Expr,
99
+ where: Expr,
100
+ ...from: Source[]
101
+ ): Insert => {
102
+ let [first, ...rest] = [...from, call('json_each', [tables], 'j')]
103
+ return {
104
+ t: 'insert',
105
+ or: 'ignore',
106
+ into: MEMBERSHIP,
107
+ cols: ['component', 'archetype'],
108
+ q: select({
109
+ cols: [col('value', 'j'), id],
110
+ from: first,
111
+ joins: rest.map((src) => ({ how: 'cross' as const, src })),
112
+ where,
113
+ }),
114
+ }
115
+ }
116
+ let leave = (id: Expr): Delete => ({
117
+ t: 'delete',
118
+ from: MEMBERSHIP,
119
+ where: eq(col('archetype'), id),
120
+ })
121
+ // The rows of the archetype a population row counts, from its descriptor.
122
+ let wearing = (id: Expr) =>
123
+ enter(
124
+ id,
125
+ col('tables', 'a'),
126
+ eq(col('entity', 'a'), id),
127
+ table('archetype', 'a'),
128
+ )
129
+ let membership: CreateTrigger[] = [
130
+ // A descriptor written after the first entity to wear it.
131
+ {
132
+ t: 'create trigger',
133
+ name: `${MEMBERSHIP}_described`,
134
+ timing: 'after',
135
+ event: 'insert',
136
+ on: 'archetype',
137
+ body: [enter(
138
+ col('entity', 'new'),
139
+ col('tables', 'new'),
140
+ exists(select({
141
+ cols: [lit(1)],
142
+ from: table(POPULATION),
143
+ where: and(
144
+ eq(col('archetype'), col('entity', 'new')),
145
+ gt(col('n'), lit(0)),
146
+ ),
147
+ })),
148
+ )],
149
+ },
150
+ {
151
+ t: 'create trigger',
152
+ name: `${MEMBERSHIP}_undescribed`,
153
+ timing: 'after',
154
+ event: 'delete',
155
+ on: 'archetype',
156
+ body: [leave(col('entity', 'old'))],
157
+ },
158
+ {
159
+ t: 'create trigger',
160
+ name: `${MEMBERSHIP}_worn`,
161
+ timing: 'after',
162
+ event: 'insert',
163
+ on: POPULATION,
164
+ when: gt(col('n', 'new'), lit(0)),
165
+ body: [wearing(col('archetype', 'new'))],
166
+ },
167
+ {
168
+ t: 'create trigger',
169
+ name: `${MEMBERSHIP}_reworn`,
170
+ timing: 'after',
171
+ event: 'update',
172
+ of: ['n'],
173
+ on: POPULATION,
174
+ when: and(le(col('n', 'old'), lit(0)), gt(col('n', 'new'), lit(0))),
175
+ body: [wearing(col('archetype', 'new'))],
176
+ },
177
+ {
178
+ t: 'create trigger',
179
+ name: `${MEMBERSHIP}_shed`,
180
+ timing: 'after',
181
+ event: 'update',
182
+ of: ['n'],
183
+ on: POPULATION,
184
+ when: and(gt(col('n', 'old'), lit(0)), le(col('n', 'new'), lit(0))),
185
+ body: [leave(col('archetype', 'new'))],
186
+ },
187
+ ]
188
+ // What membership was before it followed populations: every archetype ever
189
+ // described, kept by these two.
190
+ let LEGACY = [`${MEMBERSHIP}_insert`, `${MEMBERSHIP}_delete`]
191
+
192
+ // Graves can be written before classification (or by SQL extensions).
193
+ // Their physical presence, not the eventual descriptor, decides liveness.
194
+ let burying: CreateTrigger[] = (['insert', 'delete'] as const).map((event) => {
195
+ let which = event == 'insert' ? 'new' : 'old'
196
+ return {
197
+ t: 'create trigger',
198
+ name: `${POPULATION}_grave_${event}`,
199
+ timing: 'after',
200
+ event,
201
+ on: 'tombstone',
202
+ body: [{
203
+ t: 'insert',
204
+ into: POPULATION,
205
+ cols: ['archetype', 'n'],
206
+ q: select({
207
+ cols: [col('archetype'), lit(event == 'insert' ? -1 : 1)],
208
+ from: table('entity'),
209
+ where: and(
210
+ eq(col('id'), col('entity', which)),
211
+ notNull(col('archetype')),
212
+ ),
213
+ }),
214
+ upsert: [{
215
+ on: [col('archetype')],
216
+ set: { n: op('+', col('n'), lit(event == 'insert' ? -1 : 1)) },
217
+ }],
218
+ }],
219
+ }
220
+ })
221
+
222
+ let COUNTS: CreateTable = {
223
+ t: 'create table',
224
+ name: POPULATION,
225
+ cols: [{ name: 'archetype', type: 'integer', pk: true }, {
226
+ name: 'n',
227
+ type: 'integer',
228
+ notNull: true,
229
+ }],
230
+ }
231
+ let MEMBERS: CreateTable = {
232
+ t: 'create table',
233
+ name: MEMBERSHIP,
234
+ cols: [{ name: 'component', type: 'text' }, {
235
+ name: 'archetype',
236
+ type: 'integer',
237
+ }],
238
+ keys: [{ pk: ['component', 'archetype'] }],
239
+ }
240
+ // An archetype's rows, found by the archetype: what leaving one deletes. The
241
+ // key leads with the component, so without it every archetype that shed its
242
+ // last entity read the whole membership, 4,262 rows in the directory
243
+ // (T-5716).
244
+ let BY_ARCHETYPE: Stmt = {
245
+ t: 'create index',
246
+ name: `${MEMBERSHIP}_archetype`,
247
+ on: MEMBERSHIP,
248
+ cols: [col('archetype')],
249
+ }
250
+
251
+ // Everything the counts are made of. Each trigger moves them with the rows,
252
+ // and the counts are only true while every one stands: a table made again
253
+ // drops the triggers on it (./ddl.ts `refit`), and a spine respun before
254
+ // T-164366 dropped `tallying`, so the platform's directory went on counting
255
+ // each deploy deleted and none created. The membership is made again from
256
+ // the counts alone, without reading an entity.
257
+ let COUNTING: Stmt[] = [COUNTS, ...tallying, ...burying]
258
+ let MEMBERSHIPS: Stmt[] = [MEMBERS, BY_ARCHETYPE, ...membership]
259
+ let PARTS = [...COUNTING, ...MEMBERSHIPS]
260
+
261
+ /** Whether the file keeps counts, and every trigger that keeps them true:
262
+ * what an answer read from them asks. It reads the file's whole schema, once
263
+ * per schema revision (@yaks/sql `catalogue`). */
264
+ export let installed = (driver: Driver): boolean => standing(driver, PARTS)
265
+ let standing = (driver: Driver, parts: Stmt[]) => {
266
+ let held = new Set(catalogue(driver).map((o) => o.name))
267
+ return parts.every((s) => held.has((s as { name: string }).name))
268
+ }
269
+
270
+ // Whether the file keeps counts at all, one look at their table, once while
271
+ // the schema stands: what a plan is sized by asks. A count gone stale sizes a
272
+ // plan badly and answers nothing, and the next answer read from the counts
273
+ // seeds them anew ({@link population}).
274
+ let looked = new WeakMap<object, { at: number; kept: boolean }>()
275
+ let kept = (driver: Driver): boolean => {
276
+ let at = revision(driver, 'schema'), on = driver.connection ?? driver
277
+ let held = looked.get(on)
278
+ if (held?.at !== at) {
279
+ let rows = driver.query({
280
+ t: 'pragma',
281
+ name: 'table_info',
282
+ arg: POPULATION,
283
+ })
284
+ looked.set(on, held = { at, kept: rows.length > 0 })
285
+ }
286
+ return held.kept
287
+ }
288
+
289
+ // Drop `parts`, and the names before them: the triggers first, since a
290
+ // table dropped takes the triggers on it along.
291
+ let clear = (driver: Driver, parts: Stmt[], legacy: string[] = []) => {
292
+ let named = (s: Stmt) => (s as { name: string }).name
293
+ let triggers = parts.filter((s) => s.t == 'create trigger').map(named)
294
+ let tables = parts.filter((s) => s.t == 'create table').map(named)
295
+ for (let name of [...legacy, ...triggers]) {
296
+ driver.query({ t: 'drop', kind: 'trigger', name, ifExists: true })
297
+ }
298
+ for (let name of tables) {
299
+ driver.query({ t: 'drop', kind: 'table', name, ifExists: true })
300
+ }
301
+ }
302
+
303
+ /** Install once, after the entity schema and its archetype backfill stand.
304
+ * Seeding and the triggers commit together; another opener sees both or none.
305
+ * Counts missing any part are not trusted: what is left of them goes, and they
306
+ * are seeded anew from the rows. A membership missing a part is made again
307
+ * from the counts that stand. */
308
+ export let population = (driver: Driver): void => {
309
+ if (installed(driver)) return
310
+ if (!standing(driver, COUNTING)) {
311
+ clear(driver, PARTS, LEGACY)
312
+ driver.query(COUNTS)
313
+ driver.query({
314
+ t: 'insert',
315
+ into: POPULATION,
316
+ cols: ['archetype', 'n'],
317
+ q: select({
318
+ cols: [col('archetype'), count()],
319
+ from: table('entity'),
320
+ where: and(
321
+ notNull(col('archetype')),
322
+ not(
323
+ exists(
324
+ select({
325
+ cols: [lit(1)],
326
+ from: table('tombstone'),
327
+ where: eq(col('entity'), col('id', 'entity')),
328
+ }),
329
+ ),
330
+ ),
331
+ ),
332
+ group: [col('archetype')],
333
+ }),
334
+ })
335
+ for (let t of [...tallying, ...burying]) driver.query(t)
336
+ }
337
+ clear(driver, MEMBERSHIPS, LEGACY)
338
+ driver.query(MEMBERS)
339
+ driver.query(
340
+ enter(
341
+ col('archetype', 'p'),
342
+ col('tables', 'a'),
343
+ and(
344
+ gt(col('n', 'p'), lit(0)),
345
+ eq(col('entity', 'a'), col('archetype', 'p')),
346
+ ),
347
+ table(POPULATION, 'p'),
348
+ table('archetype', 'a'),
349
+ ),
350
+ )
351
+ for (let t of [BY_ARCHETYPE, ...membership]) driver.query(t)
352
+ }
353
+
354
+ /** Whether counts stand but a part that keeps them true does not, such as an
355
+ * index or trigger added since: mended by install ({@link population}) rather
356
+ * than by the first count asked, which a lazy store may never ask while its
357
+ * every write runs what stands. Counts that do not stand are left to that
358
+ * first count, which seeds them. */
359
+ export let torn = (driver: Driver): boolean =>
360
+ !installed(driver) && standing(driver, COUNTING)
361
+
362
+ export type Population = { value: string; n: number; tables: string[] }
363
+ /** Read buckets, never their owners. Tombstone sets are excluded exactly as
364
+ * ordinary entity reads exclude graves. Unknown/old files decline the fast path. */
365
+ export let populations = (driver: Driver): Population[] | undefined => {
366
+ if (!installed(driver)) return
367
+ return driver.query(select({
368
+ cols: [as(col('eid', 'e'), 'value'), col('n', 'p'), col('tables', 'a')],
369
+ from: table(POPULATION, 'p'),
370
+ // Population drives the join even when an eid ordering could tempt the
371
+ // planner into scanning owners through entity's eid index.
372
+ joins: [
373
+ { how: 'cross', src: table('entity', 'e') },
374
+ { how: 'cross', src: table('archetype', 'a') },
375
+ ],
376
+ where: and(
377
+ gt(col('n', 'p'), lit(0)),
378
+ eq(col('id', 'e'), col('archetype', 'p')),
379
+ eq(col('entity', 'a'), col('archetype', 'p')),
380
+ ),
381
+ order: [col('eid', 'e')],
382
+ })).map((r) => ({
383
+ value: String(r.value),
384
+ n: Number(r.n),
385
+ tables: [...descriptor(driver, String(r.tables)).tables],
386
+ }))
387
+ }
388
+
389
+ /** A pending raw patch may not have been classified yet. Then component
390
+ * counts must read physical rows rather than an intermediate population. */
391
+ export let classified = (driver: Driver): boolean =>
392
+ !driver.query(
393
+ select({
394
+ cols: [lit(1)],
395
+ from: table('entity'),
396
+ where: isNull(col('archetype')),
397
+ limit: lit(1),
398
+ }),
399
+ ).length
400
+
401
+ /** A component's buckets are sought through a descriptor membership index;
402
+ * unrelated descriptor diversity never adds work to a plain count. */
403
+ export let populationCount = (
404
+ driver: Driver,
405
+ component?: string,
406
+ kept?: Presence,
407
+ ): number | undefined =>
408
+ installed(driver) ? counting(driver, component, kept) : undefined
409
+ let counting = (
410
+ driver: Driver,
411
+ component?: string,
412
+ kept?: Presence,
413
+ ): number => {
414
+ let p = table(POPULATION, 'p')
415
+ let member = (name: string) =>
416
+ entryIs(col('component', 'm'), driver.stored?.v, name)
417
+ let bucket = eq(col('archetype', 'p'), col('archetype', 'm'))
418
+ let wearing = (name: string) =>
419
+ exists(select({
420
+ cols: [lit(1)],
421
+ from: table(MEMBERSHIP, 'm'),
422
+ where: and(member(name), bucket),
423
+ }))
424
+ let by = component && component != 'entity' ? component : undefined
425
+ let row = driver.query(
426
+ select({
427
+ cols: [as(fn('coalesce', fn('sum', col('n', 'p')), lit(0)), 'n')],
428
+ from: by ? table(MEMBERSHIP, 'm') : p,
429
+ joins: by ? [{ how: 'cross' as const, src: p }] : [],
430
+ where: and(
431
+ ...by ? [member(by), bucket] : [],
432
+ ...(kept?.all ?? []).filter((c) => c != by).map(wearing),
433
+ ...(kept?.none ?? []).map((c) => not(wearing(c))),
434
+ ),
435
+ }),
436
+ )[0]
437
+ return Number(row?.n ?? 0)
438
+ }
439
+
440
+ // What the census has read, while the rows it read stand (@yaks/sql
441
+ // `revision`): the reads of one summary share a revision, and ask once.
442
+ type Counted = {
443
+ at: number
444
+ held: Map<string, number | undefined>
445
+ looked: Map<string, boolean>
446
+ numbered: Map<string, boolean>
447
+ largest?: number
448
+ }
449
+ let counts = new WeakMap<Driver, Counted>()
450
+ let counted = (driver: Driver): Counted => {
451
+ let at = revision(driver, 'data')
452
+ let held = counts.get(driver)
453
+ if (held?.at != at) {
454
+ counts.set(
455
+ driver,
456
+ held = { at, held: new Map(), looked: new Map(), numbered: new Map() },
457
+ )
458
+ }
459
+ return held
460
+ }
461
+
462
+ // Whether any live entity holding `comp` has a number: a seek of the number
463
+ // index (`entity(archetype, num)`) for each archetype a live entity wears that
464
+ // holds it, and one for the entities no archetype describes yet, which may
465
+ // hold it too.
466
+ let numbering = (driver: Driver, comp: string): boolean =>
467
+ driver.query(select({
468
+ cols: [lit(1)],
469
+ from: table(MEMBERSHIP, 'm'),
470
+ joins: [{ how: 'cross', src: table('entity', 'e') }],
471
+ where: and(
472
+ entryIs(col('component', 'm'), driver.stored?.v, comp),
473
+ eq(col('archetype', 'e'), col('archetype', 'm')),
474
+ notNull(col('num', 'e')),
475
+ ),
476
+ limit: lit(1),
477
+ })).length > 0 ||
478
+ driver.query(select({
479
+ cols: [lit(1)],
480
+ from: table('entity'),
481
+ where: and(isNull(col('archetype')), notNull(col('num'))),
482
+ limit: lit(1),
483
+ })).length > 0
484
+
485
+ /** What a read's plans are sized by (@yaks/sql `Census`): a component's
486
+ * counted population, once the file keeps populations, the entity table's
487
+ * largest id, one seek, whether a component's table holds more than so
488
+ * many rows, a bounded look, and whether any entity holding a component has
489
+ * a number, a seek per archetype holding it. Each is read only when a plan
490
+ * asks, and once while the rows it read stand. */
491
+ export let census = (driver: Driver): Census => ({
492
+ held: (comp) => {
493
+ let at = counted(driver)
494
+ if (!kept(driver)) return
495
+ if (!at.held.has(comp)) at.held.set(comp, counting(driver, comp))
496
+ return at.held.get(comp)
497
+ },
498
+ largest: () =>
499
+ counted(driver).largest ??= Number(
500
+ driver.query(select({
501
+ cols: [as(fn('max', col('id')), 'n')],
502
+ from: table('entity'),
503
+ }))[0]?.n ?? 0,
504
+ ),
505
+ exceeds: (comp, n) => {
506
+ let { looked } = counted(driver), key = `${n} ${comp}`
507
+ let more = looked.get(key)
508
+ if (more == null) {
509
+ more = driver.query(select({
510
+ cols: [lit(1)],
511
+ from: table(comp),
512
+ limit: lit(1),
513
+ offset: lit(n),
514
+ })).length > 0
515
+ looked.set(key, more)
516
+ }
517
+ return more
518
+ },
519
+ numbered: (comp) => {
520
+ let at = counted(driver)
521
+ if (!kept(driver)) return
522
+ if (!at.numbered.has(comp)) at.numbered.set(comp, numbering(driver, comp))
523
+ return at.numbered.get(comp)
524
+ },
525
+ // A count gone stale chooses a road badly and answers nothing.
526
+ counts: () => {
527
+ if (!kept(driver)) return
528
+ return { population: POPULATION, membership: MEMBERSHIP }
529
+ },
530
+ })
531
+
532
+ type Presence = { all: string[]; none: string[] }
533
+
534
+ let presence = (
535
+ vocab: Vocab,
536
+ opts: BindOpts,
537
+ clauses: Clause[],
538
+ ): Presence | undefined => {
539
+ let all: string[] = [], none: string[] = []
540
+ for (let c of clauses) {
541
+ if (
542
+ c.kind != 'pred' || !bare(c) || c.op == '?' || c.where ||
543
+ opts.extend?.some((e) => e.compile[c.kind]) ||
544
+ !vocab.comp(c.path[0]) ||
545
+ vocab.comp(c.path[0])?.computed ||
546
+ derivedOf(vocab, opts.derived)[c.path[0]] || opts.backed?.[c.path[0]]
547
+ ) return
548
+ let present = c.op == '!' && !c.not
549
+ // Every live row already has its entity spine.
550
+ if (c.path[0] == 'entity') {
551
+ if (present) continue
552
+ return
553
+ }
554
+ let into = present ? all : none
555
+ into.push(c.path[0])
556
+ }
557
+ return { all, none }
558
+ }
559
+
560
+ /** A presence-only entity policy selects whole buckets. */
561
+ let visible = (vocab: Vocab, opts: BindOpts) => {
562
+ if (Object.keys(opts.visibility?.components ?? {}).length) return
563
+ let policy = opts.visibility?.entity
564
+ return presence(
565
+ vocab,
566
+ opts,
567
+ typeof policy == 'string' ? parse(policy).clauses : policy?.clauses ?? [],
568
+ )
569
+ }
570
+ // A clause that leaves a count's matches as they are: a declared component or
571
+ // property asked for with `?`, which carries it without filtering, and the
572
+ // row-shaping directives an aggregate ignores. An undeclared name is left to
573
+ // the compiler, which reads or refuses it.
574
+ let idle = (vocab: Vocab, c: And['clauses'][number]): boolean =>
575
+ c.kind == 'order' || c.kind == 'limit' || c.kind == 'after' ||
576
+ c.kind == 'pred' && c.op == '?' && !c.value && !c.not && !c.where &&
577
+ !!vocab.comp(c.path[0]) &&
578
+ (c.path.length == 1 ||
579
+ c.path.length == 2 && !!vocab.prop(c.path[0], c.path[1]))
580
+
581
+ /** Only plain aggregates whose policy selects whole buckets use populations.
582
+ * Shared by lazy activation and reads; value-scoped counts stay on SQL. */
583
+ export let cardinality = (
584
+ parsed: And,
585
+ vocab: Vocab,
586
+ opts: BindOpts = {},
587
+ ): {
588
+ tally: boolean
589
+ comp?: string
590
+ visible: (tables: string[]) => boolean
591
+ presence?: Presence
592
+ archetype?: Filter
593
+ } | undefined => {
594
+ let cs = parsed.clauses
595
+ let accepts = visible(vocab, opts)
596
+ if (
597
+ !vocab.comp('archetype') || !accepts || opts.eids ||
598
+ opts.extend?.some((e) => cs.some((c) => e.compile[c.kind]))
599
+ ) return
600
+ let tally = cs.length == 1 && cs[0].kind == 'tally' &&
601
+ cs[0].path.join('.') == 'entity.archetype'
602
+ let count = cs.some((c) => c.kind == 'count')
603
+ let filters = cs.filter((c) => c.kind != 'count' && !idle(vocab, c))
604
+ let metadata = !opts.backed?.entity &&
605
+ vocab.prop('entity', 'archetype')?.ref == 'archetype' &&
606
+ !vocab.prop('entity', 'archetype')?.computed &&
607
+ !derivedOf(vocab, opts.derived)['entity.archetype'] &&
608
+ !opts.visibility?.entity && filters.length > 0 &&
609
+ filters.every((c) =>
610
+ c.kind == 'pred' && !c.not && !c.where &&
611
+ c.path.join('.') == 'entity.archetype' &&
612
+ (c.op == '!' && !c.value || ['=', '!='].includes(c.op) &&
613
+ (!c.value || c.value.kind == 'scalar' && c.value.raw == ''))
614
+ )
615
+ let parts = presence(vocab, opts, filters)
616
+ if (!(tally || count && (parts || metadata))) return
617
+ let all = [...accepts.all, ...parts?.all ?? []]
618
+ let none = [...accepts.none, ...parts?.none ?? []]
619
+ return {
620
+ tally,
621
+ comp: all[0],
622
+ visible: (tables) =>
623
+ all.every((c) => tables.includes(c)) &&
624
+ none.every((c) => !tables.includes(c)),
625
+ ...parts || tally ? { presence: { all, none } } : {},
626
+ ...metadata
627
+ ? { archetype: filter({ kind: 'and', clauses: filters }, vocab) }
628
+ : {},
629
+ }
630
+ }