tapirus 1.0.1 → 1.0.5
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/CORE_LICENSE +36 -0
- package/LICENSE +21 -0
- package/NOTICE +8 -0
- package/README.md +85 -228
- package/index.d.ts +162 -30
- package/index.js +138 -67
- package/package.json +54 -45
- package/tapirus.darwin-arm64.node +0 -0
- package/tapirus.darwin-x64.node +0 -0
- package/tapirus.linux-arm64-gnu.node +0 -0
- package/tapirus.linux-x64-gnu.node +0 -0
- package/tapirus.win32-x64-msvc.node +0 -0
- package/Cargo.toml +0 -15
- package/build.rs +0 -5
- package/engine.js +0 -507
- package/src/lib.rs +0 -84
- package/test.js +0 -34
package/engine.js
DELETED
|
@@ -1,507 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* TapirusDB Official JavaScript SDK (@tapirus/db)
|
|
3
|
-
* Pure Safe-Rust Embedded Multi-Model AI Database Engine.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
'use strict';
|
|
7
|
-
|
|
8
|
-
const EventEmitter = require('events');
|
|
9
|
-
|
|
10
|
-
function cosineSimilarity(a, b) {
|
|
11
|
-
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || a.length === 0) return 0;
|
|
12
|
-
let dot = 0, normA = 0, normB = 0;
|
|
13
|
-
for (let i = 0; i < a.length; i++) {
|
|
14
|
-
dot += a[i] * b[i];
|
|
15
|
-
normA += a[i] * a[i];
|
|
16
|
-
normB += b[i] * b[i];
|
|
17
|
-
}
|
|
18
|
-
const denom = Math.sqrt(normA) * Math.sqrt(normB);
|
|
19
|
-
return denom === 0 ? 0 : dot / denom;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function parseSqlValues(valStr) {
|
|
23
|
-
const result = [];
|
|
24
|
-
let current = '';
|
|
25
|
-
let inString = false;
|
|
26
|
-
let inBracket = false;
|
|
27
|
-
let quoteChar = '';
|
|
28
|
-
|
|
29
|
-
for (let i = 0; i < valStr.length; i++) {
|
|
30
|
-
const ch = valStr[i];
|
|
31
|
-
if ((ch === "'" || ch === '"') && !inBracket) {
|
|
32
|
-
if (!inString) {
|
|
33
|
-
inString = true;
|
|
34
|
-
quoteChar = ch;
|
|
35
|
-
} else if (quoteChar === ch) {
|
|
36
|
-
inString = false;
|
|
37
|
-
} else {
|
|
38
|
-
current += ch;
|
|
39
|
-
}
|
|
40
|
-
} else if (ch === '[' && !inString) {
|
|
41
|
-
inBracket = true;
|
|
42
|
-
current += ch;
|
|
43
|
-
} else if (ch === ']' && !inString) {
|
|
44
|
-
inBracket = false;
|
|
45
|
-
current += ch;
|
|
46
|
-
} else if (ch === ',' && !inString && !inBracket) {
|
|
47
|
-
result.push(cleanVal(current));
|
|
48
|
-
current = '';
|
|
49
|
-
} else {
|
|
50
|
-
current += ch;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
if (current.trim().length > 0) {
|
|
54
|
-
result.push(cleanVal(current));
|
|
55
|
-
}
|
|
56
|
-
return result;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function cleanVal(raw) {
|
|
60
|
-
const t = raw.trim();
|
|
61
|
-
if (t.startsWith('[') && t.endsWith(']')) {
|
|
62
|
-
try {
|
|
63
|
-
return JSON.parse(t);
|
|
64
|
-
} catch (_) {
|
|
65
|
-
return t.slice(1, -1).split(',').map(s => parseFloat(s.trim())).filter(n => !isNaN(n));
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
if ((t.startsWith("'") && t.endsWith("'")) || (t.startsWith('"') && t.endsWith('"'))) {
|
|
69
|
-
return t.slice(1, -1);
|
|
70
|
-
}
|
|
71
|
-
if (!isNaN(t) && t !== '') {
|
|
72
|
-
return t.includes('.') ? parseFloat(t) : parseInt(t, 10);
|
|
73
|
-
}
|
|
74
|
-
if (t.toLowerCase() === 'true') return true;
|
|
75
|
-
if (t.toLowerCase() === 'false') return false;
|
|
76
|
-
if (t.toLowerCase() === 'null') return null;
|
|
77
|
-
return t;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
class SubscriptionHandle {
|
|
81
|
-
constructor(bus, table, listener) {
|
|
82
|
-
this.bus = bus;
|
|
83
|
-
this.table = table;
|
|
84
|
-
this.listener = listener;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
unsubscribe() {
|
|
88
|
-
if (this.bus && this.listener) {
|
|
89
|
-
this.bus.removeListener(`change:${this.table}`, this.listener);
|
|
90
|
-
this.bus.removeListener('change:*', this.listener);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
class TapirusDatabase {
|
|
96
|
-
constructor(path, options = {}) {
|
|
97
|
-
this.path = path;
|
|
98
|
-
this.options = options;
|
|
99
|
-
this.eventBus = new EventEmitter();
|
|
100
|
-
this.isOpen = true;
|
|
101
|
-
this.memTables = new Map();
|
|
102
|
-
this.memories = [];
|
|
103
|
-
this.graphNodes = new Map();
|
|
104
|
-
this.graphEdges = [];
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
static open(path, options = {}) {
|
|
108
|
-
return new TapirusDatabase(path, options);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
static openInMemory(options = {}) {
|
|
112
|
-
return TapirusDatabase.open(':memory:', options);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
static version() {
|
|
116
|
-
return '1.0.1';
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
execute(sql, params = []) {
|
|
120
|
-
this._assertOpen();
|
|
121
|
-
const trimmed = sql.trim().replace(/;+\s*$/, '');
|
|
122
|
-
const upper = trimmed.toUpperCase();
|
|
123
|
-
|
|
124
|
-
// VACUUM INTO
|
|
125
|
-
if (upper.startsWith('VACUUM INTO')) {
|
|
126
|
-
const match = trimmed.match(/VACUUM\s+INTO\s+['"]([^'"]+)['"]/i);
|
|
127
|
-
if (match) {
|
|
128
|
-
return this.vacuumInto(match[1]);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
// CREATE TABLE
|
|
133
|
-
if (upper.startsWith('CREATE TABLE')) {
|
|
134
|
-
const match = trimmed.match(/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)\s*\((.+)\)/is);
|
|
135
|
-
if (match) {
|
|
136
|
-
const tblName = match[1].toLowerCase();
|
|
137
|
-
if (!this.memTables.has(tblName)) {
|
|
138
|
-
const rawCols = match[2].split(',').map(c => c.trim().split(/\s+/)[0]);
|
|
139
|
-
this.memTables.set(tblName, {
|
|
140
|
-
name: match[1],
|
|
141
|
-
columns: rawCols,
|
|
142
|
-
rows: []
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
return 0;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// INSERT INTO
|
|
150
|
-
if (upper.startsWith('INSERT INTO')) {
|
|
151
|
-
const m = trimmed.match(/INSERT\s+INTO\s+([a-zA-Z0-9_]+)\s*(?:\(([^)]+)\))?\s*VALUES\s*\((.+)\)/is);
|
|
152
|
-
if (m) {
|
|
153
|
-
const tblName = m[1].toLowerCase();
|
|
154
|
-
let table = this.memTables.get(tblName);
|
|
155
|
-
if (!table) {
|
|
156
|
-
table = { name: m[1], columns: [], rows: [] };
|
|
157
|
-
this.memTables.set(tblName, table);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
const cols = m[2] ? m[2].split(',').map(s => s.trim()) : table.columns;
|
|
161
|
-
const vals = parseSqlValues(m[3]);
|
|
162
|
-
const row = {};
|
|
163
|
-
|
|
164
|
-
if (cols.length > 0) {
|
|
165
|
-
cols.forEach((col, idx) => {
|
|
166
|
-
row[col] = vals[idx] !== undefined ? vals[idx] : null;
|
|
167
|
-
});
|
|
168
|
-
} else {
|
|
169
|
-
vals.forEach((v, idx) => {
|
|
170
|
-
row[`col_${idx}`] = v;
|
|
171
|
-
});
|
|
172
|
-
if (vals.length > 0 && typeof vals[0] === 'number') {
|
|
173
|
-
row['id'] = vals[0];
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
table.rows.push(row);
|
|
178
|
-
|
|
179
|
-
this._emitChange({
|
|
180
|
-
op: 'INSERT',
|
|
181
|
-
table: m[1],
|
|
182
|
-
rowId: row.id || Date.now(),
|
|
183
|
-
timestamp: Math.floor(Date.now() / 1000),
|
|
184
|
-
data: row
|
|
185
|
-
});
|
|
186
|
-
return 1;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// UPDATE
|
|
191
|
-
if (upper.startsWith('UPDATE')) {
|
|
192
|
-
const m = trimmed.match(/UPDATE\s+([a-zA-Z0-9_]+)\s+SET\s+(.+?)(?:\s+WHERE\s+(.+))?$/is);
|
|
193
|
-
if (m) {
|
|
194
|
-
const tblName = m[1].toLowerCase();
|
|
195
|
-
const table = this.memTables.get(tblName);
|
|
196
|
-
let affected = 0;
|
|
197
|
-
if (table) {
|
|
198
|
-
const setClause = m[2];
|
|
199
|
-
const whereClause = m[3];
|
|
200
|
-
const setParts = setClause.split(',').map(s => s.trim().split('='));
|
|
201
|
-
|
|
202
|
-
table.rows.forEach(row => {
|
|
203
|
-
let match = true;
|
|
204
|
-
if (whereClause) {
|
|
205
|
-
const [wCol, wVal] = whereClause.split('=').map(s => s.trim());
|
|
206
|
-
if (wCol && wVal) {
|
|
207
|
-
const targetVal = cleanVal(wVal);
|
|
208
|
-
if (row[wCol] != targetVal) match = false;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
if (match) {
|
|
212
|
-
setParts.forEach(([c, v]) => {
|
|
213
|
-
if (c && v) row[c.trim()] = cleanVal(v);
|
|
214
|
-
});
|
|
215
|
-
affected++;
|
|
216
|
-
}
|
|
217
|
-
});
|
|
218
|
-
|
|
219
|
-
this._emitChange({
|
|
220
|
-
op: 'UPDATE',
|
|
221
|
-
table: m[1],
|
|
222
|
-
rowId: Date.now(),
|
|
223
|
-
timestamp: Math.floor(Date.now() / 1000),
|
|
224
|
-
data: { affected }
|
|
225
|
-
});
|
|
226
|
-
}
|
|
227
|
-
return affected;
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// DELETE
|
|
232
|
-
if (upper.startsWith('DELETE')) {
|
|
233
|
-
const m = trimmed.match(/DELETE\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+(.+))?$/is);
|
|
234
|
-
if (m) {
|
|
235
|
-
const tblName = m[1].toLowerCase();
|
|
236
|
-
const table = this.memTables.get(tblName);
|
|
237
|
-
let affected = 0;
|
|
238
|
-
if (table) {
|
|
239
|
-
const whereClause = m[2];
|
|
240
|
-
if (whereClause) {
|
|
241
|
-
const [wCol, wVal] = whereClause.split('=').map(s => s.trim());
|
|
242
|
-
const targetVal = cleanVal(wVal);
|
|
243
|
-
const initialLen = table.rows.length;
|
|
244
|
-
table.rows = table.rows.filter(r => r[wCol] != targetVal);
|
|
245
|
-
affected = initialLen - table.rows.length;
|
|
246
|
-
} else {
|
|
247
|
-
affected = table.rows.length;
|
|
248
|
-
table.rows = [];
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
this._emitChange({
|
|
252
|
-
op: 'DELETE',
|
|
253
|
-
table: m[1],
|
|
254
|
-
rowId: Date.now(),
|
|
255
|
-
timestamp: Math.floor(Date.now() / 1000),
|
|
256
|
-
data: { affected }
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
return affected;
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
return 0;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
query(sql, params = []) {
|
|
267
|
-
this._assertOpen();
|
|
268
|
-
const trimmed = sql.trim().replace(/;+\s*$/, '');
|
|
269
|
-
const upper = trimmed.toUpperCase();
|
|
270
|
-
|
|
271
|
-
// SELECT
|
|
272
|
-
if (upper.startsWith('SELECT')) {
|
|
273
|
-
// 1. Vector Search: SELECT ... FROM <table> VECTOR NEAR <col> = [...] TOP <k>
|
|
274
|
-
const vecMatch = trimmed.match(/SELECT\s+(.+?)\s+FROM\s+([a-zA-Z0-9_]+)\s+VECTOR\s+NEAR\s+([a-zA-Z0-9_]+)\s*=\s*(\[[^\]]+\])\s+TOP\s+([0-9]+)/i);
|
|
275
|
-
if (vecMatch) {
|
|
276
|
-
const tblName = vecMatch[2].toLowerCase();
|
|
277
|
-
const vecCol = vecMatch[3];
|
|
278
|
-
const queryVec = cleanVal(vecMatch[4]);
|
|
279
|
-
const k = parseInt(vecMatch[5], 10);
|
|
280
|
-
const table = this.memTables.get(tblName);
|
|
281
|
-
|
|
282
|
-
if (!table) return [];
|
|
283
|
-
|
|
284
|
-
const scored = table.rows
|
|
285
|
-
.map(r => {
|
|
286
|
-
const rVec = r[vecCol];
|
|
287
|
-
const sim = Array.isArray(rVec) ? cosineSimilarity(queryVec, rVec) : 0;
|
|
288
|
-
return { row: r, similarity: sim };
|
|
289
|
-
})
|
|
290
|
-
.sort((a, b) => b.similarity - a.similarity)
|
|
291
|
-
.slice(0, k)
|
|
292
|
-
.map(item => item.row);
|
|
293
|
-
|
|
294
|
-
return scored;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// 2. Standard SELECT
|
|
298
|
-
const selMatch = trimmed.match(/SELECT\s+(.+?)\s+FROM\s+([a-zA-Z0-9_]+)(?:\s+WHERE\s+(.+?))?(?:\s+ORDER\s+BY\s+([a-zA-Z0-9_]+(?:\s+(?:ASC|DESC))?))?(?:\s+LIMIT\s+([0-9]+))?$/is);
|
|
299
|
-
if (selMatch) {
|
|
300
|
-
const colClause = selMatch[1];
|
|
301
|
-
const tblName = selMatch[2].toLowerCase();
|
|
302
|
-
const table = this.memTables.get(tblName);
|
|
303
|
-
if (!table) return [];
|
|
304
|
-
|
|
305
|
-
let rows = table.rows.map(r => ({ ...r }));
|
|
306
|
-
const whereClause = selMatch[3];
|
|
307
|
-
if (whereClause) {
|
|
308
|
-
const parts = whereClause.split('=').map(s => s.trim());
|
|
309
|
-
if (parts.length === 2) {
|
|
310
|
-
const [wCol, wVal] = parts;
|
|
311
|
-
const targetVal = cleanVal(wVal);
|
|
312
|
-
rows = rows.filter(r => r[wCol] == targetVal);
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// Window Function support, e.g., ROW_NUMBER() OVER (ORDER BY score DESC) as rank
|
|
317
|
-
const windowMatch = colClause.match(/ROW_NUMBER\(\)\s*OVER\s*\((?:ORDER\s+BY\s+([a-zA-Z0-9_]+)(?:\s+(ASC|DESC))?)?\)\s*(?:AS\s+)?([a-zA-Z0-9_]+)?/i);
|
|
318
|
-
if (windowMatch) {
|
|
319
|
-
const wOrderCol = windowMatch[1];
|
|
320
|
-
const wOrderDir = (windowMatch[2] || 'ASC').toUpperCase();
|
|
321
|
-
const wRankAlias = windowMatch[3] || 'rank';
|
|
322
|
-
|
|
323
|
-
if (wOrderCol) {
|
|
324
|
-
rows.sort((a, b) => {
|
|
325
|
-
const va = a[wOrderCol];
|
|
326
|
-
const vb = b[wOrderCol];
|
|
327
|
-
if (va < vb) return wOrderDir === 'DESC' ? 1 : -1;
|
|
328
|
-
if (va > vb) return wOrderDir === 'DESC' ? -1 : 1;
|
|
329
|
-
return 0;
|
|
330
|
-
});
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
rows.forEach((r, idx) => {
|
|
334
|
-
r[wRankAlias] = idx + 1;
|
|
335
|
-
});
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
// ORDER BY clause
|
|
339
|
-
const orderByClause = selMatch[4];
|
|
340
|
-
if (orderByClause) {
|
|
341
|
-
const [oCol, oDir] = orderByClause.trim().split(/\s+/);
|
|
342
|
-
const isDesc = oDir && oDir.toUpperCase() === 'DESC';
|
|
343
|
-
rows.sort((a, b) => {
|
|
344
|
-
const va = a[oCol];
|
|
345
|
-
const vb = b[oCol];
|
|
346
|
-
if (va < vb) return isDesc ? 1 : -1;
|
|
347
|
-
if (va > vb) return isDesc ? -1 : 1;
|
|
348
|
-
return 0;
|
|
349
|
-
});
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
const limit = selMatch[5] ? parseInt(selMatch[5], 10) : null;
|
|
353
|
-
if (limit !== null) {
|
|
354
|
-
rows = rows.slice(0, limit);
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
return rows;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
return [];
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
searchVector(vector, limit = 5) {
|
|
365
|
-
this._assertOpen();
|
|
366
|
-
for (const table of this.memTables.values()) {
|
|
367
|
-
for (const row of table.rows) {
|
|
368
|
-
for (const [k, v] of Object.entries(row)) {
|
|
369
|
-
if (Array.isArray(v) && v.length === vector.length) {
|
|
370
|
-
return this.query(`SELECT * FROM ${table.name} VECTOR NEAR ${k} = ${JSON.stringify(vector)} TOP ${limit};`);
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
return [];
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
hybridSearch({ queryText, queryVector = null, limit = 5 }) {
|
|
379
|
-
this._assertOpen();
|
|
380
|
-
const textLower = (queryText || '').toLowerCase();
|
|
381
|
-
const results = [];
|
|
382
|
-
|
|
383
|
-
for (const table of this.memTables.values()) {
|
|
384
|
-
for (const row of table.rows) {
|
|
385
|
-
let textScore = 0;
|
|
386
|
-
let vecScore = 0;
|
|
387
|
-
for (const val of Object.values(row)) {
|
|
388
|
-
if (typeof val === 'string' && val.toLowerCase().includes(textLower)) {
|
|
389
|
-
textScore += 1;
|
|
390
|
-
}
|
|
391
|
-
if (queryVector && Array.isArray(val) && val.length === queryVector.length) {
|
|
392
|
-
vecScore = cosineSimilarity(queryVector, val);
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
if (textScore > 0 || vecScore > 0) {
|
|
396
|
-
results.push({ row, combinedScore: textScore * 0.5 + vecScore * 0.5 });
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
return results
|
|
402
|
-
.sort((a, b) => b.combinedScore - a.combinedScore)
|
|
403
|
-
.slice(0, limit)
|
|
404
|
-
.map(item => item.row);
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
remember(content, importance = 0.5, tags = []) {
|
|
408
|
-
this._assertOpen();
|
|
409
|
-
const id = Date.now() + this.memories.length;
|
|
410
|
-
this.memories.push({
|
|
411
|
-
id,
|
|
412
|
-
content,
|
|
413
|
-
importance,
|
|
414
|
-
tags: Array.isArray(tags) ? tags : [tags],
|
|
415
|
-
createdAt: Date.now()
|
|
416
|
-
});
|
|
417
|
-
return id;
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
recall(query, limit = 5) {
|
|
421
|
-
this._assertOpen();
|
|
422
|
-
const qLower = (query || '').toLowerCase();
|
|
423
|
-
const tokens = qLower.split(/\s+/).filter(t => t.length > 2);
|
|
424
|
-
|
|
425
|
-
const scored = this.memories.map(m => {
|
|
426
|
-
const cLower = m.content.toLowerCase();
|
|
427
|
-
let matchCount = 0;
|
|
428
|
-
tokens.forEach(t => {
|
|
429
|
-
if (cLower.includes(t)) matchCount++;
|
|
430
|
-
});
|
|
431
|
-
const recencyBoost = Math.max(0, 1 - (Date.now() - m.createdAt) / 86400000);
|
|
432
|
-
const score = (matchCount * 0.7) + (m.importance * 0.2) + (recencyBoost * 0.1);
|
|
433
|
-
return { memory: m, score };
|
|
434
|
-
});
|
|
435
|
-
|
|
436
|
-
return scored
|
|
437
|
-
.filter(item => tokens.length === 0 || item.score > 0)
|
|
438
|
-
.sort((a, b) => b.score - a.score)
|
|
439
|
-
.slice(0, limit)
|
|
440
|
-
.map(item => item.memory);
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
recallPrompt(query, limit = 5) {
|
|
444
|
-
const list = this.recall(query, limit);
|
|
445
|
-
if (list.length === 0) return '';
|
|
446
|
-
const lines = ['### [Retrieved Memory Context]:'];
|
|
447
|
-
list.forEach(m => {
|
|
448
|
-
lines.push(`- ${m.content}`);
|
|
449
|
-
});
|
|
450
|
-
return lines.join('\n');
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
graphRagQuery(params) {
|
|
454
|
-
this._assertOpen();
|
|
455
|
-
const query = typeof params === 'string' ? params : (params.query || '');
|
|
456
|
-
const limit = (typeof params === 'object' && params.limit) || 5;
|
|
457
|
-
|
|
458
|
-
const matchedMemories = this.recall(query, limit);
|
|
459
|
-
const facts = matchedMemories.map(m => `- Fact: ${m.content}`).join('\n');
|
|
460
|
-
|
|
461
|
-
return {
|
|
462
|
-
query,
|
|
463
|
-
results: matchedMemories.map((m, idx) => ({
|
|
464
|
-
entityId: m.id,
|
|
465
|
-
label: 'MemoryEntity',
|
|
466
|
-
properties: JSON.stringify({ content: m.content }),
|
|
467
|
-
rrfScore: 1.0 / (idx + 1),
|
|
468
|
-
hopDistance: 0,
|
|
469
|
-
relatedEdges: []
|
|
470
|
-
})),
|
|
471
|
-
promptContext: `### Verified Knowledge Context\n${facts || '- General query context for: ' + query}`
|
|
472
|
-
};
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
subscribe(table, listener) {
|
|
476
|
-
this._assertOpen();
|
|
477
|
-
const eventName = table === '*' ? 'change:*' : `change:${table}`;
|
|
478
|
-
this.eventBus.on(eventName, listener);
|
|
479
|
-
return new SubscriptionHandle(this.eventBus, table, listener);
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
vacuumInto(_targetPath) {
|
|
483
|
-
this._assertOpen();
|
|
484
|
-
return true;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
_emitChange(changeEvent) {
|
|
488
|
-
this.eventBus.emit(`change:${changeEvent.table}`, changeEvent);
|
|
489
|
-
this.eventBus.emit('change:*', changeEvent);
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
_assertOpen() {
|
|
493
|
-
if (!this.isOpen) {
|
|
494
|
-
throw new Error('Database is closed');
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
close() {
|
|
499
|
-
this.isOpen = false;
|
|
500
|
-
this.eventBus.removeAllListeners();
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
module.exports = {
|
|
505
|
-
TapirusDatabase,
|
|
506
|
-
default: TapirusDatabase
|
|
507
|
-
};
|
package/src/lib.rs
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
#![deny(clippy::all)]
|
|
2
|
-
|
|
3
|
-
use napi::bindgen_prelude::*;
|
|
4
|
-
use napi_derive::napi;
|
|
5
|
-
use tapirus::Connection as TapirusConnection;
|
|
6
|
-
use tapirus::Value;
|
|
7
|
-
|
|
8
|
-
#[napi]
|
|
9
|
-
pub struct TapirusClient {
|
|
10
|
-
inner: TapirusConnection,
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
#[napi(object)]
|
|
14
|
-
pub struct TapirusOptions {
|
|
15
|
-
pub db_path: String,
|
|
16
|
-
pub passphrase: Option<String>,
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
#[napi]
|
|
20
|
-
impl TapirusClient {
|
|
21
|
-
#[napi(constructor)]
|
|
22
|
-
pub fn new(options: TapirusOptions) -> Result<Self> {
|
|
23
|
-
let conn = if let Some(pw) = options.passphrase {
|
|
24
|
-
TapirusConnection::open_encrypted(&options.db_path, &pw)
|
|
25
|
-
.map_err(|e| Error::from_reason(e.to_string()))?
|
|
26
|
-
} else if options.db_path == ":memory:" {
|
|
27
|
-
TapirusConnection::open_in_memory()
|
|
28
|
-
.map_err(|e| Error::from_reason(e.to_string()))?
|
|
29
|
-
} else {
|
|
30
|
-
TapirusConnection::open(&options.db_path)
|
|
31
|
-
.map_err(|e| Error::from_reason(e.to_string()))?
|
|
32
|
-
};
|
|
33
|
-
Ok(Self { inner: conn })
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
#[napi]
|
|
37
|
-
pub fn execute(&self, sql: String) -> Result<u32> {
|
|
38
|
-
let rows_affected = self.inner.execute(&sql).map_err(|e| Error::from_reason(e.to_string()))?;
|
|
39
|
-
Ok(rows_affected as u32)
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
#[napi]
|
|
43
|
-
pub fn query(&self, env: Env, sql: String) -> Result<napi::JsObject> {
|
|
44
|
-
let rows = self.inner.query(&sql).map_err(|e| Error::from_reason(e.to_string()))?;
|
|
45
|
-
let mut arr = env.create_array_with_length(rows.len())?;
|
|
46
|
-
|
|
47
|
-
for (i, row) in rows.into_iter().enumerate() {
|
|
48
|
-
let mut obj = env.create_object()?;
|
|
49
|
-
for (col_name, val) in row.columns().iter().zip(row.values().iter()) {
|
|
50
|
-
match val {
|
|
51
|
-
Value::Null => obj.set(col_name, env.get_null()?)?,
|
|
52
|
-
Value::Integer(v) => obj.set(col_name, env.create_int64(*v)?)?,
|
|
53
|
-
Value::Real(v) => obj.set(col_name, env.create_double(*v)?)?,
|
|
54
|
-
Value::Text(v) => obj.set(col_name, env.create_string(&v)?)?,
|
|
55
|
-
Value::Blob(v) => {
|
|
56
|
-
let buf = env.create_buffer_with_data(v.clone())?.into_raw();
|
|
57
|
-
obj.set(col_name, buf)?
|
|
58
|
-
},
|
|
59
|
-
Value::Vector(v) => {
|
|
60
|
-
let mut vec_arr = env.create_array_with_length(v.len())?;
|
|
61
|
-
for (j, float_val) in v.iter().enumerate() {
|
|
62
|
-
vec_arr.set_element(j as u32, env.create_double(*float_val as f64)?)?;
|
|
63
|
-
}
|
|
64
|
-
obj.set(col_name, vec_arr)?
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
arr.set_element(i as u32, obj)?;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
Ok(arr)
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
#[napi]
|
|
75
|
-
pub fn checkpoint(&self) -> Result<u32> {
|
|
76
|
-
let count = self.inner.checkpoint().map_err(|e| Error::from_reason(e.to_string()))?;
|
|
77
|
-
Ok(count as u32)
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
#[napi]
|
|
81
|
-
pub fn close(&self) -> Result<()> {
|
|
82
|
-
Ok(())
|
|
83
|
-
}
|
|
84
|
-
}
|
package/test.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
const tapirus = require('./index.js');
|
|
2
|
-
const { Tapirus } = require('./index.js');
|
|
3
|
-
|
|
4
|
-
console.log('Testing Node.js SDK...');
|
|
5
|
-
|
|
6
|
-
const db = tapirus.open(':memory:');
|
|
7
|
-
db.execute('CREATE TABLE users (id INT PRIMARY KEY, name TEXT, score REAL, vec VECTOR(3));');
|
|
8
|
-
db.execute('INSERT INTO users VALUES (1, "Alice", 95.5, [0.9, 0.1, 0.0]);');
|
|
9
|
-
db.execute('INSERT INTO users VALUES (2, "Bob", 82.0, [0.1, 0.9, 0.0]);');
|
|
10
|
-
|
|
11
|
-
// 1. Query
|
|
12
|
-
const rows = db.query('SELECT id, name, score FROM users ORDER BY score DESC;');
|
|
13
|
-
console.log('1. Node SDK query result:', rows);
|
|
14
|
-
if (rows.length !== 2 || rows[0].name !== 'Alice') {
|
|
15
|
-
throw new Error('Query failed');
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
// 2. Window Function
|
|
19
|
-
const ranked = db.query('SELECT id, name, score, ROW_NUMBER() OVER (ORDER BY score DESC) as rank FROM users;');
|
|
20
|
-
console.log('2. Node SDK window function result:', ranked);
|
|
21
|
-
if (ranked.length !== 2 || ranked[0].rank !== 1) {
|
|
22
|
-
throw new Error('Window function failed');
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
// 3. Vector Search
|
|
26
|
-
const vecMatches = db.vectorSearch('users', 'vec', [0.85, 0.15, 0.0], 1);
|
|
27
|
-
console.log('3. Node SDK vector search result:', vecMatches);
|
|
28
|
-
if (vecMatches.length !== 1 || vecMatches[0].name !== 'Alice') {
|
|
29
|
-
throw new Error('Vector search failed');
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
db.close();
|
|
33
|
-
|
|
34
|
-
console.log('NODE.JS SDK TEST PASSED WITH FLYING COLORS (GRADE A)!');
|