@vultro/docstore-sqlite 0.0.0-stage → 0.0.2

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,9 @@
1
+ import { type DocStoreBackend } from "@vultro/core/docstore";
2
+ /**
3
+ * SQLite 文档存储选择器(纯配置,不 import 运行时类)。
4
+ *
5
+ * 具体实现由 `@vultro/docstore-sqlite/runtime` 注册;生成入口会同时 import
6
+ * 选择器与该子路径,避免 `vultro.config.ts` 在 Node 的 strip-only TS 加载器
7
+ * 下解析 core 的运行时代码。
8
+ */
9
+ export declare function sqliteStore(): DocStoreBackend;
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ import { resolveDocStoreCreator } from "@vultro/core/docstore";
2
+ // src/index.ts
3
+ /**
4
+ * SQLite 文档存储选择器(纯配置,不 import 运行时类)。
5
+ *
6
+ * 具体实现由 `@vultro/docstore-sqlite/runtime` 注册;生成入口会同时 import
7
+ * 选择器与该子路径,避免 `vultro.config.ts` 在 Node 的 strip-only TS 加载器
8
+ * 下解析 core 的运行时代码。
9
+ */
10
+ function sqliteStore() {
11
+ return {
12
+ name: "sqlite",
13
+ runtimes: [
14
+ "cloudflare",
15
+ "cloud",
16
+ "bun",
17
+ "node"
18
+ ],
19
+ module: "@vultro/docstore-sqlite",
20
+ exportName: "sqliteStore",
21
+ create(runtime, context) {
22
+ return resolveDocStoreCreator("sqlite")(runtime, context);
23
+ }
24
+ };
25
+ }
26
+ export { sqliteStore };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ import { AsyncCachedDocumentStore } from "@vultro/core";
2
+ import { registerDocStore } from "@vultro/core/docstore";
3
+ import { DocumentStore } from "./store.js";
4
+ // src/runtime.ts
5
+ /**
6
+ * SQLite 文档存储实现。
7
+ *
8
+ * - Cloudflare 同步 DO SQLite:`DocumentStore(sql, schema)`;
9
+ * - Bun / Node 的异步 SQLite 适配器:`AsyncCachedDocumentStore(schema, d1)`。
10
+ */
11
+ registerDocStore("sqlite", (_runtime, context) => {
12
+ if (context.d1) return new AsyncCachedDocumentStore(context.schema, context.d1);
13
+ if (context.sql) return new DocumentStore(context.sql, context.schema);
14
+ throw new Error("sqliteStore requires a SQL or D1 database");
15
+ });
@@ -0,0 +1,161 @@
1
+ /**
2
+ * ============================================================================
3
+ * SQLite 文档存储实现(`@vultro/docstore-sqlite`)
4
+ * ============================================================================
5
+ *
6
+ * 这是 `@vultro/core` 的默认文档存储引擎,代码归属 SQLite 后端包;core 只
7
+ * 定义 `DocumentStore` 接口与查询 / 事务构建器,通过 `@vultro/core/database`
8
+ * 重新导出本类以保持兼容。
9
+ *
10
+ * 依赖 core 的 schema 解析、值编码、搜索 / 向量索引和最小 SQL 接口;这些
11
+ * 都是平台无关的共享模块,不包含任何运行时适配代码。
12
+ */
13
+ import { type IndexInfo, type SchemaInfo, type SearchIndexInfo, type TableInfo, type VectorIndexInfo } from "@vultro/core/schema-info";
14
+ import type { SqlExecutor } from "@vultro/core/sql";
15
+ /** 运行时中的文档形状:Convex 文档 = 用户字段 + `_id` + `_creationTime`。 */
16
+ export interface Doc {
17
+ _id: string;
18
+ _creationTime: number;
19
+ [key: string]: unknown;
20
+ }
21
+ /** 一次待提交的文档写入。patch 在事务内已经合并成完整的 put。 */
22
+ export type PendingWrite = {
23
+ kind: "put";
24
+ tableNumber: number;
25
+ id: string;
26
+ doc: Doc;
27
+ before?: Doc;
28
+ } | {
29
+ kind: "delete";
30
+ tableNumber: number;
31
+ id: string;
32
+ before: Doc;
33
+ };
34
+ /** 一条文档变更历史。 */
35
+ export interface HistoryEntry {
36
+ seq: number;
37
+ commitTs: number;
38
+ tableNumber: number;
39
+ tableName: string;
40
+ docId: string;
41
+ op: "insert" | "update" | "delete";
42
+ before: unknown;
43
+ after: unknown;
44
+ }
45
+ export declare class DocumentStore {
46
+ private readonly sql;
47
+ private readonly schema;
48
+ private commitTimestamp;
49
+ private initialized;
50
+ constructor(sql: SqlExecutor, schema: SchemaInfo);
51
+ /**
52
+ * 初始化数据库:建表、分配稳定的表号、补建索引。
53
+ *
54
+ * 该方法必须幂等:Durable Object 可能在任意时刻重新启动,
55
+ * 每次构造都会执行一次 `initialize()`,但不能破坏已有数据。
56
+ */
57
+ initialize(): void;
58
+ /**
59
+ * 运行时创建一张动态表(官方 dashboard 的 Create Table)。
60
+ *
61
+ * 表定义只包含虚拟索引,文档不经过 schema validator;持久化在
62
+ * `_vultro_tables`,重启后 `initialize()` 会自动恢复。
63
+ */
64
+ createTable(name: string): TableInfo;
65
+ /** 当前最新提交时间戳。 */
66
+ get commitTs(): number;
67
+ /**
68
+ * 为下一次 mutation 预留提交时间戳。
69
+ *
70
+ * 使用 `max(上一次 + 1, 当前时间)` 而不是单纯 `Date.now()`:
71
+ * - 同一毫秒内连续提交也能得到严格递增的版本号;
72
+ * - 同步协议要求版本号单调,否则客户端会认为数据“倒流”。
73
+ */
74
+ nextCommitTs(): number;
75
+ getTable(name: string): TableInfo;
76
+ getTableByNumber(number: number): TableInfo | undefined;
77
+ /** 按表名查找表;不存在时返回 undefined(校验器用它做软检查)。 */
78
+ findTable(name: string): TableInfo | undefined;
79
+ /** 读取单个已提交文档;不存在时返回 null。 */
80
+ get(table: TableInfo, id: string): Doc | null;
81
+ /** 统计表内文档数量(dashboard / analytics 使用)。 */
82
+ count(table: TableInfo): number;
83
+ /**
84
+ * 文档变更历史(dashboard History 页)。
85
+ *
86
+ * `before` / `after` 使用与 dashboard 表数据相同的 Convex JSON 编码,
87
+ * 前端可以直接展示。
88
+ */
89
+ listHistory(options?: {
90
+ limit?: number;
91
+ offset?: number;
92
+ table?: string;
93
+ op?: "insert" | "update" | "delete";
94
+ docId?: string;
95
+ minTime?: number;
96
+ maxTime?: number;
97
+ }): {
98
+ entries: HistoryEntry[];
99
+ total: number;
100
+ limit: number;
101
+ offset: number;
102
+ };
103
+ countHistory(): number;
104
+ /** 扫描整张表(按创建时间排序)。 */
105
+ scan(table: TableInfo): Doc[];
106
+ /**
107
+ * 通过索引找到与某个字段值相等的文档 ID 集合。
108
+ *
109
+ * 注意:这里只负责「等值」候选集;范围条件与排序会在查询执行器里
110
+ * 用 Convex 的值比较规则完成,保证 null / number / string / bytes
111
+ * 的排序语义与 Convex 一致。
112
+ */
113
+ findIndexDocIds(table: TableInfo, index: IndexInfo, field: string, value: unknown): Set<string>;
114
+ /** 取出某个索引下的所有文档 ID(用于没有等值条件、只有范围条件的查询)。 */
115
+ allIndexDocIds(table: TableInfo, index: IndexInfo): Set<string>;
116
+ /**
117
+ * 原子提交一批写入。
118
+ *
119
+ * 优先使用 Durable Object 提供的 `transactionSync`;测试适配器则退化为
120
+ * 标准 SQL `BEGIN IMMEDIATE / COMMIT / ROLLBACK`。
121
+ */
122
+ commit(writes: Iterable<PendingWrite>, timestamp: number): void;
123
+ /** 删除一条文档在所有搜索索引中的条目。 */
124
+ private deleteSearchEntries;
125
+ /** 写入一条文档的搜索文本、token 和 filter 条目。 */
126
+ private insertSearchEntry;
127
+ /**
128
+ * 确保搜索索引与 schema 声明一致。
129
+ *
130
+ * 搜索字段或 filterFields 变化时清空并重建;否则保留已有倒排表。
131
+ */
132
+ private ensureSearchIndex;
133
+ /**
134
+ * 通过倒排索引查候选文档 ID。
135
+ *
136
+ * 返回 null 表示索引元数据不存在(例如刚升级 schema 尚未补建),调用方
137
+ * 应回退到文档扫描,保证正确性。
138
+ */
139
+ searchDocIds(table: TableInfo, index: SearchIndexInfo, tokens: string[], filters: Array<{
140
+ field: string;
141
+ valueJson: string;
142
+ }>): Set<string> | null;
143
+ /** 删除一条文档在所有向量索引中的条目。 */
144
+ private deleteVectorEntries;
145
+ /** 写入一条文档的向量条目;字段缺失或维度不符时跳过。 */
146
+ private insertVectorEntry;
147
+ /** 确保向量索引与 schema 声明一致;维度或字段变化时重建。 */
148
+ private ensureVectorIndex;
149
+ /**
150
+ * 读取持久化向量条目;返回 null 表示索引尚未建立,调用方回退到扫描。
151
+ */
152
+ vectorEntries(table: TableInfo, index: VectorIndexInfo): Array<{
153
+ docId: string;
154
+ vector: number[];
155
+ bytes: number;
156
+ }> | null;
157
+ /** 如果索引不存在或字段定义变化,重建索引条目。 */
158
+ private ensureIndex;
159
+ }
160
+ /** 读取索引字段;系统字段直接从文档上取。 */
161
+ export declare function fieldValue(doc: Doc, field: string): unknown;
package/dist/store.js ADDED
@@ -0,0 +1,583 @@
1
+ import { convexToJson, jsonToConvex } from "@vultro/core/values";
2
+ import { getTable } from "@vultro/core/schema-info";
3
+ import { decodeVector, documentVector, encodeVector, vectorBytes } from "@vultro/core/vector";
4
+ import "@vultro/core/id-codec";
5
+ import { searchEntryFor, searchTokenPrefixUpperBound } from "@vultro/core/search";
6
+ // src/store.ts
7
+ /**
8
+ * ============================================================================
9
+ * SQLite 文档存储实现(`@vultro/docstore-sqlite`)
10
+ * ============================================================================
11
+ *
12
+ * 这是 `@vultro/core` 的默认文档存储引擎,代码归属 SQLite 后端包;core 只
13
+ * 定义 `DocumentStore` 接口与查询 / 事务构建器,通过 `@vultro/core/database`
14
+ * 重新导出本类以保持兼容。
15
+ *
16
+ * 依赖 core 的 schema 解析、值编码、搜索 / 向量索引和最小 SQL 接口;这些
17
+ * 都是平台无关的共享模块,不包含任何运行时适配代码。
18
+ */
19
+ function rowToHistory(row) {
20
+ return {
21
+ seq: Number(row.seq),
22
+ commitTs: Number(row.commit_ts),
23
+ tableNumber: Number(row.table_number),
24
+ tableName: row.table_name,
25
+ docId: row.doc_id,
26
+ op: row.op === "insert" || row.op === "delete" ? row.op : "update",
27
+ before: row.before_json ? JSON.parse(row.before_json) : null,
28
+ after: row.after_json ? JSON.parse(row.after_json) : null
29
+ };
30
+ }
31
+ var META_COMMIT_TS = "commit_ts";
32
+ /** 动态表的默认虚拟索引;与 readSchema 的规则保持一致。 */
33
+ function virtualIndexes() {
34
+ return /* @__PURE__ */ new Map([["by_creation_time", {
35
+ name: "by_creation_time",
36
+ fields: ["_creationTime"],
37
+ virtual: true
38
+ }], ["by_id", {
39
+ name: "by_id",
40
+ fields: ["_id"],
41
+ virtual: true
42
+ }]]);
43
+ }
44
+ var DocumentStore = class {
45
+ sql;
46
+ schema;
47
+ commitTimestamp = 0;
48
+ initialized = false;
49
+ constructor(sql, schema) {
50
+ this.sql = sql;
51
+ this.schema = schema;
52
+ }
53
+ /**
54
+ * 初始化数据库:建表、分配稳定的表号、补建索引。
55
+ *
56
+ * 该方法必须幂等:Durable Object 可能在任意时刻重新启动,
57
+ * 每次构造都会执行一次 `initialize()`,但不能破坏已有数据。
58
+ */
59
+ initialize() {
60
+ if (this.initialized) return;
61
+ this.sql.exec(`
62
+ CREATE TABLE IF NOT EXISTS _vultro_meta (
63
+ key TEXT PRIMARY KEY,
64
+ value TEXT NOT NULL
65
+ )
66
+ `);
67
+ this.sql.exec(`
68
+ CREATE TABLE IF NOT EXISTS _vultro_tables (
69
+ name TEXT PRIMARY KEY,
70
+ number INTEGER NOT NULL UNIQUE,
71
+ created_at REAL NOT NULL
72
+ )
73
+ `);
74
+ this.sql.exec(`
75
+ CREATE TABLE IF NOT EXISTS _vultro_documents (
76
+ table_number INTEGER NOT NULL,
77
+ id TEXT NOT NULL,
78
+ creation_time REAL NOT NULL,
79
+ data TEXT NOT NULL,
80
+ PRIMARY KEY (table_number, id)
81
+ )
82
+ `);
83
+ this.sql.exec(`
84
+ CREATE INDEX IF NOT EXISTS _vultro_documents_creation
85
+ ON _vultro_documents (table_number, creation_time, id)
86
+ `);
87
+ this.sql.exec(`
88
+ CREATE TABLE IF NOT EXISTS _vultro_index_entries (
89
+ table_number INTEGER NOT NULL,
90
+ index_name TEXT NOT NULL,
91
+ doc_id TEXT NOT NULL,
92
+ field TEXT NOT NULL,
93
+ value_json TEXT NOT NULL,
94
+ PRIMARY KEY (table_number, index_name, doc_id, field)
95
+ )
96
+ `);
97
+ this.sql.exec(`
98
+ CREATE INDEX IF NOT EXISTS _vultro_index_lookup
99
+ ON _vultro_index_entries (table_number, index_name, field, value_json, doc_id)
100
+ `);
101
+ this.sql.exec(`
102
+ CREATE TABLE IF NOT EXISTS _vultro_index_meta (
103
+ table_number INTEGER NOT NULL,
104
+ index_name TEXT NOT NULL,
105
+ fields_json TEXT NOT NULL,
106
+ PRIMARY KEY (table_number, index_name)
107
+ )
108
+ `);
109
+ this.sql.exec(`
110
+ CREATE TABLE IF NOT EXISTS _vultro_search_docs (
111
+ table_number INTEGER NOT NULL,
112
+ index_name TEXT NOT NULL,
113
+ doc_id TEXT NOT NULL,
114
+ search_text TEXT NOT NULL,
115
+ PRIMARY KEY (table_number, index_name, doc_id)
116
+ )
117
+ `);
118
+ this.sql.exec(`
119
+ CREATE TABLE IF NOT EXISTS _vultro_search_tokens (
120
+ table_number INTEGER NOT NULL,
121
+ index_name TEXT NOT NULL,
122
+ doc_id TEXT NOT NULL,
123
+ token TEXT NOT NULL,
124
+ PRIMARY KEY (table_number, index_name, doc_id, token)
125
+ )
126
+ `);
127
+ this.sql.exec(`
128
+ CREATE INDEX IF NOT EXISTS _vultro_search_token_lookup
129
+ ON _vultro_search_tokens (table_number, index_name, token, doc_id)
130
+ `);
131
+ this.sql.exec(`
132
+ CREATE TABLE IF NOT EXISTS _vultro_search_filters (
133
+ table_number INTEGER NOT NULL,
134
+ index_name TEXT NOT NULL,
135
+ doc_id TEXT NOT NULL,
136
+ field TEXT NOT NULL,
137
+ value_json TEXT NOT NULL,
138
+ PRIMARY KEY (table_number, index_name, doc_id, field)
139
+ )
140
+ `);
141
+ this.sql.exec(`
142
+ CREATE INDEX IF NOT EXISTS _vultro_search_filter_lookup
143
+ ON _vultro_search_filters (table_number, index_name, field, value_json, doc_id)
144
+ `);
145
+ this.sql.exec(`
146
+ CREATE TABLE IF NOT EXISTS _vultro_search_meta (
147
+ table_number INTEGER NOT NULL,
148
+ index_name TEXT NOT NULL,
149
+ search_field TEXT NOT NULL,
150
+ filter_fields_json TEXT NOT NULL,
151
+ PRIMARY KEY (table_number, index_name)
152
+ )
153
+ `);
154
+ this.sql.exec(`
155
+ CREATE TABLE IF NOT EXISTS _vultro_vector_entries (
156
+ table_number INTEGER NOT NULL,
157
+ index_name TEXT NOT NULL,
158
+ doc_id TEXT NOT NULL,
159
+ vector_json TEXT NOT NULL,
160
+ PRIMARY KEY (table_number, index_name, doc_id)
161
+ )
162
+ `);
163
+ this.sql.exec(`
164
+ CREATE TABLE IF NOT EXISTS _vultro_vector_meta (
165
+ table_number INTEGER NOT NULL,
166
+ index_name TEXT NOT NULL,
167
+ vector_field TEXT NOT NULL,
168
+ dimensions INTEGER NOT NULL,
169
+ filter_fields_json TEXT NOT NULL,
170
+ PRIMARY KEY (table_number, index_name)
171
+ )
172
+ `);
173
+ this.sql.exec(`
174
+ CREATE TABLE IF NOT EXISTS _vultro_history (
175
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
176
+ commit_ts REAL NOT NULL,
177
+ table_number INTEGER NOT NULL,
178
+ table_name TEXT NOT NULL,
179
+ doc_id TEXT NOT NULL,
180
+ op TEXT NOT NULL,
181
+ before_json TEXT,
182
+ after_json TEXT
183
+ )
184
+ `);
185
+ this.sql.exec(`
186
+ CREATE INDEX IF NOT EXISTS _vultro_history_commit
187
+ ON _vultro_history (commit_ts DESC, seq DESC)
188
+ `);
189
+ const metaRows = this.sql.exec(`SELECT value FROM _vultro_meta WHERE key = ?`, META_COMMIT_TS);
190
+ if (metaRows[0]) this.commitTimestamp = Number(metaRows[0].value);
191
+ else {
192
+ this.commitTimestamp = Date.now();
193
+ this.sql.exec(`INSERT INTO _vultro_meta (key, value) VALUES (?, ?)`, META_COMMIT_TS, String(this.commitTimestamp));
194
+ }
195
+ const existingRows = this.sql.exec(`SELECT name, number FROM _vultro_tables`);
196
+ const existing = new Map(existingRows.map((row) => [row.name, row.number]));
197
+ for (const row of existingRows) {
198
+ if (this.schema.tables.has(row.name)) continue;
199
+ this.schema.tables.set(row.name, {
200
+ name: row.name,
201
+ number: Number(row.number),
202
+ indexes: virtualIndexes()
203
+ });
204
+ this.schema.order.push(row.name);
205
+ }
206
+ let nextNumber = Math.max(0, ...existing.values()) + 1;
207
+ for (const tableName of this.schema.order) {
208
+ const table = this.schema.tables.get(tableName);
209
+ let number = existing.get(tableName);
210
+ if (number === void 0) {
211
+ number = nextNumber++;
212
+ this.sql.exec(`INSERT INTO _vultro_tables (name, number, created_at) VALUES (?, ?, ?)`, tableName, number, Date.now());
213
+ }
214
+ table.number = number;
215
+ }
216
+ for (const table of this.schema.tables.values()) {
217
+ for (const index of table.indexes.values()) {
218
+ if (index.virtual) continue;
219
+ this.ensureIndex(table, index);
220
+ }
221
+ for (const index of table.searchIndexes?.values() ?? []) this.ensureSearchIndex(table, index);
222
+ for (const index of table.vectorIndexes?.values() ?? []) this.ensureVectorIndex(table, index);
223
+ }
224
+ this.initialized = true;
225
+ }
226
+ /**
227
+ * 运行时创建一张动态表(官方 dashboard 的 Create Table)。
228
+ *
229
+ * 表定义只包含虚拟索引,文档不经过 schema validator;持久化在
230
+ * `_vultro_tables`,重启后 `initialize()` 会自动恢复。
231
+ */
232
+ createTable(name) {
233
+ const tableName = name.trim();
234
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(tableName)) throw new Error(`Invalid table name "${name}"`);
235
+ const existing = this.schema.tables.get(tableName);
236
+ if (existing) return existing;
237
+ const number = Math.max(0, ...[...this.schema.tables.values()].map((table) => table.number)) + 1;
238
+ const table = {
239
+ name: tableName,
240
+ number,
241
+ indexes: virtualIndexes()
242
+ };
243
+ this.schema.tables.set(tableName, table);
244
+ this.schema.order.push(tableName);
245
+ this.sql.exec(`INSERT OR IGNORE INTO _vultro_tables (name, number, created_at) VALUES (?, ?, ?)`, tableName, number, Date.now());
246
+ return table;
247
+ }
248
+ /** 当前最新提交时间戳。 */
249
+ get commitTs() {
250
+ return this.commitTimestamp;
251
+ }
252
+ /**
253
+ * 为下一次 mutation 预留提交时间戳。
254
+ *
255
+ * 使用 `max(上一次 + 1, 当前时间)` 而不是单纯 `Date.now()`:
256
+ * - 同一毫秒内连续提交也能得到严格递增的版本号;
257
+ * - 同步协议要求版本号单调,否则客户端会认为数据“倒流”。
258
+ */
259
+ nextCommitTs() {
260
+ this.commitTimestamp = Math.max(this.commitTimestamp + 1, Date.now());
261
+ return this.commitTimestamp;
262
+ }
263
+ getTable(name) {
264
+ return getTable(this.schema, name);
265
+ }
266
+ getTableByNumber(number) {
267
+ for (const table of this.schema.tables.values()) if (table.number === number) return table;
268
+ }
269
+ /** 按表名查找表;不存在时返回 undefined(校验器用它做软检查)。 */
270
+ findTable(name) {
271
+ return this.schema.tables.get(name);
272
+ }
273
+ /** 读取单个已提交文档;不存在时返回 null。 */
274
+ get(table, id) {
275
+ const row = this.sql.exec(`SELECT id, creation_time, data FROM _vultro_documents
276
+ WHERE table_number = ? AND id = ?`, table.number, id)[0];
277
+ if (!row) return null;
278
+ return {
279
+ ...jsonToConvex(JSON.parse(row.data)),
280
+ _id: row.id,
281
+ _creationTime: row.creation_time
282
+ };
283
+ }
284
+ /** 统计表内文档数量(dashboard / analytics 使用)。 */
285
+ count(table) {
286
+ const rows = this.sql.exec(`SELECT COUNT(*) AS count FROM _vultro_documents WHERE table_number = ?`, table.number);
287
+ return Number(rows[0]?.count ?? 0);
288
+ }
289
+ /**
290
+ * 文档变更历史(dashboard History 页)。
291
+ *
292
+ * `before` / `after` 使用与 dashboard 表数据相同的 Convex JSON 编码,
293
+ * 前端可以直接展示。
294
+ */
295
+ listHistory(options = {}) {
296
+ const where = [];
297
+ const params = [];
298
+ if (options.table) {
299
+ where.push("table_name = ?");
300
+ params.push(options.table);
301
+ }
302
+ if (options.op) {
303
+ where.push("op = ?");
304
+ params.push(options.op);
305
+ }
306
+ if (options.docId) {
307
+ where.push("doc_id = ?");
308
+ params.push(options.docId);
309
+ }
310
+ if (options.minTime !== void 0) {
311
+ where.push("commit_ts >= ?");
312
+ params.push(options.minTime);
313
+ }
314
+ if (options.maxTime !== void 0) {
315
+ where.push("commit_ts <= ?");
316
+ params.push(options.maxTime);
317
+ }
318
+ const whereSql = where.length > 0 ? `WHERE ${where.join(" AND ")}` : "";
319
+ const totalRows = this.sql.exec(`SELECT COUNT(*) AS total FROM _vultro_history ${whereSql}`, ...params);
320
+ const total = Number(totalRows[0]?.total ?? 0);
321
+ const limit = Math.max(1, Math.min(options.limit ?? 50, 200));
322
+ const offset = Math.max(0, options.offset ?? 0);
323
+ return {
324
+ entries: this.sql.exec(`SELECT * FROM _vultro_history ${whereSql}
325
+ ORDER BY commit_ts DESC, seq DESC
326
+ LIMIT ? OFFSET ?`, ...params, limit, offset).map(rowToHistory),
327
+ total,
328
+ limit,
329
+ offset
330
+ };
331
+ }
332
+ countHistory() {
333
+ const rows = this.sql.exec(`SELECT COUNT(*) AS total FROM _vultro_history`);
334
+ return Number(rows[0]?.total ?? 0);
335
+ }
336
+ /** 扫描整张表(按创建时间排序)。 */
337
+ scan(table) {
338
+ return this.sql.exec(`SELECT id, creation_time, data FROM _vultro_documents
339
+ WHERE table_number = ?`, table.number).map((row) => ({
340
+ ...jsonToConvex(JSON.parse(row.data)),
341
+ _id: row.id,
342
+ _creationTime: row.creation_time
343
+ }));
344
+ }
345
+ /**
346
+ * 通过索引找到与某个字段值相等的文档 ID 集合。
347
+ *
348
+ * 注意:这里只负责「等值」候选集;范围条件与排序会在查询执行器里
349
+ * 用 Convex 的值比较规则完成,保证 null / number / string / bytes
350
+ * 的排序语义与 Convex 一致。
351
+ */
352
+ findIndexDocIds(table, index, field, value) {
353
+ const encoded = JSON.stringify(convexToJson(value === void 0 ? null : value));
354
+ const rows = this.sql.exec(`SELECT doc_id FROM _vultro_index_entries
355
+ WHERE table_number = ? AND index_name = ? AND field = ? AND value_json = ?`, table.number, index.name, field, encoded);
356
+ return new Set(rows.map((row) => row.doc_id));
357
+ }
358
+ /** 取出某个索引下的所有文档 ID(用于没有等值条件、只有范围条件的查询)。 */
359
+ allIndexDocIds(table, index) {
360
+ const rows = this.sql.exec(`SELECT doc_id FROM _vultro_index_entries
361
+ WHERE table_number = ? AND index_name = ?`, table.number, index.name);
362
+ return new Set(rows.map((row) => row.doc_id));
363
+ }
364
+ /**
365
+ * 原子提交一批写入。
366
+ *
367
+ * 优先使用 Durable Object 提供的 `transactionSync`;测试适配器则退化为
368
+ * 标准 SQL `BEGIN IMMEDIATE / COMMIT / ROLLBACK`。
369
+ */
370
+ commit(writes, timestamp) {
371
+ const writeList = [...writes];
372
+ const apply = () => {
373
+ for (const write of writeList) {
374
+ if (write.kind === "delete") {
375
+ this.sql.exec(`DELETE FROM _vultro_documents WHERE table_number = ? AND id = ?`, write.tableNumber, write.id);
376
+ this.sql.exec(`DELETE FROM _vultro_index_entries WHERE table_number = ? AND doc_id = ?`, write.tableNumber, write.id);
377
+ const deleteTable = this.getTableByNumber(write.tableNumber);
378
+ if (deleteTable) {
379
+ this.deleteSearchEntries(deleteTable, write.id);
380
+ this.deleteVectorEntries(deleteTable, write.id);
381
+ }
382
+ continue;
383
+ }
384
+ const table = this.getTableByNumber(write.tableNumber);
385
+ const data = JSON.stringify(convexToJson(write.doc));
386
+ this.sql.exec(`INSERT INTO _vultro_documents (table_number, id, creation_time, data)
387
+ VALUES (?, ?, ?, ?)
388
+ ON CONFLICT (table_number, id) DO UPDATE SET
389
+ creation_time = excluded.creation_time,
390
+ data = excluded.data`, write.tableNumber, write.id, write.doc._creationTime, data);
391
+ this.sql.exec(`DELETE FROM _vultro_index_entries WHERE table_number = ? AND doc_id = ?`, write.tableNumber, write.id);
392
+ if (table) {
393
+ this.deleteSearchEntries(table, write.id);
394
+ this.deleteVectorEntries(table, write.id);
395
+ for (const index of table.searchIndexes?.values() ?? []) this.insertSearchEntry(table, index, write.doc);
396
+ for (const index of table.vectorIndexes?.values() ?? []) this.insertVectorEntry(table, index, write.doc);
397
+ for (const index of table.indexes.values()) {
398
+ if (index.virtual) continue;
399
+ for (const field of index.fields) this.sql.exec(`INSERT INTO _vultro_index_entries
400
+ (table_number, index_name, doc_id, field, value_json)
401
+ VALUES (?, ?, ?, ?, ?)`, write.tableNumber, index.name, write.id, field, JSON.stringify(convexToJson(fieldValue(write.doc, field) ?? null)));
402
+ }
403
+ }
404
+ }
405
+ for (const write of writeList) {
406
+ const table = this.getTableByNumber(write.tableNumber);
407
+ const op = write.kind === "put" ? write.before ? "update" : "insert" : "delete";
408
+ this.sql.exec(`INSERT INTO _vultro_history
409
+ (commit_ts, table_number, table_name, doc_id, op, before_json, after_json)
410
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, timestamp, write.tableNumber, table?.name ?? String(write.tableNumber), write.id, op, write.before ? JSON.stringify(convexToJson(write.before)) : null, write.kind === "put" ? JSON.stringify(convexToJson(write.doc)) : null);
411
+ }
412
+ const historyCount = Number(this.sql.exec(`SELECT COUNT(*) AS total FROM _vultro_history`)[0]?.total ?? 0);
413
+ if (historyCount > 2e4) this.sql.exec(`DELETE FROM _vultro_history WHERE seq IN (
414
+ SELECT seq FROM _vultro_history ORDER BY seq ASC LIMIT ?
415
+ )`, historyCount - 2e4);
416
+ this.sql.exec(`INSERT INTO _vultro_meta (key, value) VALUES (?, ?)
417
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value`, META_COMMIT_TS, String(timestamp));
418
+ };
419
+ if (this.sql.transactionSync) this.sql.transactionSync(apply);
420
+ else {
421
+ this.sql.exec("BEGIN IMMEDIATE");
422
+ try {
423
+ apply();
424
+ this.sql.exec("COMMIT");
425
+ } catch (error) {
426
+ this.sql.exec("ROLLBACK");
427
+ throw error;
428
+ }
429
+ }
430
+ this.commitTimestamp = timestamp;
431
+ }
432
+ /** 删除一条文档在所有搜索索引中的条目。 */
433
+ deleteSearchEntries(table, docId) {
434
+ for (const index of table.searchIndexes?.values() ?? []) {
435
+ this.sql.exec(`DELETE FROM _vultro_search_docs
436
+ WHERE table_number = ? AND index_name = ? AND doc_id = ?`, table.number, index.name, docId);
437
+ this.sql.exec(`DELETE FROM _vultro_search_tokens
438
+ WHERE table_number = ? AND index_name = ? AND doc_id = ?`, table.number, index.name, docId);
439
+ this.sql.exec(`DELETE FROM _vultro_search_filters
440
+ WHERE table_number = ? AND index_name = ? AND doc_id = ?`, table.number, index.name, docId);
441
+ }
442
+ }
443
+ /** 写入一条文档的搜索文本、token 和 filter 条目。 */
444
+ insertSearchEntry(table, index, doc) {
445
+ const entry = searchEntryFor(index, doc);
446
+ this.sql.exec(`INSERT OR REPLACE INTO _vultro_search_docs
447
+ (table_number, index_name, doc_id, search_text)
448
+ VALUES (?, ?, ?, ?)`, table.number, index.name, doc._id, entry.text);
449
+ for (const token of entry.tokens) this.sql.exec(`INSERT OR REPLACE INTO _vultro_search_tokens
450
+ (table_number, index_name, doc_id, token)
451
+ VALUES (?, ?, ?, ?)`, table.number, index.name, doc._id, token);
452
+ for (const filter of entry.filters) this.sql.exec(`INSERT OR REPLACE INTO _vultro_search_filters
453
+ (table_number, index_name, doc_id, field, value_json)
454
+ VALUES (?, ?, ?, ?, ?)`, table.number, index.name, doc._id, filter.field, filter.valueJson);
455
+ }
456
+ /**
457
+ * 确保搜索索引与 schema 声明一致。
458
+ *
459
+ * 搜索字段或 filterFields 变化时清空并重建;否则保留已有倒排表。
460
+ */
461
+ ensureSearchIndex(table, index) {
462
+ const filterFieldsJson = JSON.stringify(index.filterFields);
463
+ const meta = this.sql.exec(`SELECT search_field, filter_fields_json FROM _vultro_search_meta
464
+ WHERE table_number = ? AND index_name = ?`, table.number, index.name)[0];
465
+ if (meta && meta.search_field === index.searchField && meta.filter_fields_json === filterFieldsJson) return;
466
+ this.sql.exec(`DELETE FROM _vultro_search_docs WHERE table_number = ? AND index_name = ?`, table.number, index.name);
467
+ this.sql.exec(`DELETE FROM _vultro_search_tokens WHERE table_number = ? AND index_name = ?`, table.number, index.name);
468
+ this.sql.exec(`DELETE FROM _vultro_search_filters WHERE table_number = ? AND index_name = ?`, table.number, index.name);
469
+ this.sql.exec(`INSERT INTO _vultro_search_meta
470
+ (table_number, index_name, search_field, filter_fields_json)
471
+ VALUES (?, ?, ?, ?)
472
+ ON CONFLICT (table_number, index_name) DO UPDATE SET
473
+ search_field = excluded.search_field,
474
+ filter_fields_json = excluded.filter_fields_json`, table.number, index.name, index.searchField, filterFieldsJson);
475
+ for (const doc of this.scan(table)) this.insertSearchEntry(table, index, doc);
476
+ }
477
+ /**
478
+ * 通过倒排索引查候选文档 ID。
479
+ *
480
+ * 返回 null 表示索引元数据不存在(例如刚升级 schema 尚未补建),调用方
481
+ * 应回退到文档扫描,保证正确性。
482
+ */
483
+ searchDocIds(table, index, tokens, filters) {
484
+ if (!this.sql.exec(`SELECT table_number FROM _vultro_search_meta
485
+ WHERE table_number = ? AND index_name = ?`, table.number, index.name)[0]) return null;
486
+ let ids = null;
487
+ const intersect = (next) => {
488
+ if (ids === null) ids = next;
489
+ else ids = new Set([...ids].filter((id) => next.has(id)));
490
+ };
491
+ if (tokens.length === 0) {
492
+ const rows = this.sql.exec(`SELECT doc_id FROM _vultro_search_docs
493
+ WHERE table_number = ? AND index_name = ?`, table.number, index.name);
494
+ intersect(new Set(rows.map((row) => row.doc_id)));
495
+ } else for (const token of tokens) {
496
+ const rows = this.sql.exec(`SELECT doc_id FROM _vultro_search_tokens
497
+ WHERE table_number = ? AND index_name = ? AND token >= ? AND token < ?`, table.number, index.name, token, searchTokenPrefixUpperBound(token));
498
+ intersect(new Set(rows.map((row) => row.doc_id)));
499
+ }
500
+ for (const filter of filters) {
501
+ const rows = this.sql.exec(`SELECT doc_id FROM _vultro_search_filters
502
+ WHERE table_number = ? AND index_name = ? AND field = ? AND value_json = ?`, table.number, index.name, filter.field, filter.valueJson);
503
+ intersect(new Set(rows.map((row) => row.doc_id)));
504
+ }
505
+ return ids ?? /* @__PURE__ */ new Set();
506
+ }
507
+ /** 删除一条文档在所有向量索引中的条目。 */
508
+ deleteVectorEntries(table, docId) {
509
+ for (const index of table.vectorIndexes?.values() ?? []) this.sql.exec(`DELETE FROM _vultro_vector_entries
510
+ WHERE table_number = ? AND index_name = ? AND doc_id = ?`, table.number, index.name, docId);
511
+ }
512
+ /** 写入一条文档的向量条目;字段缺失或维度不符时跳过。 */
513
+ insertVectorEntry(table, index, doc) {
514
+ const vector = documentVector(index, doc);
515
+ if (!vector) return;
516
+ this.sql.exec(`INSERT OR REPLACE INTO _vultro_vector_entries
517
+ (table_number, index_name, doc_id, vector_json)
518
+ VALUES (?, ?, ?, ?)`, table.number, index.name, doc._id, encodeVector(vector));
519
+ }
520
+ /** 确保向量索引与 schema 声明一致;维度或字段变化时重建。 */
521
+ ensureVectorIndex(table, index) {
522
+ const filterFieldsJson = JSON.stringify(index.filterFields);
523
+ const meta = this.sql.exec(`SELECT vector_field, dimensions, filter_fields_json FROM _vultro_vector_meta
524
+ WHERE table_number = ? AND index_name = ?`, table.number, index.name)[0];
525
+ if (meta && meta.vector_field === index.vectorField && Number(meta.dimensions) === index.dimensions && meta.filter_fields_json === filterFieldsJson) return;
526
+ this.sql.exec(`DELETE FROM _vultro_vector_entries WHERE table_number = ? AND index_name = ?`, table.number, index.name);
527
+ this.sql.exec(`INSERT INTO _vultro_vector_meta
528
+ (table_number, index_name, vector_field, dimensions, filter_fields_json)
529
+ VALUES (?, ?, ?, ?, ?)
530
+ ON CONFLICT (table_number, index_name) DO UPDATE SET
531
+ vector_field = excluded.vector_field,
532
+ dimensions = excluded.dimensions,
533
+ filter_fields_json = excluded.filter_fields_json`, table.number, index.name, index.vectorField, index.dimensions, filterFieldsJson);
534
+ for (const doc of this.scan(table)) this.insertVectorEntry(table, index, doc);
535
+ }
536
+ /**
537
+ * 读取持久化向量条目;返回 null 表示索引尚未建立,调用方回退到扫描。
538
+ */
539
+ vectorEntries(table, index) {
540
+ if (!this.sql.exec(`SELECT table_number FROM _vultro_vector_meta
541
+ WHERE table_number = ? AND index_name = ?`, table.number, index.name)[0]) return null;
542
+ const rows = this.sql.exec(`SELECT doc_id, vector_json FROM _vultro_vector_entries
543
+ WHERE table_number = ? AND index_name = ?`, table.number, index.name);
544
+ const entries = [];
545
+ for (const row of rows) {
546
+ const vector = decodeVector(row.vector_json, index.dimensions);
547
+ if (!vector) continue;
548
+ entries.push({
549
+ docId: row.doc_id,
550
+ vector,
551
+ bytes: vectorBytes(vector)
552
+ });
553
+ }
554
+ return entries;
555
+ }
556
+ /** 如果索引不存在或字段定义变化,重建索引条目。 */
557
+ ensureIndex(table, index) {
558
+ const fieldsJson = JSON.stringify(index.fields);
559
+ const meta = this.sql.exec(`SELECT fields_json FROM _vultro_index_meta
560
+ WHERE table_number = ? AND index_name = ?`, table.number, index.name)[0];
561
+ if (meta && meta.fields_json === fieldsJson) return;
562
+ this.sql.exec(`DELETE FROM _vultro_index_entries WHERE table_number = ? AND index_name = ?`, table.number, index.name);
563
+ this.sql.exec(`INSERT INTO _vultro_index_meta (table_number, index_name, fields_json)
564
+ VALUES (?, ?, ?)
565
+ ON CONFLICT (table_number, index_name) DO UPDATE SET fields_json = excluded.fields_json`, table.number, index.name, fieldsJson);
566
+ const docs = this.scan(table);
567
+ for (const doc of docs) for (const field of index.fields) this.sql.exec(`INSERT OR REPLACE INTO _vultro_index_entries
568
+ (table_number, index_name, doc_id, field, value_json)
569
+ VALUES (?, ?, ?, ?, ?)`, table.number, index.name, doc._id, field, JSON.stringify(convexToJson(fieldValue(doc, field) ?? null)));
570
+ }
571
+ };
572
+ /** 读取索引字段;系统字段直接从文档上取。 */
573
+ function fieldValue(doc, field) {
574
+ if (field === "_id") return doc._id;
575
+ if (field === "_creationTime") return doc._creationTime;
576
+ let current = doc;
577
+ for (const part of field.split(".")) {
578
+ if (current === null || typeof current !== "object") return void 0;
579
+ current = current[part];
580
+ }
581
+ return current;
582
+ }
583
+ export { DocumentStore, fieldValue };
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@vultro/docstore-sqlite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "description": "SQLite document store backend for Vultro",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./runtime": {
13
+ "types": "./dist/runtime.d.ts",
14
+ "import": "./dist/runtime.js",
15
+ "default": "./dist/runtime.js"
16
+ },
17
+ "./store": {
18
+ "types": "./dist/store.d.ts",
19
+ "import": "./dist/store.js",
20
+ "default": "./dist/store.js"
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "@vultro/core": "0.0.2"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "types": "./dist/index.d.ts"
30
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.