@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.
@@ -0,0 +1,42 @@
1
+ import { type Clock } from "@yaks/fp";
2
+ import { type D1Like, type Prepared } from "./d1.js";
3
+ /** What a vault keeps for one secret — @yaks/secrets' `Sealed`, by shape. */ export type Sealed = {
4
+ name?: string;
5
+ handle: string;
6
+ value?: string;
7
+ op?: string;
8
+ };
9
+ /** Metadata of a retained version, without its credential value. */ export type Trashed = {
10
+ id: string;
11
+ eid: string;
12
+ handle: string;
13
+ name?: string;
14
+ at: number;
15
+ };
16
+ /** A vault in D1, answering with promises. */ export type D1Vault = {
17
+ salt: () => Promise<Uint8Array>;
18
+ read: (eid: string) => Promise<Sealed | undefined>;
19
+ readMany: (eids: readonly string[]) => Promise<Map<string, PromiseSettledResult<Sealed>>>;
20
+ seal: (eid: string, sealed: Sealed) => Promise<void>;
21
+ drop: (eid: string) => Promise<void>;
22
+ trash: () => Promise<Trashed[]>;
23
+ past: (id: string) => Promise<Sealed | undefined>;
24
+ restore: (id: string) => Promise<boolean>;
25
+ purge: (id: string) => Promise<void>;
26
+ /** Permanently erase the active secrets and all saved versions of these eids. */ erase: (eids: string[]) => Promise<void>;
27
+ all: () => Promise<[string, Sealed][]>;
28
+ lock: <T>(eid: string, fn: () => Promise<T>) => Promise<T>;
29
+ };
30
+ /**
31
+ * The vault in a D1 database, every value encrypted under `key` (AES-GCM),
32
+ * which may still be on its way — a key imported from a Worker secret is. Its
33
+ * tables are created on first use.
34
+ *
35
+ * ```ts
36
+ * import { d1Vault } from '@yaks/d1'
37
+ *
38
+ * // let vault = d1Vault(env.DB, key)
39
+ * // graph({ storage, vocab, plugins: [secrets(vault, write, vocab)] }) // @yaks/secrets
40
+ * ```
41
+ */ export declare let d1Vault: <S extends Prepared<S>>(db: D1Like<S>, key: CryptoKey | Promise<CryptoKey>, clock?: Clock) => D1Vault;
42
+ //# sourceMappingURL=vault.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vault.d.ts","sources":["../vault.ts"],"names":[],"mappings":"AAuCA,SAAS,KAAK,KAAK,wBAAmD;AACtE,SAAiB,KAAK,MAAM,EAAE,KAAK,QAAQ,kBAAiB;AAG5D,2EAA2E,GAC3E,YAAY;EACV,OAAO,MAAM;EACb,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd,KAAK,MAAM;;AAGb,kEAAkE,GAClE,YAAY;EACV,IAAI,MAAM;EACV,KAAK,MAAM;EACX,QAAQ,MAAM;EACd,OAAO,MAAM;EACb,IAAI,MAAM;;AAGZ,4CAA4C,GAC5C,YAAY;EACV,YAAY,QAAQ;EACpB,OAAO,KAAK,MAAM,KAAK,QAAQ,SAAS,SAAS;EACjD,WACE,eAAe,MAAM,OAClB,QAAQ,IAAI,MAAM,EAAE,qBAAqB;EAC9C,OAAO,KAAK,MAAM,EAAE,QAAQ,WAAW,QAAQ,IAAI;EACnD,OAAO,KAAK,MAAM,KAAK,QAAQ,IAAI;EACnC,aAAa,QAAQ;EACrB,OAAO,IAAI,MAAM,KAAK,QAAQ,SAAS,SAAS;EAChD,UAAU,IAAI,MAAM,KAAK,QAAQ,OAAO;EACxC,QAAQ,IAAI,MAAM,KAAK,QAAQ,IAAI;EACnC,+EAA+E,GAC/E,QAAQ,MAAM,MAAM,OAAO,QAAQ,IAAI;EACvC,WAAW,SAAS,MAAM,EAAE;EAC5B,OAAO,GAAG,KAAK,MAAM,EAAE,UAAU,QAAQ,OAAO,QAAQ;;AA0J1D;;;;;;;;;;;CAWC,GACD,OAAO,YAAI,UAAW,UAAU,SAAS,IACvC,IAAI,OAAO,IACX,KAAK,YAAY,QAAQ,YACzB,QAAO,UACN,QAgPF"}
package/d1.js ADDED
@@ -0,0 +1,57 @@
1
+ // Cloudflare D1, reduced to the three calls a store makes — prepare a
2
+ // statement, bind and run it, send a list of statements as one batch — plus the
3
+ // value conversions the engine's own type table demands. Naming just this keeps
4
+ // the adapter free of any Cloudflare dependency at runtime; ./conform.ts is
5
+ // where the claim is checked against the runtime's published types.
6
+ //
7
+ // Two facts about D1 shape everything above this file:
8
+ //
9
+ // It is async. There is no synchronous API. Every read is a round trip, so
10
+ // the adapter collects what it can into one `batch()` rather than issuing one
11
+ // statement at a time.
12
+ //
13
+ // A batch is the only transaction. `begin`, `savepoint` and their friends are
14
+ // not statements you may send; `batch()` runs its list sequentially inside one
15
+ // implicit transaction and rolls the whole list back if any statement fails.
16
+ // There is no interactive transaction — nothing holds a lock open while your
17
+ // code decides what to write next. ./store.ts is built around that.
18
+ import { DEPTH, render, VARIABLES } from "@yaks/sql";
19
+ import { retry } from "./retry.js";
20
+ /**
21
+ * A value as D1 takes it. `undefined` and `null` are the same absence; a bigint
22
+ * becomes a number (D1 refuses one outright); a byte array becomes the
23
+ * ArrayBuffer it is a window onto. A boolean passes through — D1 stores it as
24
+ * 0/1 — so nothing here has to know a column's affinity.
25
+ */ export let bind = (value)=>value == null ? null : typeof value == 'bigint' ? Number(value) : value instanceof Uint8Array ? value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength) : value;
26
+ /**
27
+ * A row as the rest of the stack expects it. D1 hands a BLOB back as an array
28
+ * of byte values; every other adapter hands back bytes, so it is converted here
29
+ * and a caller never learns which database answered.
30
+ */ export let unbind = (row)=>{
31
+ for(let key in row){
32
+ let value = row[key];
33
+ if (Array.isArray(value)) row[key] = Uint8Array.from(value);
34
+ }
35
+ return row;
36
+ };
37
+ /** A @yaks/sql statement prepared on D1: rendered, and every value put through
38
+ * {@link bind}, so a statement may carry the plain SQLite values @yaks/sqlite's
39
+ * shared write path uses (a bigint, a byte array) and D1's narrower set is
40
+ * satisfied in exactly one place. */ export let prepare = (db, s, vocab)=>{
41
+ let r = render(s, VARIABLES, DEPTH, vocab);
42
+ return db.prepare(r.sql).bind(...r.params.map(bind));
43
+ };
44
+ /** Send replayable statements, with identical bindings on every attempt. */ export let access = (db, vocab, clock)=>{
45
+ let prep = (s)=>prepare(db, s, vocab?.());
46
+ return {
47
+ all: (s, until)=>{
48
+ let stmt = prep(s);
49
+ return retry(()=>stmt.all(), until, clock);
50
+ },
51
+ batch: (stmts, until)=>{
52
+ let bound = stmts.map(prep);
53
+ return retry(()=>db.batch(bound), until, clock);
54
+ }
55
+ };
56
+ };
57
+ //# sourceMappingURL=d1.js.map
package/d1.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"d1.js","sources":["./d1.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,gFAAgF;AAChF,gFAAgF;AAChF,4EAA4E;AAC5E,oEAAoE;AACpE,EAAE;AACF,uDAAuD;AACvD,EAAE;AACF,6EAA6E;AAC7E,gFAAgF;AAChF,yBAAyB;AACzB,EAAE;AACF,gFAAgF;AAChF,iFAAiF;AACjF,+EAA+E;AAC/E,+EAA+E;AAC/E,sEAAsE;AAItE,SAAS,KAAK,EAAE,MAAM,EAAa,SAAS,yBAA8B;AAC1E,SAAS,KAAK,qBAAoB;AAiDlC;;;;;CAKC,GACD,OAAO,IAAI,OAAO,CAAC,QACjB,SAAS,OACL,OACA,OAAO,SAAS,WAChB,OAAO,SACP,iBAAiB,aACjB,MAAM,MAAM,CAAC,KAAK,CAClB,MAAM,UAAU,EAChB,MAAM,UAAU,GAAG,MAAM,UAAU,IAEnC,MAAgB;AAEtB;;;;CAIC,GACD,OAAO,IAAI,SAAS,CAAC;EACnB,IAAK,IAAI,OAAO,IAAK;IACnB,IAAI,QAAQ,GAAG,CAAC,IAAI;IACpB,IAAI,MAAM,OAAO,CAAC,QAAQ,GAAG,CAAC,IAAI,GAAG,WAAW,IAAI,CAAC;EACvD;EACA,OAAO;AACT,EAAC;AAED;;;mCAGmC,GACnC,OAAO,IAAI,UAAU,CACnB,IACA,GACA;EAEA,IAAI,IAAI,OAAO,GAAG,WAAW,OAAO;EACpC,OAAO,GAAG,OAAO,CAAC,EAAE,GAAG,EAAE,IAAI,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC;AAChD,EAAC;AAED,0EAA0E,GAC1E,OAAO,IAAI,SAAS,CAClB,IACA,OACA;EAEA,IAAI,OAAO,CAAC,IAAY,QAAQ,IAAI,GAAG;EACvC,OAAO;IACL,KAAK,CAAU,GAAS;MACtB,IAAI,OAAO,KAAK;MAChB,OAAO,MAAM,IAAM,KAAK,GAAG,IAAO,OAAO;IAC3C;IACA,OAAO,CACL,OACA;MAEA,IAAI,QAAQ,MAAM,GAAG,CAAC;MACtB,OAAO,MAAM,IAAM,GAAG,KAAK,CAAC,QAAQ,OAAO;IAC7C;EACF;AACF,EAAC"}
package/d1.ts ADDED
@@ -0,0 +1,135 @@
1
+ // Cloudflare D1, reduced to the three calls a store makes — prepare a
2
+ // statement, bind and run it, send a list of statements as one batch — plus the
3
+ // value conversions the engine's own type table demands. Naming just this keeps
4
+ // the adapter free of any Cloudflare dependency at runtime; ./conform.ts is
5
+ // where the claim is checked against the runtime's published types.
6
+ //
7
+ // Two facts about D1 shape everything above this file:
8
+ //
9
+ // It is async. There is no synchronous API. Every read is a round trip, so
10
+ // the adapter collects what it can into one `batch()` rather than issuing one
11
+ // statement at a time.
12
+ //
13
+ // A batch is the only transaction. `begin`, `savepoint` and their friends are
14
+ // not statements you may send; `batch()` runs its list sequentially inside one
15
+ // implicit transaction and rolls the whole list back if any statement fails.
16
+ // There is no interactive transaction — nothing holds a lock open while your
17
+ // code decides what to write next. ./store.ts is built around that.
18
+
19
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
20
+ import type { Clock } from 'jsr:@yaks/fp@0.2.36'
21
+ import { DEPTH, render, type Stmt, VARIABLES } from '@yaks/sql'
22
+ import { retry } from './retry.js'
23
+
24
+ /** A value D1 binds: its documented type table, and nothing else. A boolean is
25
+ * bound as the 0/1 an integer column holds; bytes are bound as an
26
+ * ArrayBuffer. */
27
+ export type D1Value = ArrayBuffer | string | number | boolean | null
28
+
29
+ /** One row: its column values, keyed by column name. */
30
+ export type Row = Record<string, unknown>
31
+
32
+ /** What a run hands back — the rows it selected. */
33
+ export type D1Result<T> = { results: T[] }
34
+
35
+ /**
36
+ * A prepared statement, generic over the type the binding hands back. The
37
+ * adapter treats one as opaque: it binds values, runs it for rows, or passes it
38
+ * straight back to {@link D1Like.batch}. Keeping the type a parameter is what
39
+ * lets a `D1PreparedStatement` be used as itself rather than narrowed to a
40
+ * slice — a statement appears both as a return and as an argument, and a
41
+ * narrowed slice cannot be both.
42
+ */
43
+ export type Prepared<S> = {
44
+ /** bind positional parameters, returning the bound statement */
45
+ bind: (...values: D1Value[]) => S
46
+ /** run the statement and resolve its result rows */
47
+ all: <T = Row>() => Promise<D1Result<T>>
48
+ }
49
+
50
+ /** The default statement shape, for a caller naming {@link D1Like} without a
51
+ * binding of its own: this package's own slice, closed over itself. */
52
+ export type D1Stmt = {
53
+ /** bind positional parameters, returning the bound statement */
54
+ bind: (...values: D1Value[]) => D1Stmt
55
+ /** run the statement and resolve its result rows */
56
+ all: <T = Row>() => Promise<D1Result<T>>
57
+ }
58
+
59
+ /**
60
+ * The async surface this adapter needs from a `D1Database`: prepare a
61
+ * statement, and send a list of them as one atomic batch. A Cloudflare
62
+ * `D1Database` satisfies it — see ./conform.ts.
63
+ */
64
+ export type D1Like<S extends Prepared<S> = D1Stmt> = {
65
+ /** prepare a parameterized statement for binding and running */
66
+ prepare: (sql: string) => S
67
+ /** run these statements sequentially, as one all-or-nothing transaction */
68
+ batch: (statements: S[]) => Promise<D1Result<Row>[]>
69
+ }
70
+
71
+ /**
72
+ * A value as D1 takes it. `undefined` and `null` are the same absence; a bigint
73
+ * becomes a number (D1 refuses one outright); a byte array becomes the
74
+ * ArrayBuffer it is a window onto. A boolean passes through — D1 stores it as
75
+ * 0/1 — so nothing here has to know a column's affinity.
76
+ */
77
+ export let bind = (value: unknown): D1Value =>
78
+ value == null
79
+ ? null
80
+ : typeof value == 'bigint'
81
+ ? Number(value)
82
+ : value instanceof Uint8Array
83
+ ? value.buffer.slice(
84
+ value.byteOffset,
85
+ value.byteOffset + value.byteLength,
86
+ ) as ArrayBuffer
87
+ : value as D1Value
88
+
89
+ /**
90
+ * A row as the rest of the stack expects it. D1 hands a BLOB back as an array
91
+ * of byte values; every other adapter hands back bytes, so it is converted here
92
+ * and a caller never learns which database answered.
93
+ */
94
+ export let unbind = (row: Row): Row => {
95
+ for (let key in row) {
96
+ let value = row[key]
97
+ if (Array.isArray(value)) row[key] = Uint8Array.from(value as number[])
98
+ }
99
+ return row
100
+ }
101
+
102
+ /** A @yaks/sql statement prepared on D1: rendered, and every value put through
103
+ * {@link bind}, so a statement may carry the plain SQLite values @yaks/sqlite's
104
+ * shared write path uses (a bigint, a byte array) and D1's narrower set is
105
+ * satisfied in exactly one place. */
106
+ export let prepare = <S extends Prepared<S>>(
107
+ db: D1Like<S>,
108
+ s: Stmt,
109
+ vocab?: Vocab,
110
+ ): S => {
111
+ let r = render(s, VARIABLES, DEPTH, vocab)
112
+ return db.prepare(r.sql).bind(...r.params.map(bind))
113
+ }
114
+
115
+ /** Send replayable statements, with identical bindings on every attempt. */
116
+ export let access = <S extends Prepared<S>>(
117
+ db: D1Like<S>,
118
+ vocab?: () => Vocab,
119
+ clock?: Clock,
120
+ ) => {
121
+ let prep = (s: Stmt) => prepare(db, s, vocab?.())
122
+ return {
123
+ all: <T = Row>(s: Stmt, until?: number) => {
124
+ let stmt = prep(s)
125
+ return retry(() => stmt.all<T>(), until, clock)
126
+ },
127
+ batch: (
128
+ stmts: readonly Stmt[],
129
+ until?: number,
130
+ ) => {
131
+ let bound = stmts.map(prep)
132
+ return retry(() => db.batch(bound), until, clock)
133
+ },
134
+ }
135
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts","testing.ts","conform.ts","workers.json"]},"name":"@yaks/d1","version":"0.2.36","license":"Apache-2.0","description":"Adapts Cloudflare D1 to graph storage with asynchronous queries and writes submitted as atomic statement batches.","exports":"./mod.ts","imports":{"@yaks/d1":"./mod.ts"}}
package/mod.js ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @yaks/d1 — the storage adapter that backs a yaks graph with Cloudflare D1.
3
+ *
4
+ * ## What it is
5
+ * D1 is a serverless SQLite reachable only over an async API, so this adapter
6
+ * is async end to end: every read and every write returns a promise. It
7
+ * composes the yaks query → vocabulary → SQL stack over a D1 binding to
8
+ * implement {@link https://jsr.io/@yaks/graph | @yaks/graph}'s `Storage`
9
+ * interface — a query in, whole bundles out; bundles patched into rows.
10
+ *
11
+ * ```ts
12
+ * import { graph } from '@yaks/graph'
13
+ * import { storage } from '@yaks/d1'
14
+ *
15
+ * // let store = storage(env.DB, vocab)
16
+ * // await store.install()
17
+ * // let g = graph({ storage: store, vocab })
18
+ * // await g.apply([{ entity: { eid: 'b1' }, doc: { title: 'Dune' } }])
19
+ * // await g.read('.kind=doc')
20
+ * ```
21
+ *
22
+ * Because `Storage` may be either asynchronous or synchronous, and @yaks/graph
23
+ * handles either (@yaks/fp's `after` awaits a promise and passes a plain value
24
+ * straight through), the same `apply()` is synchronous over @yaks/sqlite and
25
+ * asynchronous here. No caller in between has to know which.
26
+ *
27
+ * ## The transaction, in plain terms
28
+ * D1 has no interactive transaction — no call opens one, lets your code read
29
+ * and decide inside it, and commits at the end. What it has is `batch()`, which
30
+ * runs a list of statements sequentially in one implicit transaction and rolls
31
+ * the whole list back if any fails. So {@link storage}'s `tx` defers: reads run
32
+ * immediately against the committed database, writes are gathered as
33
+ * statements, returning flushes them as one atomic batch, and throwing discards
34
+ * them unsent. Reads inside the transaction see its own pending writes through
35
+ * an in-memory overlay evaluated by
36
+ * {@link https://jsr.io/@yaks/match | @yaks/match}.
37
+ *
38
+ * The write is atomic; the transaction is NOT serializable, because the reads
39
+ * cannot be enrolled in a batch that has not been sent. See the README's
40
+ * "The transaction" for exactly what that costs and when it matters.
41
+ *
42
+ * ## Secrets
43
+ * {@link d1Vault} keeps a graph's secrets in D1, each value encrypted under a
44
+ * key the caller holds. It meets @yaks/secrets' vault by shape, without this
45
+ * package importing it.
46
+ *
47
+ * ## Where it sits
48
+ * One of three interchangeable adapters behind the same seam:
49
+ * **@yaks/d1** (this package, async), {@link
50
+ * https://jsr.io/@yaks/durable-object | @yaks/durable-object} (a Durable
51
+ * Object's embedded SQLite, synchronous) and {@link
52
+ * https://jsr.io/@yaks/sqlite | @yaks/sqlite} (in-process, synchronous — and
53
+ * the reference every adapter is held to).
54
+ *
55
+ * @module
56
+ */ export { bind, unbind } from "./d1.js";
57
+ export { bundles, comps, gatherSql, spineSql, sql } from "./read.js";
58
+ // The write path is @yaks/sqlite's. Every write it builds is a self-sufficient
59
+ // statement — an owner id is a subquery, nothing is read between two writes —
60
+ // which is exactly what a batch that has not been sent yet needs, so this
61
+ // package gathers those statements rather than keeping a second copy of them.
62
+ export { dropSql, mintSql, patchSql, removeSql, touched, upsertSql } from "@yaks/sqlite";
63
+ export { storage } from "./store.js";
64
+ export { d1Vault } from "./vault.js";
65
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GAED,SACE,IAAI,EAOJ,MAAM,kBACQ;AAChB,SAAS,OAAO,EAAE,KAAK,EAAE,SAAS,EAAc,QAAQ,EAAE,GAAG,oBAAmB;AAChF,+EAA+E;AAC/E,8EAA8E;AAC9E,0EAA0E;AAC1E,8EAA8E;AAC9E,SACE,OAAO,EACP,OAAO,EACP,QAAQ,EACR,SAAS,EACT,OAAO,EACP,SAAS,4BACqB;AAChC,SAAS,OAAO,qBAAgC;AAChD,SAAuB,OAAO,qBAAiC"}
package/mod.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @yaks/d1 — the storage adapter that backs a yaks graph with Cloudflare D1.
3
+ *
4
+ * ## What it is
5
+ * D1 is a serverless SQLite reachable only over an async API, so this adapter
6
+ * is async end to end: every read and every write returns a promise. It
7
+ * composes the yaks query → vocabulary → SQL stack over a D1 binding to
8
+ * implement {@link https://jsr.io/@yaks/graph | @yaks/graph}'s `Storage`
9
+ * interface — a query in, whole bundles out; bundles patched into rows.
10
+ *
11
+ * ```ts
12
+ * import { graph } from '@yaks/graph'
13
+ * import { storage } from '@yaks/d1'
14
+ *
15
+ * // let store = storage(env.DB, vocab)
16
+ * // await store.install()
17
+ * // let g = graph({ storage: store, vocab })
18
+ * // await g.apply([{ entity: { eid: 'b1' }, doc: { title: 'Dune' } }])
19
+ * // await g.read('.kind=doc')
20
+ * ```
21
+ *
22
+ * Because `Storage` may be either asynchronous or synchronous, and @yaks/graph
23
+ * handles either (@yaks/fp's `after` awaits a promise and passes a plain value
24
+ * straight through), the same `apply()` is synchronous over @yaks/sqlite and
25
+ * asynchronous here. No caller in between has to know which.
26
+ *
27
+ * ## The transaction, in plain terms
28
+ * D1 has no interactive transaction — no call opens one, lets your code read
29
+ * and decide inside it, and commits at the end. What it has is `batch()`, which
30
+ * runs a list of statements sequentially in one implicit transaction and rolls
31
+ * the whole list back if any fails. So {@link storage}'s `tx` defers: reads run
32
+ * immediately against the committed database, writes are gathered as
33
+ * statements, returning flushes them as one atomic batch, and throwing discards
34
+ * them unsent. Reads inside the transaction see its own pending writes through
35
+ * an in-memory overlay evaluated by
36
+ * {@link https://jsr.io/@yaks/match | @yaks/match}.
37
+ *
38
+ * The write is atomic; the transaction is NOT serializable, because the reads
39
+ * cannot be enrolled in a batch that has not been sent. See the README's
40
+ * "The transaction" for exactly what that costs and when it matters.
41
+ *
42
+ * ## Secrets
43
+ * {@link d1Vault} keeps a graph's secrets in D1, each value encrypted under a
44
+ * key the caller holds. It meets @yaks/secrets' vault by shape, without this
45
+ * package importing it.
46
+ *
47
+ * ## Where it sits
48
+ * One of three interchangeable adapters behind the same seam:
49
+ * **@yaks/d1** (this package, async), {@link
50
+ * https://jsr.io/@yaks/durable-object | @yaks/durable-object} (a Durable
51
+ * Object's embedded SQLite, synchronous) and {@link
52
+ * https://jsr.io/@yaks/sqlite | @yaks/sqlite} (in-process, synchronous — and
53
+ * the reference every adapter is held to).
54
+ *
55
+ * @module
56
+ */
57
+
58
+ export {
59
+ bind,
60
+ type D1Like,
61
+ type D1Result,
62
+ type D1Stmt,
63
+ type D1Value,
64
+ type Prepared,
65
+ type Row,
66
+ unbind,
67
+ } from './d1.js'
68
+ export { bundles, comps, gatherSql, type Query, spineSql, sql } from './read.js'
69
+ // The write path is @yaks/sqlite's. Every write it builds is a self-sufficient
70
+ // statement — an owner id is a subquery, nothing is read between two writes —
71
+ // which is exactly what a batch that has not been sent yet needs, so this
72
+ // package gathers those statements rather than keeping a second copy of them.
73
+ export {
74
+ dropSql,
75
+ mintSql,
76
+ patchSql,
77
+ removeSql,
78
+ touched,
79
+ upsertSql,
80
+ } from '@yaks/sqlite'
81
+ export { storage, type Store } from './store.js'
82
+ export { type D1Vault, d1Vault, type Sealed } from './vault.js'
83
+ export type { Storage, Tx } from 'jsr:@yaks/graph@0.2.36'
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@yaks/d1",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/d1",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ }
11
+ },
12
+ "license": "Apache-2.0",
13
+ "dependencies": {
14
+ "@yaks/fp": "0.2.36",
15
+ "@yaks/graph": "0.2.36",
16
+ "@yaks/match": "0.2.36",
17
+ "@yaks/query": "0.2.36",
18
+ "@yaks/sql": "0.2.36",
19
+ "@yaks/sqlite": "0.2.36",
20
+ "@yaks/vocab": "0.2.36"
21
+ },
22
+ "description": "Adapts Cloudflare D1 to graph storage with asynchronous queries and writes submitted as atomic statement batches.",
23
+ "repository": "https://github.com/yak-sh/yak.git"
24
+ }
package/read.js ADDED
@@ -0,0 +1,134 @@
1
+ // Reads: a query in, whole entities out. The compile half is the sibling
2
+ // packages' — @yaks/query parses the query text, @yaks/vocab describes the
3
+ // vocabulary, @yaks/sql compiles the two into a statement — and the per-
4
+ // component gather is @yaks/sqlite's `compSql`, so a property that the filter
5
+ // resolves one way cannot come back gathered another.
6
+ //
7
+ // What is this package's own is the number of round trips. @yaks/sqlite runs
8
+ // one statement at a time, because an embedded engine answers in microseconds;
9
+ // over D1 every statement is a network hop, so reading one component at a time
10
+ // would cost a hop per component per entity. Here the whole gather —
11
+ // every entity's spine, every entity's components — is built as one list of
12
+ // statements and sent as a single `batch()`. A read of any size takes two round
13
+ // trips: the compiled query, then the read of the components.
14
+ //
15
+ // Two, because the second list has to bind the eids the first one found. When
16
+ // those eids do not need binding — when the query that found them can simply be
17
+ // repeated as a subquery — the two collapse into one: `wholeSql` puts the
18
+ // query, the `entity` rows it matches and every component of them into a single
19
+ // batch, each statement ending `where o.eid in (<the query>)`. That is what
20
+ // @yaks/graph's `Tx.whole` asks for, and it is why an `about` read costs one
21
+ // trip rather than two. The cost is that the filter is evaluated once per
22
+ // component instead of once in total, which is why it is offered for a query
23
+ // naming a set and not for `read`, where a `.limit` re-evaluated per statement
24
+ // could break a tie differently each time.
25
+ import { parse } from "@yaks/query";
26
+ import { among, col, compile, eq, from, select, val } from "@yaks/sql";
27
+ import { compSql, decoded, OWNER, setSql, spine } from "@yaks/sqlite";
28
+ import { tombstoned } from "@yaks/graph/bundle";
29
+ export let ast = (q)=>typeof q == 'string' ? parse(q) : q;
30
+ /** The compiled statement for a query. */ export let sql = (v, query, opts = {})=>compile(ast(query), v, opts);
31
+ /** The identity of an eid, as stored: its `num`, and whether it is buried. One
32
+ * statement, so a gather of many entities is one batch. */ export let spineSql = (v, eid)=>spine(v, eq(col('eid', 'e'), val(eid)));
33
+ /** What a gather asks about one entity: its spine, then one read per component
34
+ * the vocabulary declares, or per one of those `names` names. The order is
35
+ * what {@link bundles} reads back. */ export let gatherSql = (v, eid, opts = {}, names)=>[
36
+ spineSql(v, eid),
37
+ ...comps(v, names).map((comp)=>compSql(v, comp, eid, opts.derived))
38
+ ];
39
+ /** The components a gather reads, in the vocabulary's order: every one, or
40
+ * those `names` names — the spine is the identity, not a component of its
41
+ * own. */ export let comps = (v, names)=>v.all.filter((name)=>name != 'entity' && (!names || names.includes(name)));
42
+ // One entity's answers, turned back into a bundle. The results arrive in the
43
+ // order `gatherSql` asked: the spine first, then a component per statement.
44
+ let bundleOf = (v, eid, answers, names)=>{
45
+ let spine = answers[0][0];
46
+ if (!spine) return undefined;
47
+ let entity = {
48
+ eid,
49
+ ...spine.num == null ? {} : {
50
+ num: Number(spine.num)
51
+ }
52
+ };
53
+ if (spine.dead != null) return tombstoned(entity);
54
+ let out = {
55
+ entity
56
+ };
57
+ comps(v, names).forEach((comp, i)=>{
58
+ let row = answers[i + 1][0];
59
+ if (!row) return;
60
+ delete row.present;
61
+ out[comp] = decoded(v, comp, row);
62
+ });
63
+ return out;
64
+ };
65
+ /**
66
+ * Turn the answers to a gather back into bundles, one per eid, in the order the
67
+ * eids were asked about. An eid no entity has is simply absent; a tombstoned
68
+ * one comes back carrying `tombstone` (it is still an identity, just a dead one).
69
+ *
70
+ * `answers` is the flat result list `batch()` returns for
71
+ * `eids.flatMap((e) => gatherSql(v, e, opts, names))` — one entry per
72
+ * statement, in order.
73
+ */ export let bundles = (v, eids, answers, names)=>{
74
+ let width = comps(v, names).length + 1;
75
+ return eids.flatMap((eid, i)=>{
76
+ let b = bundleOf(v, eid, answers.slice(i * width, (i + 1) * width), names);
77
+ return b ? [
78
+ b
79
+ ] : [];
80
+ });
81
+ };
82
+ /**
83
+ * What a whole read asks, as one batch: the compiled query first — it names the
84
+ * hits and fixes their order — then the spine of everything it hits, then one
85
+ * statement per component over that same set. Nothing binds an eid: each
86
+ * statement repeats the query as a subquery, which is what lets the whole read
87
+ * come back in a single round trip. {@link whole} reads it back.
88
+ */ export let wholeSql = (v, q, opts = {})=>{
89
+ let hits = select({
90
+ cols: [
91
+ col('eid')
92
+ ],
93
+ from: from(q)
94
+ });
95
+ return [
96
+ q,
97
+ spine(v, among(col('eid', 'e'), hits)),
98
+ ...comps(v).map((comp)=>setSql(v, comp, hits, opts.derived))
99
+ ];
100
+ };
101
+ /**
102
+ * Turn those answers back into bundles: the hits in the order the query named
103
+ * them, each whole. Same shape as {@link bundles}, keyed by the owner column
104
+ * each set-shaped statement carries rather than by position.
105
+ */ export let whole = (v, answers)=>{
106
+ let [hits, spines, ...parts] = answers;
107
+ let out = new Map();
108
+ for (let r of spines){
109
+ let entity = {
110
+ eid: String(r.eid),
111
+ ...r.num == null ? {} : {
112
+ num: Number(r.num)
113
+ }
114
+ };
115
+ out.set(entity.eid, r.dead == null ? {
116
+ entity
117
+ } : tombstoned(entity));
118
+ }
119
+ comps(v).forEach((comp, i)=>{
120
+ for (let row of parts[i] ?? []){
121
+ let b = out.get(String(row[OWNER]));
122
+ delete row[OWNER];
123
+ delete row.present;
124
+ if (b && b.tombstone == null) b[comp] = decoded(v, comp, row);
125
+ }
126
+ });
127
+ return hits.flatMap((r)=>{
128
+ let b = r.eid == null ? undefined : out.get(String(r.eid));
129
+ return b ? [
130
+ b
131
+ ] : [];
132
+ });
133
+ };
134
+ //# sourceMappingURL=read.js.map
package/read.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.js","sources":["./read.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,2EAA2E;AAC3E,yEAAyE;AACzE,8EAA8E;AAC9E,sDAAsD;AACtD,EAAE;AACF,6EAA6E;AAC7E,+EAA+E;AAC/E,+EAA+E;AAC/E,qEAAqE;AACrE,4EAA4E;AAC5E,gFAAgF;AAChF,8DAA8D;AAC9D,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,0EAA0E;AAC1E,gFAAgF;AAChF,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;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