@yaks/d1 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.
package/store.ts ADDED
@@ -0,0 +1,713 @@
1
+ import { preserving, type Trash, type TrashPage } from '@yaks/graph/trash'
2
+ import {
3
+ purgeTrashSql,
4
+ retainSql,
5
+ trashRows,
6
+ trashSql,
7
+ trashTargetsSql,
8
+ } from '@yaks/sqlite/trash'
9
+ // The store, bound: @yaks/graph's `Storage` over a D1 binding. Reads and DDL
10
+ // are ordinary; the transaction is where D1's shape has to be faced squarely,
11
+ // so what it does and does not promise is written out here rather than implied.
12
+ //
13
+ // What D1 gives. `batch()` runs a list of statements sequentially inside one
14
+ // implicit transaction and rolls the whole list back if any of them fails.
15
+ // That is a true atomic write. What D1 does not give is an interactive
16
+ // transaction: there is no call that opens a transaction, lets your code read,
17
+ // decide, and write inside it, and commits at the end. Nothing holds a lock
18
+ // while you think.
19
+ //
20
+ // What `tx()` does about it. A transaction here is deferred-write:
21
+ //
22
+ // reads run immediately, against the committed database;
23
+ // writes are gathered as statements, not sent;
24
+ // returning flushes the gathered statements as one `batch()` — atomic;
25
+ // throwing discards them — nothing was ever sent.
26
+ //
27
+ // So the write half is genuinely all-or-nothing, and a rejected batch (a failed
28
+ // `$was` precondition, a hook that rejects it at commit) leaves the database
29
+ // untouched, because it was never written to. The writes can wait like that
30
+ // because they need nothing read first: @yaks/sqlite builds every one as a
31
+ // self-sufficient statement (an owner id is a subquery, never a value looked up
32
+ // first), and this package collects those same statements rather than keeping a
33
+ // write path of its own.
34
+ //
35
+ // Read-your-own-writes, which `apply()` needs — a cascading delete has to find
36
+ // who points at a deleted entity after the batch's own patches — is served from
37
+ // an in-memory overlay rather than from the database: every entity this
38
+ // transaction wrote is held in the state it will have once the batch commits,
39
+ // and a read inside the transaction returns the committed result with those
40
+ // entities replaced by their pending state (evaluated with @yaks/match, the
41
+ // same query grammar the database implements). Untouched entities never go
42
+ // through the overlay, so a transaction that has not written yet reads exactly
43
+ // as the database does.
44
+ //
45
+ // What is not promised, precisely. The reads are not part of the write's
46
+ // transaction, because D1 has nowhere to put them. Between a read and the flush
47
+ // another writer may change what was read: this is read-committed with an
48
+ // atomic write batch, not serializable isolation. A check that must not lose a
49
+ // race — `$was` — is therefore best-effort against a concurrent writer here,
50
+ // where it is exact over @yaks/sqlite. The failure it cannot prevent is a lost
51
+ // update that nothing detects, not a half-written batch; atomicity holds
52
+ // either way.
53
+ //
54
+ // A D1 store numbers nothing: an entity is its eid. A number is given in its
55
+ // series, past the last that series gave, which is a read before the write,
56
+ // and a batch sent at once has no room for one.
57
+ //
58
+ // A nested `tx()` is a separate batch, since D1 has no savepoints. Nothing in
59
+ // `apply()` nests one.
60
+
61
+ import type {
62
+ Bundle,
63
+ Comp,
64
+ Doom,
65
+ Eid,
66
+ Entity,
67
+ Gone,
68
+ Loose,
69
+ Tx,
70
+ } from 'jsr:@yaks/graph@0.2.36'
71
+ import { comps, tombstoned } from '@yaks/graph/bundle'
72
+ import { only } from '@yaks/graph/read'
73
+ import { type Clock, system } from '@yaks/fp'
74
+ import { matcher } from '@yaks/match'
75
+ import {
76
+ and,
77
+ asWritten,
78
+ type BindOpts,
79
+ col,
80
+ cross,
81
+ DEEP,
82
+ doomSql,
83
+ eq,
84
+ faultAsWritten,
85
+ isNull,
86
+ looseSql,
87
+ narrow,
88
+ select,
89
+ type Stmt,
90
+ table,
91
+ tableAsWritten,
92
+ worn,
93
+ } from '@yaks/sql'
94
+ import {
95
+ asked,
96
+ defined,
97
+ fitting,
98
+ grown,
99
+ heard,
100
+ identified,
101
+ indexed,
102
+ layoutOf,
103
+ logged,
104
+ mintSql,
105
+ type Orphan,
106
+ orphaned,
107
+ patchSql,
108
+ pointSql,
109
+ projected,
110
+ pruneSql,
111
+ refit,
112
+ removeSql,
113
+ schema,
114
+ tabled,
115
+ touched,
116
+ unburySql,
117
+ unfit,
118
+ unresolved,
119
+ } from '@yaks/sqlite'
120
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
121
+ import {
122
+ access,
123
+ type D1Like,
124
+ prepare,
125
+ type Prepared,
126
+ type Row,
127
+ unbind,
128
+ } from './d1.js'
129
+ import { writer } from './receipt.js'
130
+ import {
131
+ ast,
132
+ bundles,
133
+ gatherSql,
134
+ type Query,
135
+ sql,
136
+ whole,
137
+ wholeSql,
138
+ } from './read.js'
139
+
140
+ export type { Query }
141
+
142
+ /**
143
+ * A bound store: @yaks/graph's `Storage` over D1, every answer a promise.
144
+ *
145
+ * `tx` is declared as the seam declares it — the seam is async-or-sync and a
146
+ * synchronous adapter returns a plain value — but over D1 it always returns a
147
+ * promise, and it resolves only once the write batch has committed.
148
+ */
149
+ export type Store = {
150
+ /** Destructive transactions retained for recovery. */
151
+ trash: (eids?: Eid[], page?: TrashPage) => Promise<Trash[]>
152
+ /** Purge one retained transaction after a person explicitly chooses it. */
153
+ purgeTrash: (id: string | string[]) => Promise<void>
154
+
155
+ /** Whether a value this store reads for the property means its entity
156
+ * wears the component (@yaks/sql `worn`). */
157
+ worn: (comp: string, prop: string) => boolean
158
+ /** the schema statements the bound vocabulary implies */
159
+ ddl: () => Stmt[]
160
+ /** run them — create the tables, indexes and triggers the vocabulary needs */
161
+ install: () => Promise<void>
162
+ /** a query → its entities, with `comps` only where named */
163
+ read: (query: Query, opts?: BindOpts, comps?: string[]) => Promise<Bundle[]>
164
+ /** a query → the compiled statement's raw rows (counts, tallies) */
165
+ rows: (query: Query, opts?: BindOpts) => Promise<Row[]>
166
+ /** these entities as they stand, carrying the components `comps` names or
167
+ * every one: D1 holds no lock to take */
168
+ get: (eids: Eid[], comps?: string[]) => Promise<Bundle[]>
169
+ /** run `body` against a transaction: flush its writes as one atomic batch on
170
+ * return, discard them on throw */
171
+ tx: <R>(body: (tx: Tx) => R) => Promise<Awaited<R>>
172
+ }
173
+
174
+ // The identity of an eid as the database holds it, or `null` for an eid no
175
+ // entity has. Cached per transaction so one gather serves every lookup.
176
+ type Spine = { num?: number | null; dead: boolean } | null
177
+
178
+ // A patch merged onto the bundle it patches: a null component drops the row,
179
+ // anything else merges in, so an omitted property keeps what it held and a null
180
+ // one clears it. This is the overlay's copy of the same rule ./write.ts states
181
+ // in SQL — it is what a read inside the transaction has to see.
182
+ let merged = (v: Vocab, held: Bundle, b: Bundle): Bundle => {
183
+ let out: Bundle = { ...held }
184
+ for (let [name, comp] of comps(b)) {
185
+ if (comp == null) {
186
+ delete out[name]
187
+ continue
188
+ }
189
+ let kept = Object.entries(comp)
190
+ .filter(([p]) => v.prop(name, p)?.computed === false)
191
+ out[name] = {
192
+ ...(out[name] as Comp | undefined ?? {}),
193
+ ...Object.fromEntries(kept),
194
+ }
195
+ }
196
+ return out
197
+ }
198
+
199
+ /**
200
+ * Bind a store to a D1 binding and a vocabulary — the `Storage` a
201
+ * {@link https://jsr.io/@yaks/graph | @yaks/graph} applies bundles to.
202
+ *
203
+ * `base` options (a derived-property registry, an @yaks/sql extension, a fixed
204
+ * `now` for time phrases) ride every read; a per-call `opts` merges over them.
205
+ *
206
+ * ```ts
207
+ * // let store = storage(env.DB, vocab)
208
+ * // await store.install()
209
+ * // let g = graph({ storage: store, vocab })
210
+ * // await g.apply([{ entity: { eid: 'b1' }, doc: { title: 'Dune' } }])
211
+ * ```
212
+ */
213
+ // The components bearing a reference whose death word means something — a
214
+ // patch touching one of these is a patch the death cascade would have to read,
215
+ // and the database has not seen it yet.
216
+ let deadly = (v: Vocab): Set<string> =>
217
+ new Set(
218
+ (['cascade', 'detach', 'release'] as const)
219
+ .flatMap((word) => v.deaths(word).map(([comp]) => comp)),
220
+ )
221
+
222
+ /** What a D1 store is bound with: @yaks/sql's read options. */
223
+ export type Opts = BindOpts & {
224
+ /** Where a failure the store outlives is told, as @yaks/sqlite's `report`:
225
+ * one line on the console, by default. */
226
+ report?: (error: Error) => void
227
+ /** Time used for D1 recovery and write receipts. */
228
+ clock?: Clock
229
+ }
230
+
231
+ export let storage = <S extends Prepared<S>>(
232
+ db: D1Like<S>,
233
+ vocab: Vocab,
234
+ base: Opts = {},
235
+ ): Store => {
236
+ if (!vocab.comp('archetype')) {
237
+ base = { ...base, bookkeeping: [...base.bookkeeping ?? [], 'archetype'] }
238
+ }
239
+ let bears = deadly(vocab)
240
+ let report = base.report ?? logged
241
+ let clock = base.clock ?? system
242
+ let io = access(db, () => vocab, clock)
243
+ let commit = writer(db, (s) => prepare(db, s, vocab), clock)
244
+
245
+ // One statement, one round trip. A refusal is told under the names the
246
+ // statement wrote (@yaks/sql `faultAsWritten`), as its rows are.
247
+ let one = async (s: Stmt): Promise<Row[]> =>
248
+ asWritten(
249
+ s,
250
+ (await io.all(s).catch(said)).results.map(unbind),
251
+ vocab,
252
+ )
253
+ let said = (e: unknown): never => {
254
+ throw faultAsWritten(e, vocab)
255
+ }
256
+
257
+ // Many reads, still one round trip. Answers come back in statement order.
258
+ let send = async (stmts: readonly Stmt[]): Promise<Row[][]> =>
259
+ stmts.length
260
+ ? (await io.batch(stmts).catch(said)).map((r, i) =>
261
+ asWritten(stmts[i], r.results.map(unbind), vocab)
262
+ )
263
+ : []
264
+ let write = (
265
+ stmts: readonly Stmt[],
266
+ births?: ReadonlyMap<number, string>,
267
+ ) =>
268
+ stmts.length
269
+ ? commit(stmts, births).catch(said)
270
+ : Promise.resolve(undefined)
271
+
272
+ let layout: Promise<void> | undefined
273
+ let ready = () =>
274
+ identified(vocab)
275
+ ? layout ??= one(defined).then((rows) => {
276
+ vocab = layoutOf(vocab, rows.map((r) => String(r.name)))
277
+ }).catch((error) => {
278
+ layout = undefined
279
+ throw error
280
+ })
281
+ : undefined
282
+
283
+ let shapes = (bundles: Bundle[]) =>
284
+ bundles.map((b) => ({
285
+ eid: b.entity.eid,
286
+ tables: comps(b).filter(([n]) => !vocab.comp(n)?.computed).map(([n]) =>
287
+ n
288
+ ),
289
+ }))
290
+ // Explicit installation repair for files written before this adapter kept
291
+ // pointers. Each component is read once; ordinary reads never classify.
292
+ let backfill = async () => {
293
+ let missing = await one(select({
294
+ cols: [col('id'), col('eid')],
295
+ from: table('entity'),
296
+ where: isNull(col('archetype')),
297
+ }))
298
+ if (!missing.length) return
299
+ let owners = new Map(missing.map((r) => [Number(r.id), {
300
+ eid: String(r.eid),
301
+ tables: [] as string[],
302
+ }]))
303
+ let names = [
304
+ 'tombstone',
305
+ ...vocab.comps.filter((n) =>
306
+ n != 'entity' && n != 'tombstone' && !vocab.comp(n)?.computed
307
+ ),
308
+ ]
309
+ let parts = await send(
310
+ names.map((name) =>
311
+ select({
312
+ cols: [col('entity', 'c')],
313
+ from: table(name, 'c'),
314
+ joins: [cross(table('entity', 'e'))],
315
+ where: and(
316
+ eq(col('id', 'e'), col('entity', 'c')),
317
+ isNull(col('archetype', 'e')),
318
+ ),
319
+ })
320
+ ),
321
+ )
322
+ parts.forEach((rows, i) => {
323
+ for (let r of rows) owners.get(Number(r.entity))?.tables.push(names[i])
324
+ })
325
+ await write(pointSql([...owners.values()], vocab))
326
+ }
327
+
328
+ let rows = async (query: Query, opts: BindOpts = {}): Promise<Row[]> => {
329
+ let parsed = ast(query)
330
+ return (await one(sql(vocab, parsed, { ...base, ...opts })))
331
+ .map((r) => projected(vocab, r, parsed))
332
+ }
333
+
334
+ // Every named entity in one batch, whole or carrying the components `names`
335
+ // names: the gather asks each entity's spine and each of those components as
336
+ // separate statements and reads the answers back in the order it asked.
337
+ let gather = async (
338
+ eids: Eid[],
339
+ opts: BindOpts = {},
340
+ names?: string[],
341
+ ): Promise<Bundle[]> =>
342
+ eids.length
343
+ ? bundles(
344
+ vocab,
345
+ eids,
346
+ await send(eids.flatMap((e) => gatherSql(vocab, e, opts, names))),
347
+ names,
348
+ )
349
+ : []
350
+
351
+ let read = async (
352
+ query: Query,
353
+ opts: BindOpts = {},
354
+ comps?: string[],
355
+ ): Promise<Bundle[]> => {
356
+ let hits = await rows(query, opts)
357
+ return gather(
358
+ hits.filter((r) => r.eid != null).map((r) => String(r.eid)),
359
+ { ...base, ...opts },
360
+ comps,
361
+ )
362
+ }
363
+
364
+ // The same answer as `read` in one trip, for a query that names a set: the
365
+ // query and the gather of what it hits go as one batch, each statement
366
+ // naming the hit set as a subquery rather than binding eids a first trip
367
+ // went and found. What @yaks/graph's backwards reads ask for — see
368
+ // ./read.ts `wholeSql` for why it is not what `read` does.
369
+ let seek = async (query: Query, opts: BindOpts = {}): Promise<Bundle[]> => {
370
+ let o = { ...base, ...opts }
371
+ return whole(
372
+ vocab,
373
+ await send(wholeSql(vocab, sql(vocab, query, o), o)),
374
+ )
375
+ }
376
+
377
+ // One transaction: the deferred write log, the read cache, and the overlay of
378
+ // what this transaction has written. See the header for what that buys.
379
+ let open = () => {
380
+ let pending: Stmt[] = []
381
+ let retained = new Set<string>()
382
+ // Entities this transaction wrote, as they will be once the batch lands.
383
+ let dirty = new Map<Eid, Bundle>()
384
+ // Entities it merely read, faithful to the database. Kept apart from the
385
+ // overlay so a read that changed nothing never routes a query through
386
+ // @yaks/match.
387
+ let held = new Map<Eid, Bundle>()
388
+ let pruned = new Set<Eid>()
389
+ let known = new Map<Eid, Spine>()
390
+ // The identities this transaction mints, each paired with the position of
391
+ // its insert in `pending` — that statement's RETURNING is where its number
392
+ // comes from once the batch lands.
393
+ let births: { at: number; entity: Entity }[] = []
394
+ // Whether this transaction has written something the database cannot see
395
+ // that the death cascade would have to read: a patch touching a component
396
+ // whose references declare a death, or a removal. Until it has, the rows
397
+ // the database holds are the rows the batch leaves behind, and the
398
+ // cascade's question is one statement; once it has, that statement would be
399
+ // answering about rows that have moved, so the question is declined and
400
+ // @yaks/graph walks it through the overlay instead.
401
+ let moved = false
402
+
403
+ // Learn about these eids, asking the database only about the ones no
404
+ // question has covered yet.
405
+ let learn = async (eids: Eid[]): Promise<void> => {
406
+ let ask = [...new Set(eids)].filter((e) => !known.has(e))
407
+ if (!ask.length) return
408
+ let found = await gather(ask, base)
409
+ for (let b of found) {
410
+ held.set(b.entity.eid, b)
411
+ known.set(b.entity.eid, {
412
+ num: b.entity.num,
413
+ dead: b.tombstone != null,
414
+ })
415
+ }
416
+ for (let e of ask) if (!known.has(e)) known.set(e, null)
417
+ }
418
+
419
+ let at = (eid: Eid): Bundle | undefined =>
420
+ pruned.has(eid) ? undefined : dirty.get(eid) ?? held.get(eid)
421
+
422
+ let buried = (eid: Eid): boolean => known.get(eid)?.dead == true
423
+
424
+ // Mint an identity for an eid that has none, so a reference may name a
425
+ // target created in the same batch, in any order. `flush` fills in what
426
+ // the statement returns, before the transaction settles and before
427
+ // anything outside can read it.
428
+ let birth = (eid: Eid): Entity | undefined => {
429
+ if (known.get(eid)) return
430
+ let entity: Entity = { eid }
431
+ births.push({ at: pending.length, entity })
432
+ pending.push(mintSql(eid))
433
+ known.set(eid, { dead: false })
434
+ dirty.set(eid, { entity })
435
+ return entity
436
+ }
437
+
438
+ // Send the gathered writes, then read each mint's own RETURNING back out of
439
+ // the batch and fill in the number it handed out.
440
+ let flush = async (): Promise<void> => {
441
+ pending.push(...pointSql(shapes([...dirty.values()]), vocab))
442
+ let out = await write(
443
+ pending,
444
+ new Map(births.map(({ at, entity }) => [at, entity.eid])),
445
+ )
446
+ for (let b of births) {
447
+ let num = out?.get(b.at)
448
+ if (num !== undefined) b.entity.num = num
449
+ }
450
+ }
451
+
452
+ // The committed answer with this transaction's own entities taken out,
453
+ // then those re-judged against the same query in their pending state.
454
+ let overlaid = (query: Query, now: number | undefined, all: Bundle[]) => {
455
+ if (!dirty.size && !pruned.size) return all
456
+ let mine = matcher(query, vocab, { now: now ?? base.now })(
457
+ [...dirty.values()].filter((b) => b.tombstone == null),
458
+ )
459
+ return [
460
+ ...all.filter((b) =>
461
+ !dirty.has(b.entity.eid) && !pruned.has(b.entity.eid)
462
+ ),
463
+ ...mine,
464
+ ]
465
+ }
466
+
467
+ // Who dies with these entities, and what has to let go of them: the
468
+ // recursive closure over the cascade columns and the soft references into
469
+ // it (@yaks/sql), sent as one batch where the walk they replace cost a read
470
+ // per rung and another per frontier. The casualties' identities are kept as
471
+ // they come back, so `remove`, which is the next thing that happens to
472
+ // them, asks nothing more.
473
+ //
474
+ // A vocabulary too wide for one statement (workerd caps a compound SELECT
475
+ // at five terms) is asked in rounds, each still one batch: the arms are cut
476
+ // into statements, so a round is complete only when it turns up nothing the
477
+ // last one had not. The soft references ride every round bound to what was
478
+ // known when it began — which is the whole of the dead exactly when the
479
+ // round proves it, so the last round's answer is the one kept.
480
+ let doom = async (eids: Eid[]): Promise<Doom | null> => {
481
+ if (moved) return null
482
+ let depth = new Map<Eid, number>()
483
+ let gone: Gone[] = []
484
+ let loose: Loose[] = []
485
+ let seed = eids
486
+ let dead = eids
487
+ let base = 0
488
+ for (;;) {
489
+ let dying = doomSql(vocab, seed)
490
+ let letting = looseSql(vocab, dead)
491
+ let out = await send([...dying, ...letting])
492
+ let fresh: Eid[] = []
493
+ let least = DEEP
494
+ for (let rows of out.slice(0, dying.length)) {
495
+ for (let r of rows) {
496
+ let eid = String(r.eid)
497
+ if (depth.has(eid)) continue
498
+ if (!known.has(eid)) {
499
+ known.set(eid, {
500
+ ...(r.num == null ? {} : { num: Number(r.num) }),
501
+ dead: false,
502
+ })
503
+ }
504
+ let rung = base + Number(r.depth)
505
+ depth.set(eid, rung)
506
+ gone.push({ eid, depth: rung })
507
+ fresh.push(eid)
508
+ least = Math.min(least, rung)
509
+ }
510
+ }
511
+ loose = out.slice(dying.length).flatMap((rows) =>
512
+ rows.map((r) => ({
513
+ eid: String(r.eid),
514
+ comp: String(r.comp),
515
+ prop: String(r.prop),
516
+ }))
517
+ )
518
+ if (narrow(vocab) || !fresh.length) break
519
+ seed = fresh
520
+ dead = [...depth.keys()]
521
+ base = least
522
+ }
523
+ return { gone, loose }
524
+ }
525
+
526
+ let tx: Tx = {
527
+ read: async (query, opts, comps) =>
528
+ overlaid(
529
+ query as Query,
530
+ opts?.now,
531
+ await read(query as Query, { ...base, ...opts }, comps),
532
+ ).map(only(comps ? new Set(comps) : null)),
533
+ whole: async (query, opts) =>
534
+ overlaid(
535
+ query as Query,
536
+ opts?.now,
537
+ await seek(query as Query, { ...base, ...opts }),
538
+ ),
539
+ // Whole, whatever was named: the overlay merges a patch onto what was
540
+ // read, so a transaction keeps each entity whole and cuts its answer.
541
+ get: async (eids, names) => {
542
+ await learn(eids)
543
+ let cut = only(names ? new Set(names) : null)
544
+ return eids.flatMap((e) => {
545
+ let b = at(e)
546
+ return b ? [cut(b)] : []
547
+ })
548
+ },
549
+ doom,
550
+ patch: async (bs) => {
551
+ moved ||= bs.some((b) => comps(b).some(([name]) => bears.has(name)))
552
+ await learn(touched(vocab, bs))
553
+ let born: Entity[] = []
554
+ // `touched` puts the bundle's own eid first, then what it points at, so
555
+ // spines land in the same first-touch order every adapter uses.
556
+ for (let b of bs) {
557
+ if (buried(b.entity.eid)) continue
558
+ for (let e of touched(vocab, [b])) {
559
+ let spine = birth(e)
560
+ if (spine) born.push(spine)
561
+ }
562
+ }
563
+ for (let b of bs) {
564
+ let eid = b.entity.eid
565
+ if (buried(eid) || !comps(b).length) continue
566
+ pending.push(...patchSql(vocab, b))
567
+ dirty.set(eid, merged(vocab, at(eid) ?? { entity: { eid } }, b))
568
+ }
569
+ return born
570
+ },
571
+ // Its tombstone row goes, so the cascade's one-statement question no
572
+ // longer describes the batch; the identity it kept stays (@yaks/sqlite
573
+ // `revive`).
574
+ revive: async (eids) => {
575
+ await learn(eids)
576
+ for (let eid of eids) {
577
+ let k = known.get(eid)
578
+ if (!k?.dead) continue
579
+ moved = true
580
+ pending.push(unburySql(eid))
581
+ known.set(eid, { ...k, dead: false })
582
+ dirty.set(eid, {
583
+ entity: at(eid)?.entity ??
584
+ { eid, ...(k.num == null ? {} : { num: k.num }) },
585
+ })
586
+ }
587
+ },
588
+ remove: async (entities) => {
589
+ // A tombstoned row is a row the database has not seen go, so nothing
590
+ // after this may ask it who dies.
591
+ moved = true
592
+ // The cascade names casualties this transaction never read — an entity
593
+ // that existed only because something else did. Learn the ones nothing
594
+ // has identified yet, so the overlay knows their identity and a later
595
+ // read sees them as dead; `doom` has usually named them already.
596
+ await learn(entities.map((e) => e.eid))
597
+ let now = new Date().toISOString()
598
+ let found: Entity[] = []
599
+ for (let e of entities) {
600
+ let spine = known.get(e.eid)
601
+ if (!spine) continue
602
+ found.push(e)
603
+ known.set(e.eid, { ...spine, dead: true })
604
+ // Its identity as this transaction knows it: the bundle when one was
605
+ // read, else the spine `doom` or `learn` named — a tombstone still
606
+ // carries the number the entity was given.
607
+ let entity = at(e.eid)?.entity ??
608
+ { eid: e.eid, ...(spine.num == null ? {} : { num: spine.num }) }
609
+ dirty.set(e.eid, tombstoned(entity))
610
+ }
611
+ pending.push(...removeSql([...vocab.all], found, now))
612
+ },
613
+ prune: async (eids) => {
614
+ if (!eids.length) return
615
+ let saved = await one(trashTargetsSql(eids))
616
+ for (let row of saved) retained.add(String(row.eid))
617
+ eids = eids.filter((eid) => !retained.has(eid))
618
+ if (!eids.length) return
619
+ moved = true
620
+ pending.push(
621
+ ...pointSql(
622
+ shapes(eids.flatMap((eid) => dirty.get(eid) ?? [])),
623
+ vocab,
624
+ ),
625
+ )
626
+ pending.push(...pruneSql(vocab, eids))
627
+ for (let eid of eids) {
628
+ pruned.add(eid)
629
+ known.set(eid, null)
630
+ dirty.delete(eid)
631
+ held.delete(eid)
632
+ }
633
+ },
634
+ }
635
+
636
+ return {
637
+ tx: preserving(tx, vocab, (id, at, rows) => {
638
+ for (let row of rows) retained.add(row.entity.eid)
639
+ pending.push(...retainSql(id, at, rows))
640
+ }),
641
+ flush,
642
+ }
643
+ }
644
+
645
+ let run = async <R>(body: (tx: Tx) => R): Promise<Awaited<R>> => {
646
+ await ready()
647
+ let { tx, flush } = open()
648
+ let out = await body(tx)
649
+ await flush()
650
+ return out
651
+ }
652
+
653
+ return {
654
+ worn: worn(vocab, base.derived),
655
+ ddl: () => schema(vocab),
656
+ install: async () => {
657
+ // What stood before, which only a table that did can be behind its
658
+ // vocabulary in (@yaks/sqlite `fit`): the tables, then what each holds.
659
+ await ready()
660
+ let defs = (await one(defined)).map((d) => ({
661
+ ...d,
662
+ name: tableAsWritten(vocab, String(d.name)),
663
+ }))
664
+ let names = defs.map((d) => d.name).filter(fitting(vocab))
665
+ let before = heard(defs, names, await send(asked(names)))
666
+ await write([...tabled(vocab), ...grown(vocab, before)])
667
+ // A rebuild to a batch, which is D1's only transaction: a table whose
668
+ // rows the new shape refuses stays as it stood, and is told.
669
+ let missing = Object.fromEntries(
670
+ await Promise.all(
671
+ Object.entries(unresolved(vocab, before)).map(
672
+ async ([comp, checks]) => [
673
+ comp,
674
+ (await Promise.all(checks.map(one))).map((rows) => rows[0])
675
+ .find(Boolean),
676
+ ],
677
+ ),
678
+ ),
679
+ )
680
+ for (let [comp, stmts] of Object.entries(refit(vocab, before))) {
681
+ let orphan = missing[comp]
682
+ if (orphan) {
683
+ report(orphaned(comp, orphan as Orphan))
684
+ continue
685
+ }
686
+ await write(stmts).catch((e) => report(unfit(comp, e)))
687
+ }
688
+ // The indexes last: one may stand on a table just rebuilt.
689
+ await write(indexed(vocab, true))
690
+ await backfill()
691
+ },
692
+ read: async (...args) => {
693
+ await ready()
694
+ return read(...args)
695
+ },
696
+ rows: async (...args) => {
697
+ await ready()
698
+ return rows(...args)
699
+ },
700
+ get: async (eids, names) => {
701
+ await ready()
702
+ return gather(eids, base, names)
703
+ },
704
+ purgeTrash: async (id) => {
705
+ await write([purgeTrashSql(id)])
706
+ },
707
+ trash: async (eids, page) =>
708
+ eids?.length === 0
709
+ ? []
710
+ : trashRows(vocab, await one(trashSql(eids, page))),
711
+ tx: run,
712
+ }
713
+ }