@wazootech/worlds-cloudflare 0.0.0-stage → 0.15.6
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/LICENSE +21 -0
- package/README.md +359 -2
- package/dist/d1-connection-driver-DfBsnVwn.d.ts +71 -0
- package/dist/d1-provenance-sql-jn_cwWxX.js +99 -0
- package/dist/d1-quad-insert-sql-B4ZiZZe8.js +313 -0
- package/dist/d1-rdfjs-store-read-2QTEEe_a.js +64 -0
- package/dist/d1-schema-builder-DmrQfhKJ.js +86 -0
- package/dist/d1-schema-builder-sx3v-XjI.d.ts +42 -0
- package/dist/index.d.ts +205 -0
- package/dist/index.js +354 -0
- package/dist/mod-BRtbH8pa.d.ts +52 -0
- package/dist/mod-Do_hSIzo.d.ts +452 -0
- package/dist/mod-L9cQ_Ztm.d.ts +192 -0
- package/dist/project-search-chunks-options-qI9m5FWz.js +166 -0
- package/dist/quad-store-DX7Nqyjw.js +398 -0
- package/dist/quad-store.d.ts +2 -0
- package/dist/quad-store.js +1 -0
- package/dist/rdfjs-store-B3w5noFV.js +668 -0
- package/dist/rdfjs-store.d.ts +2 -0
- package/dist/rdfjs-store.js +1 -0
- package/dist/schema.d.ts +2 -0
- package/dist/schema.js +1 -0
- package/dist/search-index-DVbbsc3z.js +609 -0
- package/dist/search-index.d.ts +2 -0
- package/dist/search-index.js +1 -0
- package/package.json +84 -4
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { DataFactory } from "@wazootech/sparql-engine/data-model";
|
|
2
|
+
import { hashQuads, toRdfjsTerm } from "@wazootech/worlds-sdk/quad-store";
|
|
3
|
+
/**
|
|
4
|
+
* DEFAULT_D1_MAX_WRITE_BATCH_SIZE limits statements per D1 batch() call (and is
|
|
5
|
+
* the atomic statement limit of a commit). It is a chosen size, 2,000: the
|
|
6
|
+
* largest count a real-D1 measurement (2026-11-22, see README) accepted at
|
|
7
|
+
* every vector dimension. D1 documents no per-batch statement cap, but the
|
|
8
|
+
* Worker-to-D1 RPC rejects a batch whose serialized arguments exceed 32 MiB,
|
|
9
|
+
* which heavy rows (1,536-dim chunks, about 22 KB each) reach well before 2,000
|
|
10
|
+
* statements; the commit driver guards that with a byte budget
|
|
11
|
+
* (`DEFAULT_D1_MAX_BATCH_WEIGHT`), not this count. The 100-parameter cap is per
|
|
12
|
+
* statement and is a separate limit.
|
|
13
|
+
*/
|
|
14
|
+
const DEFAULT_D1_MAX_WRITE_BATCH_SIZE = 2e3;
|
|
15
|
+
/**
|
|
16
|
+
* effectiveLookupChunkSize resolves the IN-clause chunk width for a statement
|
|
17
|
+
* run. The documented cap is host parameters per statement; world-scoped
|
|
18
|
+
* statements also bind world_id, so reserve one slot for it.
|
|
19
|
+
*/
|
|
20
|
+
function effectiveLookupChunkSize(maxLookupChunkSize, worldScoped) {
|
|
21
|
+
return Math.max(1, (maxLookupChunkSize ?? 100) - (worldScoped ? 1 : 0));
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* D1BatchExecutor encapsulates statement buffering and chunked execution for D1.
|
|
25
|
+
* It prevents memory blowouts by eagerly flushing when the staging buffer reaches the threshold.
|
|
26
|
+
*/
|
|
27
|
+
var D1BatchExecutor = class {
|
|
28
|
+
options;
|
|
29
|
+
statements = [];
|
|
30
|
+
/**
|
|
31
|
+
* failure is set once a batch() call fails mid-flush. The executor is then
|
|
32
|
+
* fail-closed: staged statements after the failed batch were never executed
|
|
33
|
+
* and a retry would silently skip them, so every later stage/flush rejects.
|
|
34
|
+
*/
|
|
35
|
+
failure = null;
|
|
36
|
+
constructor(options) {
|
|
37
|
+
this.options = options;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* stage appends statements and flushes eagerly when the staging buffer grows too large.
|
|
41
|
+
*/
|
|
42
|
+
async stage(source) {
|
|
43
|
+
if (this.failure) throw this.failureError("stage");
|
|
44
|
+
const sourceLength = source.length;
|
|
45
|
+
for (let index = 0; index < sourceLength; index++) {
|
|
46
|
+
this.statements.push(source[index]);
|
|
47
|
+
if (this.statements.length >= 1e4) await this.flush();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* flush executes and clears all currently staged write statements.
|
|
52
|
+
* D1's atomic unit is a single batch() call (documented as a transaction),
|
|
53
|
+
* so staged statements are chunked by writeBatchSize and executed
|
|
54
|
+
* sequentially: a commit larger than one chunk is not atomic.
|
|
55
|
+
*
|
|
56
|
+
* A failure mid-stream leaves the commit partially applied (statements before
|
|
57
|
+
* the failed batch committed; the rest never ran). The executor records that
|
|
58
|
+
* state and refuses further use rather than letting a later flush silently
|
|
59
|
+
* skip the unexecuted tail.
|
|
60
|
+
*/
|
|
61
|
+
async flush() {
|
|
62
|
+
if (this.failure) throw this.failureError("flush");
|
|
63
|
+
if (this.statements.length === 0) return;
|
|
64
|
+
const { connection, writeBatchSize } = this.options;
|
|
65
|
+
const staged = this.statements.splice(0, this.statements.length);
|
|
66
|
+
let sent = 0;
|
|
67
|
+
try {
|
|
68
|
+
for (let index = 0; index < staged.length; index += writeBatchSize) {
|
|
69
|
+
await connection.batch(staged.slice(index, index + writeBatchSize));
|
|
70
|
+
sent += Math.min(writeBatchSize, staged.length - index);
|
|
71
|
+
}
|
|
72
|
+
} catch (cause) {
|
|
73
|
+
this.failure = {
|
|
74
|
+
sent,
|
|
75
|
+
staged: staged.length,
|
|
76
|
+
cause
|
|
77
|
+
};
|
|
78
|
+
throw this.wrapFlushFailure(cause);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
wrapFlushFailure(cause) {
|
|
82
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
83
|
+
const { sent = 0, staged = 0 } = this.failure ?? {};
|
|
84
|
+
return new Error(`D1 batch failed after ${sent} of ${staged} staged statements (${staged - sent} not executed): ${detail}`, { cause });
|
|
85
|
+
}
|
|
86
|
+
failureError(operation) {
|
|
87
|
+
const { sent = 0, staged = 0, cause } = this.failure;
|
|
88
|
+
const detail = cause instanceof Error ? cause.message : String(cause);
|
|
89
|
+
return new Error(`D1 batch executor is fail-closed after a mid-stream batch failure (${sent} of ${staged} statements executed, ${staged - sent} not executed); ${operation} refused: ${detail}`, { cause });
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
// src/cloudflare/d1/d1-quad-row.ts
|
|
93
|
+
const { quad } = DataFactory;
|
|
94
|
+
/**
|
|
95
|
+
* quadFromD1Row reconstructs an RDF/JS quad from a D1 `quads` table row.
|
|
96
|
+
* Rows come from the D1ConnectionDriver, which exposes plain column records
|
|
97
|
+
* (not the @cloudflare/workers-types array-like Row).
|
|
98
|
+
*/
|
|
99
|
+
function quadFromD1Row(row) {
|
|
100
|
+
const subject = toRdfjsTerm({
|
|
101
|
+
termType: String(row.s_type),
|
|
102
|
+
value: String(row.s)
|
|
103
|
+
});
|
|
104
|
+
const predicate = toRdfjsTerm({
|
|
105
|
+
termType: "NamedNode",
|
|
106
|
+
value: String(row.p)
|
|
107
|
+
});
|
|
108
|
+
const object = toRdfjsTerm({
|
|
109
|
+
termType: String(row.o_type),
|
|
110
|
+
value: String(row.o),
|
|
111
|
+
language: row.o_lang ? String(row.o_lang) : void 0,
|
|
112
|
+
datatype: row.o_datatype ? String(row.o_datatype) : void 0
|
|
113
|
+
});
|
|
114
|
+
const graph = toRdfjsTerm({
|
|
115
|
+
termType: String(row.g_type),
|
|
116
|
+
value: String(row.g)
|
|
117
|
+
});
|
|
118
|
+
return quad(subject, predicate, object, graph);
|
|
119
|
+
}
|
|
120
|
+
/** quadToInsertRow flattens a quad into a D1 insert row with a content-addressed id. */
|
|
121
|
+
async function quadToInsertRow(quad) {
|
|
122
|
+
const [id] = await hashQuads([quad]);
|
|
123
|
+
return buildInsertRow(quad, id);
|
|
124
|
+
}
|
|
125
|
+
/** buildInsertRow flattens a quad into a D1 insert row under its already-computed content hash. */
|
|
126
|
+
function buildInsertRow(quad, id) {
|
|
127
|
+
const subject = quad.subject;
|
|
128
|
+
const object = quad.object;
|
|
129
|
+
const graph = quad.graph;
|
|
130
|
+
return {
|
|
131
|
+
quad_id: id,
|
|
132
|
+
s: subject.value,
|
|
133
|
+
s_type: subject.termType,
|
|
134
|
+
p: quad.predicate.value,
|
|
135
|
+
o: object.value,
|
|
136
|
+
o_type: object.termType,
|
|
137
|
+
o_datatype: object.termType === "Literal" ? object.datatype?.value ?? null : null,
|
|
138
|
+
o_lang: object.termType === "Literal" ? object.language || null : null,
|
|
139
|
+
g: graph.value,
|
|
140
|
+
g_type: graph.termType
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
// src/cloudflare/quad-store/d1-quad-sql-types.ts
|
|
144
|
+
const rdfLangStringIri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";
|
|
145
|
+
const xsdStringIri = "http://www.w3.org/2001/XMLSchema#string";
|
|
146
|
+
const DEFAULT_D1_MATCH_PAGE_SIZE = 1e3;
|
|
147
|
+
function generatePlaceholders(count) {
|
|
148
|
+
return Array(count).fill("?").join(", ");
|
|
149
|
+
}
|
|
150
|
+
// src/cloudflare/quad-store/d1-quad-delete-sql.ts
|
|
151
|
+
function buildDeleteQuadsByQuadIds(quadIds, worldId) {
|
|
152
|
+
return {
|
|
153
|
+
sql: `DELETE FROM quads WHERE quad_id IN (${generatePlaceholders(quadIds.length)})${worldId ? " AND world_id = ?" : ""}`,
|
|
154
|
+
args: worldId ? [...quadIds, worldId] : quadIds
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* buildDeleteDerivedQuadsByQuadIds deletes only inferred rows, so inference
|
|
159
|
+
* can never remove an asserted quad.
|
|
160
|
+
*/
|
|
161
|
+
function buildDeleteDerivedQuadsByQuadIds(quadIds, worldId) {
|
|
162
|
+
return {
|
|
163
|
+
sql: `DELETE FROM quads WHERE derived = 1 AND quad_id IN (${generatePlaceholders(quadIds.length)})${worldId ? " AND world_id = ?" : ""}`,
|
|
164
|
+
args: worldId ? [...quadIds, worldId] : quadIds
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/** buildDeleteAllDerivedQuads removes every inferred row, never an asserted one. */
|
|
168
|
+
function buildDeleteAllDerivedQuads(worldId) {
|
|
169
|
+
return {
|
|
170
|
+
sql: `DELETE FROM quads WHERE derived = 1${worldId ? " AND world_id = ?" : ""}`,
|
|
171
|
+
args: worldId ? [worldId] : []
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
function buildWipeAllGraphDataStatements(worldId) {
|
|
175
|
+
const suffix = worldId ? " WHERE world_id = ?" : "";
|
|
176
|
+
return [{
|
|
177
|
+
sql: `DELETE FROM chunks${suffix}`,
|
|
178
|
+
args: worldId ? [worldId] : []
|
|
179
|
+
}, {
|
|
180
|
+
sql: `DELETE FROM quads${suffix}`,
|
|
181
|
+
args: worldId ? [worldId] : []
|
|
182
|
+
}];
|
|
183
|
+
}
|
|
184
|
+
// src/cloudflare/quad-store/d1-quad-where-sql.ts
|
|
185
|
+
function buildD1QuadPatternWhereClause(pattern) {
|
|
186
|
+
const conditions = [];
|
|
187
|
+
const args = [];
|
|
188
|
+
appendTermCondition(conditions, args, "s", "s_type", pattern.subject);
|
|
189
|
+
appendTermCondition(conditions, args, "o", "o_type", pattern.object);
|
|
190
|
+
if (pattern.predicate) {
|
|
191
|
+
conditions.push("p = ?");
|
|
192
|
+
args.push(pattern.predicate.value);
|
|
193
|
+
}
|
|
194
|
+
appendTermCondition(conditions, args, "g", "g_type", pattern.graph);
|
|
195
|
+
return {
|
|
196
|
+
conditions,
|
|
197
|
+
args
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
function appendTermCondition(conditions, args, valueColumn, typeColumn, term) {
|
|
201
|
+
if (!term) return;
|
|
202
|
+
conditions.push(`${valueColumn} = ?`);
|
|
203
|
+
args.push(term.value);
|
|
204
|
+
conditions.push(`${typeColumn} = ?`);
|
|
205
|
+
args.push(term.termType);
|
|
206
|
+
if (term.termType === "Literal") {
|
|
207
|
+
const literalTerm = term;
|
|
208
|
+
if (literalTerm.language) {
|
|
209
|
+
conditions.push(`o_lang = ?`);
|
|
210
|
+
args.push(literalTerm.language);
|
|
211
|
+
}
|
|
212
|
+
if (literalTerm.datatype) {
|
|
213
|
+
const datatypeValue = literalTerm.datatype.value;
|
|
214
|
+
if (datatypeValue === "http://www.w3.org/2001/XMLSchema#string") conditions.push(`(o_datatype IS NULL OR o_datatype = '' OR o_datatype = '${xsdStringIri}')`);
|
|
215
|
+
else if (datatypeValue === "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString") conditions.push(`(o_datatype IS NULL OR o_datatype = '' OR o_datatype = '${rdfLangStringIri}')`);
|
|
216
|
+
else {
|
|
217
|
+
conditions.push(`o_datatype = ?`);
|
|
218
|
+
args.push(datatypeValue);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// src/cloudflare/quad-store/d1-quad-select-sql.ts
|
|
224
|
+
/** buildSelectExistingQuadIds finds stored ids; `assertedOnly` ignores inferred rows. */
|
|
225
|
+
function buildSelectExistingQuadIds(quadIds, worldId, options = {}) {
|
|
226
|
+
return {
|
|
227
|
+
sql: `SELECT quad_id AS id FROM quads WHERE quad_id IN (${generatePlaceholders(quadIds.length)})${options.assertedOnly ? " AND derived = 0" : ""}${worldId ? " AND world_id = ?" : ""}`,
|
|
228
|
+
args: worldId ? [...quadIds, worldId] : quadIds
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
/** buildCountAssertedQuads counts the asserted (not inferred) rows. */
|
|
232
|
+
function buildCountAssertedQuads(worldId) {
|
|
233
|
+
return {
|
|
234
|
+
sql: `SELECT COUNT(*) AS count FROM quads WHERE derived = 0${worldId ? " AND world_id = ?" : ""}`,
|
|
235
|
+
args: worldId ? [worldId] : []
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/** buildSelectAssertedQuadsPage pages the asserted rows by quad_id. */
|
|
239
|
+
function buildSelectAssertedQuadsPage(pageOptions, worldId) {
|
|
240
|
+
const conditions = ["derived = 0"];
|
|
241
|
+
const args = [];
|
|
242
|
+
if (worldId) {
|
|
243
|
+
conditions.push("world_id = ?");
|
|
244
|
+
args.push(worldId);
|
|
245
|
+
}
|
|
246
|
+
if (pageOptions.afterQuadId) {
|
|
247
|
+
conditions.push("quad_id > ?");
|
|
248
|
+
args.push(pageOptions.afterQuadId);
|
|
249
|
+
}
|
|
250
|
+
args.push(String(Math.max(1, Math.floor(pageOptions.limit))));
|
|
251
|
+
return {
|
|
252
|
+
sql: `SELECT quad_id AS id, s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type FROM quads WHERE ${conditions.join(" AND ")} ORDER BY quad_id ASC LIMIT ?`,
|
|
253
|
+
args
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function buildMatchQuadsQuery(pattern, pageOptions, worldId) {
|
|
257
|
+
const { conditions, args } = buildD1QuadPatternWhereClause(pattern);
|
|
258
|
+
if (worldId) {
|
|
259
|
+
conditions.push("world_id = ?");
|
|
260
|
+
args.push(worldId);
|
|
261
|
+
}
|
|
262
|
+
if (pageOptions?.afterQuadId) {
|
|
263
|
+
conditions.push("quad_id > ?");
|
|
264
|
+
args.push(pageOptions.afterQuadId);
|
|
265
|
+
}
|
|
266
|
+
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
267
|
+
let limitClause = "";
|
|
268
|
+
if (pageOptions?.limit != null) {
|
|
269
|
+
limitClause = " LIMIT ?";
|
|
270
|
+
args.push(String(Math.max(1, Math.floor(pageOptions.limit))));
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
sql: `SELECT quad_id AS id, s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type FROM quads ${whereClause} ORDER BY quad_id ASC${limitClause}`,
|
|
274
|
+
args
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
function buildCountQuadsQuery(pattern, worldId) {
|
|
278
|
+
const { conditions, args } = buildD1QuadPatternWhereClause(pattern);
|
|
279
|
+
if (worldId) {
|
|
280
|
+
conditions.push("world_id = ?");
|
|
281
|
+
args.push(worldId);
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
sql: `SELECT COUNT(*) AS count FROM quads ${conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""}`,
|
|
285
|
+
args
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
// src/cloudflare/quad-store/d1-quad-insert-sql.ts
|
|
289
|
+
/**
|
|
290
|
+
* buildBulkInsertQuads builds one INSERT per row. By default a row replaces an
|
|
291
|
+
* existing quad_id; `orIgnore` keeps the existing row instead, which is how
|
|
292
|
+
* inferred rows are written so they can never overwrite an asserted one.
|
|
293
|
+
*/
|
|
294
|
+
function buildBulkInsertQuads(insertQuadRows, options = {}) {
|
|
295
|
+
if (insertQuadRows.length === 0) return [];
|
|
296
|
+
const statements = [];
|
|
297
|
+
for (let rowOffset = 0; rowOffset < insertQuadRows.length; rowOffset += 1) {
|
|
298
|
+
const rowBatch = insertQuadRows.slice(rowOffset, rowOffset + 1);
|
|
299
|
+
const hasWorld = rowBatch[0]?.world_id !== void 0;
|
|
300
|
+
const hasDerived = rowBatch[0]?.derived !== void 0;
|
|
301
|
+
const columnCount = 10 + (hasWorld ? 1 : 0) + (hasDerived ? 1 : 0);
|
|
302
|
+
const valuePlaceholders = rowBatch.map(() => `(${generatePlaceholders(columnCount)})`).join(", ");
|
|
303
|
+
const args = [];
|
|
304
|
+
for (const insertQuadRow of rowBatch) args.push(insertQuadRow.quad_id, insertQuadRow.s, insertQuadRow.s_type, insertQuadRow.p, insertQuadRow.o, insertQuadRow.o_type, insertQuadRow.o_datatype ?? null, insertQuadRow.o_lang ?? null, insertQuadRow.g, insertQuadRow.g_type, ...hasWorld ? [insertQuadRow.world_id] : [], ...hasDerived ? [insertQuadRow.derived] : []);
|
|
305
|
+
if (args.length > rowBatch.length * columnCount) throw new Error(`buildBulkInsertQuads: batch exceeds D1 host-parameter budget (${args.length})`);
|
|
306
|
+
statements.push({
|
|
307
|
+
sql: `INSERT OR ${options.orIgnore ? "IGNORE" : "REPLACE"} INTO quads (quad_id, s, s_type, p, o, o_type, o_datatype, o_lang, g, g_type${hasWorld ? ", world_id" : ""}${hasDerived ? ", derived" : ""}) VALUES ${valuePlaceholders}`,
|
|
308
|
+
args
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
return statements;
|
|
312
|
+
}
|
|
313
|
+
export { effectiveLookupChunkSize as _, buildSelectAssertedQuadsPage as a, buildDeleteDerivedQuadsByQuadIds as c, DEFAULT_D1_MATCH_PAGE_SIZE as d, buildInsertRow as f, DEFAULT_D1_MAX_WRITE_BATCH_SIZE as g, D1BatchExecutor as h, buildMatchQuadsQuery as i, buildDeleteQuadsByQuadIds as l, quadToInsertRow as m, buildCountAssertedQuads as n, buildSelectExistingQuadIds as o, quadFromD1Row as p, buildCountQuadsQuery as r, buildDeleteAllDerivedQuads as s, buildBulkInsertQuads as t, buildWipeAllGraphDataStatements as u };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { i as buildMatchQuadsQuery, p as quadFromD1Row, r as buildCountQuadsQuery } from "./d1-quad-insert-sql-B4ZiZZe8.js";
|
|
2
|
+
// src/cloudflare/rdfjs-store/d1-rdfjs-store-read.ts
|
|
3
|
+
/** matchD1Pages keyset-pages the quads matching a pattern, one SQL round-trip per page. */
|
|
4
|
+
async function* matchD1Pages(connection, matchPageSize, worldId, subject, predicate, object, graph) {
|
|
5
|
+
const pattern = {
|
|
6
|
+
subject: subject ?? null,
|
|
7
|
+
predicate: predicate ?? null,
|
|
8
|
+
object: object ?? null,
|
|
9
|
+
graph: graph ?? null
|
|
10
|
+
};
|
|
11
|
+
let afterQuadId;
|
|
12
|
+
for (;;) {
|
|
13
|
+
const { sql, args } = buildMatchQuadsQuery(pattern, {
|
|
14
|
+
afterQuadId,
|
|
15
|
+
limit: matchPageSize
|
|
16
|
+
}, worldId);
|
|
17
|
+
const result = await connection.execute({
|
|
18
|
+
sql,
|
|
19
|
+
args
|
|
20
|
+
});
|
|
21
|
+
if (result.rows.length === 0) return;
|
|
22
|
+
for (const row of result.rows) {
|
|
23
|
+
afterQuadId = String(row.id);
|
|
24
|
+
yield quadFromD1Row(row);
|
|
25
|
+
}
|
|
26
|
+
if (result.rows.length < matchPageSize) return;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** collectQuads drains a quad stream into an array. */
|
|
30
|
+
async function collectQuads(stream) {
|
|
31
|
+
const quads = [];
|
|
32
|
+
await new Promise((resolve, reject) => {
|
|
33
|
+
stream.on("data", (quad) => quads.push(quad));
|
|
34
|
+
stream.on("end", () => resolve());
|
|
35
|
+
stream.on("error", reject);
|
|
36
|
+
});
|
|
37
|
+
return quads;
|
|
38
|
+
}
|
|
39
|
+
/** countD1Matches returns the number of quads matching the pattern. */
|
|
40
|
+
async function countD1Matches(connection, worldId, subject, predicate, object, graph) {
|
|
41
|
+
const { sql, args } = buildCountQuadsQuery({
|
|
42
|
+
subject: subject ?? null,
|
|
43
|
+
predicate: predicate ?? null,
|
|
44
|
+
object: object ?? null,
|
|
45
|
+
graph: graph ?? null
|
|
46
|
+
}, worldId);
|
|
47
|
+
const result = await connection.execute({
|
|
48
|
+
sql,
|
|
49
|
+
args
|
|
50
|
+
});
|
|
51
|
+
return Number(result.rows[0]?.count ?? 0);
|
|
52
|
+
}
|
|
53
|
+
/** removeMatchedQuads deletes every matching quad in one patch and yields the removed quads. */
|
|
54
|
+
async function* removeMatchedQuads(store, subject, predicate, object, graph) {
|
|
55
|
+
const matches = await store.getQuads(subject, predicate, object, graph);
|
|
56
|
+
if (matches.length > 0) {
|
|
57
|
+
await store.applyPatch({
|
|
58
|
+
insertions: [],
|
|
59
|
+
deletions: matches
|
|
60
|
+
});
|
|
61
|
+
for (const quad of matches) yield quad;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export { removeMatchedQuads as i, countD1Matches as n, matchD1Pages as r, collectQuads as t };
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { buildChunksQuadIdIndex } from "@wazootech/worlds-sqlite/sql-core";
|
|
2
|
+
import { i as buildProvenanceTable } from "./d1-provenance-sql-jn_cwWxX.js";
|
|
3
|
+
// src/cloudflare/validate-world-id.ts
|
|
4
|
+
/**
|
|
5
|
+
* validateWorldId rejects a caller-provided worldId that is not a non-empty
|
|
6
|
+
* string. Every scoping branch in the adapter is truthiness-based
|
|
7
|
+
* (`worldId ? scoped : unscoped`), so an empty-string worldId would silently
|
|
8
|
+
* disable world scoping and run SQL over a shared database instead of failing
|
|
9
|
+
* visibly (worlds-cloudflare#71).
|
|
10
|
+
*/
|
|
11
|
+
function validateWorldId(worldId, context) {
|
|
12
|
+
if (worldId === void 0) return;
|
|
13
|
+
if (typeof worldId !== "string" || worldId.trim() === "") throw new Error(`${context}: worldId, when provided, must be a non-empty string; an empty value would silently disable world scoping`);
|
|
14
|
+
}
|
|
15
|
+
// src/cloudflare/schema/d1-schema-builder.ts
|
|
16
|
+
/** Maximum embedding dimensions accepted by D1SchemaBuilder (Vectorize cap: 1536 float32). */
|
|
17
|
+
const D1_MAX_VECTOR_DIMENSIONS = 1536;
|
|
18
|
+
var D1SchemaBuilder = class {
|
|
19
|
+
vectorDimensions;
|
|
20
|
+
worldId;
|
|
21
|
+
provenance;
|
|
22
|
+
constructor(vectorDimensions, options) {
|
|
23
|
+
validateWorldId(options?.worldId, "D1SchemaBuilder");
|
|
24
|
+
const dimensions = Math.floor(Number(vectorDimensions));
|
|
25
|
+
if (!Number.isFinite(dimensions) || dimensions < 1 || dimensions > D1_MAX_VECTOR_DIMENSIONS) throw new Error(`vectorDimensions must be a finite integer in [1, ${D1_MAX_VECTOR_DIMENSIONS}], received: ${String(vectorDimensions)}`);
|
|
26
|
+
this.vectorDimensions = dimensions;
|
|
27
|
+
this.worldId = options?.worldId;
|
|
28
|
+
this.provenance = options?.provenance ?? false;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* buildTables returns the idempotent DDL that creates the quads and chunks
|
|
32
|
+
* tables in dependency order.
|
|
33
|
+
*/
|
|
34
|
+
buildTables() {
|
|
35
|
+
return [
|
|
36
|
+
this.buildD1QuadsTable(),
|
|
37
|
+
this.buildD1ChunksTable(),
|
|
38
|
+
...this.provenance ? buildProvenanceTable(this.worldId) : []
|
|
39
|
+
];
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* buildIndexes returns DDL for 7 covering composite indexes on the quads table
|
|
43
|
+
* (six subject-predicate-object-graph index orders + GPSO for graph-scoped access) enabling any quad pattern
|
|
44
|
+
* to be resolved via a single index seek.
|
|
45
|
+
*/
|
|
46
|
+
buildIndexes() {
|
|
47
|
+
return [
|
|
48
|
+
"CREATE INDEX IF NOT EXISTS idx_quads_spog ON quads(s, p, o, g)",
|
|
49
|
+
"CREATE INDEX IF NOT EXISTS idx_quads_sopg ON quads(s, o, p, g)",
|
|
50
|
+
"CREATE INDEX IF NOT EXISTS idx_quads_pso ON quads(p, s, o)",
|
|
51
|
+
"CREATE INDEX IF NOT EXISTS idx_quads_pos ON quads(p, o, s)",
|
|
52
|
+
"CREATE INDEX IF NOT EXISTS idx_quads_ospg ON quads(o, s, p, g)",
|
|
53
|
+
"CREATE INDEX IF NOT EXISTS idx_quads_opsg ON quads(o, p, s, g)",
|
|
54
|
+
"CREATE INDEX IF NOT EXISTS idx_quads_gpso ON quads(g, p, s, o)"
|
|
55
|
+
];
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* buildD1QuadsTable creates the quads table. `derived` is 0 for an asserted
|
|
59
|
+
* quad and 1 for a quad materialized by inference; a quad that is both
|
|
60
|
+
* asserted and derived is stored once, as asserted.
|
|
61
|
+
*/
|
|
62
|
+
buildD1QuadsTable() {
|
|
63
|
+
return `CREATE TABLE IF NOT EXISTS quads (quad_id TEXT${this.worldId ? "" : " PRIMARY KEY"}, s TEXT NOT NULL, s_type TEXT NOT NULL, p TEXT NOT NULL, o TEXT NOT NULL, o_type TEXT NOT NULL, o_datatype TEXT, o_lang TEXT, g TEXT NOT NULL, g_type TEXT NOT NULL, derived INTEGER NOT NULL DEFAULT 0${this.worldId ? ", world_id TEXT NOT NULL, PRIMARY KEY (world_id, quad_id)" : ""})`;
|
|
64
|
+
}
|
|
65
|
+
buildD1ChunksTable() {
|
|
66
|
+
return `CREATE TABLE IF NOT EXISTS chunks (chunk_id INTEGER PRIMARY KEY AUTOINCREMENT, quad_id TEXT NOT NULL, subject TEXT NOT NULL, predicate TEXT NOT NULL, graph TEXT NOT NULL, value TEXT NOT NULL, fts_value TEXT NOT NULL, vector F32_BLOB(${this.vectorDimensions})${this.worldId ? ", world_id TEXT NOT NULL" : ""})`;
|
|
67
|
+
}
|
|
68
|
+
buildD1ChunksQuadIdIndex() {
|
|
69
|
+
return buildChunksQuadIdIndex();
|
|
70
|
+
}
|
|
71
|
+
buildD1ChunksFtsTable() {
|
|
72
|
+
return `CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
|
|
73
|
+
fts_value,
|
|
74
|
+
content='chunks',
|
|
75
|
+
content_rowid='chunk_id'
|
|
76
|
+
)`;
|
|
77
|
+
}
|
|
78
|
+
buildD1ChunksTriggers() {
|
|
79
|
+
return [`CREATE TRIGGER IF NOT EXISTS chunks_ai AFTER INSERT ON chunks BEGIN
|
|
80
|
+
INSERT INTO chunks_fts(rowid, fts_value) VALUES (new.chunk_id, new.fts_value);
|
|
81
|
+
END;`, `CREATE TRIGGER IF NOT EXISTS chunks_ad AFTER DELETE ON chunks BEGIN
|
|
82
|
+
INSERT INTO chunks_fts(chunks_fts, rowid, fts_value) VALUES('delete', old.chunk_id, old.fts_value);
|
|
83
|
+
END;`];
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
export { validateWorldId as n, D1SchemaBuilder as t };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* D1SchemaBuilder exposes DDL helpers bound to a single vector dimension for
|
|
3
|
+
* D1 schema initialization. It mirrors the libsql reference shape (10-column
|
|
4
|
+
* `quads` table + 7 covering indexes + `chunks` + FTS5 external-content
|
|
5
|
+
* `chunks_fts`) but D1-safe: no loadable extensions, so the `chunks.vector`
|
|
6
|
+
* column stays a plain `F32_BLOB(dim)` and the vector signal lives outside
|
|
7
|
+
* D1 (Vectorize). FTS5 external-content tables and sync triggers are
|
|
8
|
+
* supported on D1.
|
|
9
|
+
*/
|
|
10
|
+
interface D1SchemaBuilderOptions {
|
|
11
|
+
worldId?: string;
|
|
12
|
+
/** provenance adds the `provenance` table; an existing database gains it on the next ensureSchema. */
|
|
13
|
+
provenance?: boolean;
|
|
14
|
+
}
|
|
15
|
+
declare class D1SchemaBuilder {
|
|
16
|
+
readonly vectorDimensions: number;
|
|
17
|
+
readonly worldId?: string;
|
|
18
|
+
readonly provenance: boolean;
|
|
19
|
+
constructor(vectorDimensions: number, options?: D1SchemaBuilderOptions);
|
|
20
|
+
/**
|
|
21
|
+
* buildTables returns the idempotent DDL that creates the quads and chunks
|
|
22
|
+
* tables in dependency order.
|
|
23
|
+
*/
|
|
24
|
+
buildTables(): string[];
|
|
25
|
+
/**
|
|
26
|
+
* buildIndexes returns DDL for 7 covering composite indexes on the quads table
|
|
27
|
+
* (six subject-predicate-object-graph index orders + GPSO for graph-scoped access) enabling any quad pattern
|
|
28
|
+
* to be resolved via a single index seek.
|
|
29
|
+
*/
|
|
30
|
+
buildIndexes(): string[];
|
|
31
|
+
/**
|
|
32
|
+
* buildD1QuadsTable creates the quads table. `derived` is 0 for an asserted
|
|
33
|
+
* quad and 1 for a quad materialized by inference; a quad that is both
|
|
34
|
+
* asserted and derived is stored once, as asserted.
|
|
35
|
+
*/
|
|
36
|
+
buildD1QuadsTable(): string;
|
|
37
|
+
buildD1ChunksTable(): string;
|
|
38
|
+
buildD1ChunksQuadIdIndex(): string;
|
|
39
|
+
buildD1ChunksFtsTable(): string;
|
|
40
|
+
buildD1ChunksTriggers(): string[];
|
|
41
|
+
}
|
|
42
|
+
export { D1SchemaBuilderOptions as n, D1SchemaBuilder as t };
|