@atscript/db-sqlite 0.1.177 → 0.1.178
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/dist/index.cjs +217 -102
- package/dist/index.d.cts +55 -10
- package/dist/index.d.mts +55 -10
- package/dist/index.mjs +217 -102
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -856,6 +856,44 @@ function busyMapped(fn) {
|
|
|
856
856
|
}
|
|
857
857
|
}
|
|
858
858
|
/**
|
|
859
|
+
* A vector as sqlite-vec's compact form: float32, 4 bytes per number, in the
|
|
860
|
+
* host's byte order — the order sqlite-vec reads a BLOB in. The stored
|
|
861
|
+
* vector, its decode and the KNN query vector all use it.
|
|
862
|
+
*/
|
|
863
|
+
function float32Blob(values) {
|
|
864
|
+
return Buffer.from(new Float32Array(values).buffer);
|
|
865
|
+
}
|
|
866
|
+
/**
|
|
867
|
+
* Whether `field` is a JSON-stored array of numbers — a column that may hold
|
|
868
|
+
* a vector this adapter stored as a Float32 BLOB without being declared one
|
|
869
|
+
* (see `formatValue`).
|
|
870
|
+
*/
|
|
871
|
+
function isNumberArrayField(field) {
|
|
872
|
+
const type = field.type.type;
|
|
873
|
+
return field.storage === "json" && type.kind === "array" && type.of.type.kind === "" && type.of.type.designType === "number";
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* The numbers of a {@link float32Blob}; any other read value as is — JSON
|
|
877
|
+
* text is the mapper's to parse, and a blob whose length is not a multiple
|
|
878
|
+
* of 4 is no vector this adapter wrote. The bytes are copied into a fresh
|
|
879
|
+
* buffer first: a driver's blob is often a slice of a pooled `ArrayBuffer` at
|
|
880
|
+
* an offset a `Float32Array` view cannot start at (it needs 4-byte alignment).
|
|
881
|
+
*/
|
|
882
|
+
function decodeFloat32Blob(value) {
|
|
883
|
+
if (!(value instanceof Uint8Array) || value.byteLength % 4 !== 0) return value;
|
|
884
|
+
return Array.from(new Float32Array(new Uint8Array(value).buffer));
|
|
885
|
+
}
|
|
886
|
+
/** The numbers of JSON text holding an array of numbers, else `undefined`. */
|
|
887
|
+
function jsonNumberArray(text) {
|
|
888
|
+
let parsed;
|
|
889
|
+
try {
|
|
890
|
+
parsed = JSON.parse(text);
|
|
891
|
+
} catch {
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
return Array.isArray(parsed) && parsed.every((n) => typeof n === "number") ? parsed : void 0;
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
859
897
|
* SQLite adapter for {@link AtscriptDbTable}.
|
|
860
898
|
*
|
|
861
899
|
* Accepts any {@link TSqliteDriver} implementation — the actual SQLite engine
|
|
@@ -940,6 +978,8 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
940
978
|
_vectorPartitionFields = /* @__PURE__ */ new Map();
|
|
941
979
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
942
980
|
_gate;
|
|
981
|
+
/** Open {@link _atomically} units of the current (synchronous) call. */
|
|
982
|
+
_unitDepth = 0;
|
|
943
983
|
_txOptions;
|
|
944
984
|
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
945
985
|
_ftsTokenizers;
|
|
@@ -979,33 +1019,37 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
979
1019
|
}
|
|
980
1020
|
}
|
|
981
1021
|
/**
|
|
982
|
-
* A vector field
|
|
983
|
-
*
|
|
984
|
-
*
|
|
985
|
-
*
|
|
986
|
-
*
|
|
987
|
-
*
|
|
988
|
-
*
|
|
1022
|
+
* A vector field (since 0.1.178): with sqlite-vec a Float32 BLOB
|
|
1023
|
+
* ({@link float32Blob}), the column type `typeMapper` gives it — the mapper
|
|
1024
|
+
* hands the formatter JSON text, converted when it holds an array of
|
|
1025
|
+
* numbers (anything else is stored as is); without sqlite-vec, JSON text.
|
|
1026
|
+
* Rows written before hold JSON text and are not rewritten; a vector
|
|
1027
|
+
* changed by an array patch operator is stored as JSON text too
|
|
1028
|
+
* (`resolveArrayOps` writes without `toStorage`). Reads take both forms.
|
|
1029
|
+
* The extension is probed per value, not here — metadata is built where a
|
|
1030
|
+
* busy probe must not run (see {@link _detectVectorSupport}) — so a busy
|
|
1031
|
+
* probe fails the write with `LOCK_TIMEOUT`, never stores JSON text.
|
|
1032
|
+
*
|
|
1033
|
+
* Any other JSON `number[]` column reads a BLOB the same way: a view column
|
|
1034
|
+
* reading a vector (the annotation is not passed to a referring field), or
|
|
1035
|
+
* a field whose annotation was removed.
|
|
989
1036
|
*/
|
|
990
1037
|
formatValue(field) {
|
|
991
|
-
if (!this._vectorFields.has(field.path)) return
|
|
1038
|
+
if (!this._vectorFields.has(field.path)) return isNumberArrayField(field) ? {
|
|
1039
|
+
toStorage: (value) => value,
|
|
1040
|
+
fromStorage: decodeFloat32Blob
|
|
1041
|
+
} : void 0;
|
|
992
1042
|
return {
|
|
993
1043
|
toStorage: (value) => {
|
|
1044
|
+
if (typeof value === "string") {
|
|
1045
|
+
if (!this._detectVectorSupport()) return value;
|
|
1046
|
+
const values = jsonNumberArray(value);
|
|
1047
|
+
return values ? float32Blob(values) : value;
|
|
1048
|
+
}
|
|
994
1049
|
if (!Array.isArray(value)) return value;
|
|
995
|
-
return this._detectVectorSupport() ?
|
|
1050
|
+
return this._detectVectorSupport() ? float32Blob(value) : JSON.stringify(value);
|
|
996
1051
|
},
|
|
997
|
-
fromStorage:
|
|
998
|
-
if (value instanceof Uint8Array) {
|
|
999
|
-
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
1000
|
-
return Array.from(new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4)));
|
|
1001
|
-
}
|
|
1002
|
-
if (typeof value === "string") try {
|
|
1003
|
-
return JSON.parse(value);
|
|
1004
|
-
} catch {
|
|
1005
|
-
return value;
|
|
1006
|
-
}
|
|
1007
|
-
return value;
|
|
1008
|
-
}
|
|
1052
|
+
fromStorage: decodeFloat32Blob
|
|
1009
1053
|
};
|
|
1010
1054
|
}
|
|
1011
1055
|
isVectorSearchable() {
|
|
@@ -1977,8 +2021,10 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
1977
2021
|
action: "rebuild"
|
|
1978
2022
|
}, ftsTable, () => {
|
|
1979
2023
|
this._probeFtsTokenizer(index);
|
|
1980
|
-
this.
|
|
1981
|
-
|
|
2024
|
+
this._atomically(() => {
|
|
2025
|
+
this._dropFtsTable(ftsTable);
|
|
2026
|
+
this._createFtsTable(tableName, ftsTable, index);
|
|
2027
|
+
});
|
|
1982
2028
|
});
|
|
1983
2029
|
}
|
|
1984
2030
|
return changes;
|
|
@@ -2008,42 +2054,107 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2008
2054
|
const desired = (0, _atscript_db.splitFulltextFields)(index).text.map((f) => f.name);
|
|
2009
2055
|
return live.length === desired.length && live.every((name, i) => name === desired[i]);
|
|
2010
2056
|
}
|
|
2011
|
-
/**
|
|
2057
|
+
/**
|
|
2058
|
+
* Creates an FTS5 virtual table with sync triggers and rebuilds the index —
|
|
2059
|
+
* all or nothing (since 0.1.178, see {@link _atomically}).
|
|
2060
|
+
*/
|
|
2012
2061
|
_createFtsTable(tableName, ftsTable, index) {
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2062
|
+
this._atomically(() => {
|
|
2063
|
+
const fields = (0, _atscript_db.splitFulltextFields)(index).text;
|
|
2064
|
+
const fieldList = fields.map((f) => `"${esc(f.name)}"`).join(", ");
|
|
2065
|
+
const tokenizer = ftsTokenizer(index, this._configuredFtsTokenizer(index));
|
|
2066
|
+
const tokenize = tokenizer ? `, tokenize='${tokenizer}'` : "";
|
|
2067
|
+
const prefix = this._ftsPrefix ? `, prefix='${this._ftsPrefix}'` : "";
|
|
2068
|
+
const createSql = `CREATE VIRTUAL TABLE IF NOT EXISTS "${esc(ftsTable)}" USING fts5(${fieldList}, content='${tableName.replace(/'/g, "''")}', content_rowid='rowid'${tokenize}${prefix})`;
|
|
2069
|
+
this._log(createSql);
|
|
2070
|
+
this.driver.exec(createSql);
|
|
2071
|
+
const newFields = fields.map((f) => `new."${esc(f.name)}"`).join(", ");
|
|
2072
|
+
const oldFields = fields.map((f) => `old."${esc(f.name)}"`).join(", ");
|
|
2073
|
+
const ef = esc(ftsTable);
|
|
2074
|
+
const aiSql = `CREATE TRIGGER IF NOT EXISTS "${esc(ftsTable + "__ai")}" AFTER INSERT ON "${esc(tableName)}" BEGIN INSERT INTO "${ef}"(rowid, ${fieldList}) VALUES (new.rowid, ${newFields}); END`;
|
|
2075
|
+
this._log(aiSql);
|
|
2076
|
+
this.driver.exec(aiSql);
|
|
2077
|
+
const adSql = `CREATE TRIGGER IF NOT EXISTS "${esc(ftsTable + "__ad")}" AFTER DELETE ON "${esc(tableName)}" BEGIN INSERT INTO "${ef}"("${ef}", rowid, ${fieldList}) VALUES ('delete', old.rowid, ${oldFields}); END`;
|
|
2078
|
+
this._log(adSql);
|
|
2079
|
+
this.driver.exec(adSql);
|
|
2080
|
+
const auSql = `CREATE TRIGGER IF NOT EXISTS "${esc(ftsTable + "__au")}" AFTER UPDATE ON "${esc(tableName)}" BEGIN INSERT INTO "${ef}"("${ef}", rowid, ${fieldList}) VALUES ('delete', old.rowid, ${oldFields}); INSERT INTO "${ef}"(rowid, ${fieldList}) VALUES (new.rowid, ${newFields}); END`;
|
|
2081
|
+
this._log(auSql);
|
|
2082
|
+
this.driver.exec(auSql);
|
|
2083
|
+
const rebuildSql = `INSERT INTO "${ef}"("${ef}") VALUES ('rebuild')`;
|
|
2084
|
+
this._log(rebuildSql);
|
|
2085
|
+
this.driver.exec(rebuildSql);
|
|
2086
|
+
});
|
|
2087
|
+
}
|
|
2088
|
+
/** Drops an FTS5 virtual table and its sync triggers — all or nothing (since 0.1.178). */
|
|
2038
2089
|
_dropFtsTable(ftsTable) {
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2090
|
+
this._atomically(() => {
|
|
2091
|
+
for (const suffix of [
|
|
2092
|
+
"__ai",
|
|
2093
|
+
"__ad",
|
|
2094
|
+
"__au"
|
|
2095
|
+
]) this.driver.exec(`DROP TRIGGER IF EXISTS "${esc(ftsTable + suffix)}"`);
|
|
2096
|
+
const sql = `DROP TABLE IF EXISTS "${esc(ftsTable)}"`;
|
|
2097
|
+
this._log(sql);
|
|
2098
|
+
this.driver.exec(sql);
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* Runs the synchronous `fn` as one all-or-nothing unit (since 0.1.178) —
|
|
2103
|
+
* the FTS5 / vec0 shadow-table steps: a statement failing between a
|
|
2104
|
+
* `CREATE VIRTUAL TABLE` and its triggers left the table without them, and
|
|
2105
|
+
* the next sync, seeing the table, kept it: the index silently stopped
|
|
2106
|
+
* following writes.
|
|
2107
|
+
*
|
|
2108
|
+
* - The unit opens the transaction itself (none is open, no unit around
|
|
2109
|
+
* it): `BEGIN IMMEDIATE` … `COMMIT`, and on any failure — a `COMMIT`
|
|
2110
|
+
* refused while another connection reads (rollback-journal mode)
|
|
2111
|
+
* included — a full `ROLLBACK`, which ends the transaction. IMMEDIATE
|
|
2112
|
+
* takes the write lock up front, waiting on `busy_timeout`: a read-only
|
|
2113
|
+
* first statement (`DROP TRIGGER IF EXISTS` of a missing trigger) cannot
|
|
2114
|
+
* pin a WAL snapshot that a later write then fails on without waiting
|
|
2115
|
+
* (`SQLITE_BUSY_SNAPSHOT`).
|
|
2116
|
+
* - Inside a transaction (the adapter's own: `recreateTable`, a caller's
|
|
2117
|
+
* `withTransaction` around a schema call) or another unit (the FTS
|
|
2118
|
+
* rebuild wraps a drop and a create): a `SAVEPOINT`, rolled back to on
|
|
2119
|
+
* failure. Nothing commits there, so nothing waits on another connection.
|
|
2120
|
+
*
|
|
2121
|
+
* "Open" is the adapter's view — its transaction state and the unit depth;
|
|
2122
|
+
* the driver interface has no in-transaction flag. Every caller runs under
|
|
2123
|
+
* `_stmt` or `_withExclusiveConnection`, so another context's transaction
|
|
2124
|
+
* is never open on the connection meanwhile; one opened behind the
|
|
2125
|
+
* adapter's back makes `BEGIN IMMEDIATE` fail without running the unit.
|
|
2126
|
+
*
|
|
2127
|
+
* Errors propagate as thrown: the caller's boundary maps SQLITE_BUSY —
|
|
2128
|
+
* at `BEGIN`, `COMMIT` or any statement — to `LOCK_TIMEOUT`. A failing
|
|
2129
|
+
* rollback never replaces the original error; it is logged as an error,
|
|
2130
|
+
* because the connection may then still be in the transaction (the next
|
|
2131
|
+
* `BEGIN` fails, autocommit statements would join it).
|
|
2132
|
+
*/
|
|
2133
|
+
_atomically(fn) {
|
|
2134
|
+
const [begin, end, undo] = this._unitDepth > 0 || this._getTransactionState() !== void 0 ? [
|
|
2135
|
+
`SAVEPOINT "atscript_unit"`,
|
|
2136
|
+
`RELEASE "atscript_unit"`,
|
|
2137
|
+
[`ROLLBACK TO "atscript_unit"`, `RELEASE "atscript_unit"`]
|
|
2138
|
+
] : [
|
|
2139
|
+
"BEGIN IMMEDIATE",
|
|
2140
|
+
"COMMIT",
|
|
2141
|
+
["ROLLBACK"]
|
|
2142
|
+
];
|
|
2143
|
+
this.driver.exec(begin);
|
|
2144
|
+
this._unitDepth++;
|
|
2145
|
+
try {
|
|
2146
|
+
fn();
|
|
2147
|
+
this.driver.exec(end);
|
|
2148
|
+
} catch (error) {
|
|
2149
|
+
try {
|
|
2150
|
+
for (const sql of undo) this.driver.exec(sql);
|
|
2151
|
+
} catch (undoError) {
|
|
2152
|
+
this.logger.error(`[atscript-db-sqlite] ${undo.join("; ")} failed after a failed schema step — the connection may still be in its transaction: ${undoError?.message}`);
|
|
2153
|
+
}
|
|
2154
|
+
throw error;
|
|
2155
|
+
} finally {
|
|
2156
|
+
this._unitDepth--;
|
|
2157
|
+
}
|
|
2047
2158
|
}
|
|
2048
2159
|
/** Lists FTS5/vec0 shadow virtual tables for a content table. */
|
|
2049
2160
|
_listShadowTables(tableName, kind) {
|
|
@@ -2143,7 +2254,7 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2143
2254
|
_buildVectorSearchBase(vector, query, indexName) {
|
|
2144
2255
|
const { vec, partitionPhysicalNames } = this._resolveVectorIndex(indexName);
|
|
2145
2256
|
if (vector.length !== vec.dimensions) throw new Error(`Vector dimension mismatch: index "${vec.indexName}" expects ${vec.dimensions}, got ${vector.length}`);
|
|
2146
|
-
const vecBuf =
|
|
2257
|
+
const vecBuf = float32Blob(vector);
|
|
2147
2258
|
const controls = query.controls || {};
|
|
2148
2259
|
const limit = controls.$limit ?? 20;
|
|
2149
2260
|
const skip = controls.$skip ?? 0;
|
|
@@ -2286,51 +2397,55 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
2286
2397
|
}
|
|
2287
2398
|
for (const c of partitionCols) if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(c.physicalName)) throw new Error(`vec0 partition column name "${c.physicalName}" is not a safe identifier (only [A-Za-z_][A-Za-z0-9_]* is allowed for @db.search.filter fields on SQLite).`);
|
|
2288
2399
|
const ddlCols = [partitionCols.map((c) => `${c.physicalName} ${c.sqlType} partition key`).join(", "), `embedding float[${vec.dimensions}] distance_metric=${metric}`].filter(Boolean).join(", ");
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2400
|
+
this._atomically(() => {
|
|
2401
|
+
const createSql = `CREATE VIRTUAL TABLE IF NOT EXISTS "${esc(vecTable)}" USING vec0(${ddlCols})`;
|
|
2402
|
+
this._log(createSql);
|
|
2403
|
+
this.driver.exec(createSql);
|
|
2404
|
+
const partCols = partitionCols.map((c) => `"${esc(c.physicalName)}"`);
|
|
2405
|
+
const embCol = `"${esc(embeddingCol)}"`;
|
|
2406
|
+
const insertCols = [
|
|
2407
|
+
"rowid",
|
|
2408
|
+
...partCols,
|
|
2409
|
+
"embedding"
|
|
2410
|
+
].join(", ");
|
|
2411
|
+
const insertNewVals = [
|
|
2412
|
+
"new.rowid",
|
|
2413
|
+
...partitionCols.map((c) => `new."${esc(c.physicalName)}"`),
|
|
2414
|
+
`new.${embCol}`
|
|
2415
|
+
].join(", ");
|
|
2416
|
+
const seedColList = [
|
|
2417
|
+
"rowid",
|
|
2418
|
+
...partCols,
|
|
2419
|
+
embCol
|
|
2420
|
+
].join(", ");
|
|
2421
|
+
const ev = esc(vecTable);
|
|
2422
|
+
const et = esc(tableName);
|
|
2423
|
+
const aiSql = `CREATE TRIGGER IF NOT EXISTS "${esc(vecTable + "__ai")}" AFTER INSERT ON "${et}" WHEN new.${embCol} IS NOT NULL BEGIN INSERT INTO "${ev}"(${insertCols}) VALUES(${insertNewVals}); END`;
|
|
2424
|
+
this._log(aiSql);
|
|
2425
|
+
this.driver.exec(aiSql);
|
|
2426
|
+
const adSql = `CREATE TRIGGER IF NOT EXISTS "${esc(vecTable + "__ad")}" AFTER DELETE ON "${et}" BEGIN DELETE FROM "${ev}" WHERE rowid = old.rowid; END`;
|
|
2427
|
+
this._log(adSql);
|
|
2428
|
+
this.driver.exec(adSql);
|
|
2429
|
+
const auSql = `CREATE TRIGGER IF NOT EXISTS "${esc(vecTable + "__au")}" AFTER UPDATE ON "${et}" BEGIN DELETE FROM "${ev}" WHERE rowid = old.rowid; INSERT INTO "${ev}"(${insertCols}) SELECT ${insertNewVals} WHERE new.${embCol} IS NOT NULL; END`;
|
|
2430
|
+
this._log(auSql);
|
|
2431
|
+
this.driver.exec(auSql);
|
|
2432
|
+
const seedSql = `INSERT INTO "${ev}"(${insertCols}) SELECT ${seedColList} FROM "${et}" WHERE ${embCol} IS NOT NULL`;
|
|
2433
|
+
this._log(seedSql);
|
|
2434
|
+
this.driver.exec(seedSql);
|
|
2435
|
+
});
|
|
2436
|
+
}
|
|
2437
|
+
/** Drops a vec0 virtual table and its sync triggers — all or nothing (since 0.1.178). */
|
|
2325
2438
|
_dropVecTable(vecTable) {
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2439
|
+
this._atomically(() => {
|
|
2440
|
+
for (const suffix of [
|
|
2441
|
+
"__ai",
|
|
2442
|
+
"__ad",
|
|
2443
|
+
"__au"
|
|
2444
|
+
]) this.driver.exec(`DROP TRIGGER IF EXISTS "${esc(vecTable + suffix)}"`);
|
|
2445
|
+
const sql = `DROP TABLE IF EXISTS "${esc(vecTable)}"`;
|
|
2446
|
+
this._log(sql);
|
|
2447
|
+
this.driver.exec(sql);
|
|
2448
|
+
});
|
|
2334
2449
|
}
|
|
2335
2450
|
/** Drops all vec0 virtual shadow tables and triggers for a content table. */
|
|
2336
2451
|
_dropAllVecTables(tableName) {
|
package/dist/index.d.cts
CHANGED
|
@@ -354,6 +354,8 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
354
354
|
private _vectorPartitionFields;
|
|
355
355
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
356
356
|
private readonly _gate;
|
|
357
|
+
/** Open {@link _atomically} units of the current (synchronous) call. */
|
|
358
|
+
private _unitDepth;
|
|
357
359
|
private readonly _txOptions;
|
|
358
360
|
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
359
361
|
private readonly _ftsTokenizers;
|
|
@@ -364,13 +366,20 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
364
366
|
constructor(driver: TSqliteDriver, options?: SqliteAdapterOptions);
|
|
365
367
|
onFieldScanned(field: string, _type: unknown, metadata: TMetadataMap<AtscriptMetadata>): void;
|
|
366
368
|
/**
|
|
367
|
-
* A vector field
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
*
|
|
369
|
+
* A vector field (since 0.1.178): with sqlite-vec a Float32 BLOB
|
|
370
|
+
* ({@link float32Blob}), the column type `typeMapper` gives it — the mapper
|
|
371
|
+
* hands the formatter JSON text, converted when it holds an array of
|
|
372
|
+
* numbers (anything else is stored as is); without sqlite-vec, JSON text.
|
|
373
|
+
* Rows written before hold JSON text and are not rewritten; a vector
|
|
374
|
+
* changed by an array patch operator is stored as JSON text too
|
|
375
|
+
* (`resolveArrayOps` writes without `toStorage`). Reads take both forms.
|
|
376
|
+
* The extension is probed per value, not here — metadata is built where a
|
|
377
|
+
* busy probe must not run (see {@link _detectVectorSupport}) — so a busy
|
|
378
|
+
* probe fails the write with `LOCK_TIMEOUT`, never stores JSON text.
|
|
379
|
+
*
|
|
380
|
+
* Any other JSON `number[]` column reads a BLOB the same way: a view column
|
|
381
|
+
* reading a vector (the annotation is not passed to a referring field), or
|
|
382
|
+
* a field whose annotation was removed.
|
|
374
383
|
*/
|
|
375
384
|
formatValue(field: TDbFieldMeta): TValueFormatterPair | undefined;
|
|
376
385
|
isVectorSearchable(): boolean;
|
|
@@ -617,10 +626,46 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
617
626
|
private _probeFtsTokenizer;
|
|
618
627
|
/** Whether an existing FTS5 table has exactly the index's text columns, in order. */
|
|
619
628
|
private _ftsColumnsMatch;
|
|
620
|
-
/**
|
|
629
|
+
/**
|
|
630
|
+
* Creates an FTS5 virtual table with sync triggers and rebuilds the index —
|
|
631
|
+
* all or nothing (since 0.1.178, see {@link _atomically}).
|
|
632
|
+
*/
|
|
621
633
|
private _createFtsTable;
|
|
622
|
-
/** Drops an FTS5 virtual table and its sync triggers. */
|
|
634
|
+
/** Drops an FTS5 virtual table and its sync triggers — all or nothing (since 0.1.178). */
|
|
623
635
|
private _dropFtsTable;
|
|
636
|
+
/**
|
|
637
|
+
* Runs the synchronous `fn` as one all-or-nothing unit (since 0.1.178) —
|
|
638
|
+
* the FTS5 / vec0 shadow-table steps: a statement failing between a
|
|
639
|
+
* `CREATE VIRTUAL TABLE` and its triggers left the table without them, and
|
|
640
|
+
* the next sync, seeing the table, kept it: the index silently stopped
|
|
641
|
+
* following writes.
|
|
642
|
+
*
|
|
643
|
+
* - The unit opens the transaction itself (none is open, no unit around
|
|
644
|
+
* it): `BEGIN IMMEDIATE` … `COMMIT`, and on any failure — a `COMMIT`
|
|
645
|
+
* refused while another connection reads (rollback-journal mode)
|
|
646
|
+
* included — a full `ROLLBACK`, which ends the transaction. IMMEDIATE
|
|
647
|
+
* takes the write lock up front, waiting on `busy_timeout`: a read-only
|
|
648
|
+
* first statement (`DROP TRIGGER IF EXISTS` of a missing trigger) cannot
|
|
649
|
+
* pin a WAL snapshot that a later write then fails on without waiting
|
|
650
|
+
* (`SQLITE_BUSY_SNAPSHOT`).
|
|
651
|
+
* - Inside a transaction (the adapter's own: `recreateTable`, a caller's
|
|
652
|
+
* `withTransaction` around a schema call) or another unit (the FTS
|
|
653
|
+
* rebuild wraps a drop and a create): a `SAVEPOINT`, rolled back to on
|
|
654
|
+
* failure. Nothing commits there, so nothing waits on another connection.
|
|
655
|
+
*
|
|
656
|
+
* "Open" is the adapter's view — its transaction state and the unit depth;
|
|
657
|
+
* the driver interface has no in-transaction flag. Every caller runs under
|
|
658
|
+
* `_stmt` or `_withExclusiveConnection`, so another context's transaction
|
|
659
|
+
* is never open on the connection meanwhile; one opened behind the
|
|
660
|
+
* adapter's back makes `BEGIN IMMEDIATE` fail without running the unit.
|
|
661
|
+
*
|
|
662
|
+
* Errors propagate as thrown: the caller's boundary maps SQLITE_BUSY —
|
|
663
|
+
* at `BEGIN`, `COMMIT` or any statement — to `LOCK_TIMEOUT`. A failing
|
|
664
|
+
* rollback never replaces the original error; it is logged as an error,
|
|
665
|
+
* because the connection may then still be in the transaction (the next
|
|
666
|
+
* `BEGIN` fails, autocommit statements would join it).
|
|
667
|
+
*/
|
|
668
|
+
private _atomically;
|
|
624
669
|
/** Lists FTS5/vec0 shadow virtual tables for a content table. */
|
|
625
670
|
private _listShadowTables;
|
|
626
671
|
/** {@link _listShadowTables} with each virtual table's `CREATE` statement. */
|
|
@@ -676,7 +721,7 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
676
721
|
private _syncVecIndexes;
|
|
677
722
|
/** Creates a vec0 virtual shadow table with sync triggers and seeds it from existing rows. */
|
|
678
723
|
private _createVecTable;
|
|
679
|
-
/** Drops a vec0 virtual table and its sync triggers. */
|
|
724
|
+
/** Drops a vec0 virtual table and its sync triggers — all or nothing (since 0.1.178). */
|
|
680
725
|
private _dropVecTable;
|
|
681
726
|
/** Drops all vec0 virtual shadow tables and triggers for a content table. */
|
|
682
727
|
private _dropAllVecTables;
|
package/dist/index.d.mts
CHANGED
|
@@ -354,6 +354,8 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
354
354
|
private _vectorPartitionFields;
|
|
355
355
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
356
356
|
private readonly _gate;
|
|
357
|
+
/** Open {@link _atomically} units of the current (synchronous) call. */
|
|
358
|
+
private _unitDepth;
|
|
357
359
|
private readonly _txOptions;
|
|
358
360
|
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
359
361
|
private readonly _ftsTokenizers;
|
|
@@ -364,13 +366,20 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
364
366
|
constructor(driver: TSqliteDriver, options?: SqliteAdapterOptions);
|
|
365
367
|
onFieldScanned(field: string, _type: unknown, metadata: TMetadataMap<AtscriptMetadata>): void;
|
|
366
368
|
/**
|
|
367
|
-
* A vector field
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
*
|
|
369
|
+
* A vector field (since 0.1.178): with sqlite-vec a Float32 BLOB
|
|
370
|
+
* ({@link float32Blob}), the column type `typeMapper` gives it — the mapper
|
|
371
|
+
* hands the formatter JSON text, converted when it holds an array of
|
|
372
|
+
* numbers (anything else is stored as is); without sqlite-vec, JSON text.
|
|
373
|
+
* Rows written before hold JSON text and are not rewritten; a vector
|
|
374
|
+
* changed by an array patch operator is stored as JSON text too
|
|
375
|
+
* (`resolveArrayOps` writes without `toStorage`). Reads take both forms.
|
|
376
|
+
* The extension is probed per value, not here — metadata is built where a
|
|
377
|
+
* busy probe must not run (see {@link _detectVectorSupport}) — so a busy
|
|
378
|
+
* probe fails the write with `LOCK_TIMEOUT`, never stores JSON text.
|
|
379
|
+
*
|
|
380
|
+
* Any other JSON `number[]` column reads a BLOB the same way: a view column
|
|
381
|
+
* reading a vector (the annotation is not passed to a referring field), or
|
|
382
|
+
* a field whose annotation was removed.
|
|
374
383
|
*/
|
|
375
384
|
formatValue(field: TDbFieldMeta): TValueFormatterPair | undefined;
|
|
376
385
|
isVectorSearchable(): boolean;
|
|
@@ -617,10 +626,46 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
617
626
|
private _probeFtsTokenizer;
|
|
618
627
|
/** Whether an existing FTS5 table has exactly the index's text columns, in order. */
|
|
619
628
|
private _ftsColumnsMatch;
|
|
620
|
-
/**
|
|
629
|
+
/**
|
|
630
|
+
* Creates an FTS5 virtual table with sync triggers and rebuilds the index —
|
|
631
|
+
* all or nothing (since 0.1.178, see {@link _atomically}).
|
|
632
|
+
*/
|
|
621
633
|
private _createFtsTable;
|
|
622
|
-
/** Drops an FTS5 virtual table and its sync triggers. */
|
|
634
|
+
/** Drops an FTS5 virtual table and its sync triggers — all or nothing (since 0.1.178). */
|
|
623
635
|
private _dropFtsTable;
|
|
636
|
+
/**
|
|
637
|
+
* Runs the synchronous `fn` as one all-or-nothing unit (since 0.1.178) —
|
|
638
|
+
* the FTS5 / vec0 shadow-table steps: a statement failing between a
|
|
639
|
+
* `CREATE VIRTUAL TABLE` and its triggers left the table without them, and
|
|
640
|
+
* the next sync, seeing the table, kept it: the index silently stopped
|
|
641
|
+
* following writes.
|
|
642
|
+
*
|
|
643
|
+
* - The unit opens the transaction itself (none is open, no unit around
|
|
644
|
+
* it): `BEGIN IMMEDIATE` … `COMMIT`, and on any failure — a `COMMIT`
|
|
645
|
+
* refused while another connection reads (rollback-journal mode)
|
|
646
|
+
* included — a full `ROLLBACK`, which ends the transaction. IMMEDIATE
|
|
647
|
+
* takes the write lock up front, waiting on `busy_timeout`: a read-only
|
|
648
|
+
* first statement (`DROP TRIGGER IF EXISTS` of a missing trigger) cannot
|
|
649
|
+
* pin a WAL snapshot that a later write then fails on without waiting
|
|
650
|
+
* (`SQLITE_BUSY_SNAPSHOT`).
|
|
651
|
+
* - Inside a transaction (the adapter's own: `recreateTable`, a caller's
|
|
652
|
+
* `withTransaction` around a schema call) or another unit (the FTS
|
|
653
|
+
* rebuild wraps a drop and a create): a `SAVEPOINT`, rolled back to on
|
|
654
|
+
* failure. Nothing commits there, so nothing waits on another connection.
|
|
655
|
+
*
|
|
656
|
+
* "Open" is the adapter's view — its transaction state and the unit depth;
|
|
657
|
+
* the driver interface has no in-transaction flag. Every caller runs under
|
|
658
|
+
* `_stmt` or `_withExclusiveConnection`, so another context's transaction
|
|
659
|
+
* is never open on the connection meanwhile; one opened behind the
|
|
660
|
+
* adapter's back makes `BEGIN IMMEDIATE` fail without running the unit.
|
|
661
|
+
*
|
|
662
|
+
* Errors propagate as thrown: the caller's boundary maps SQLITE_BUSY —
|
|
663
|
+
* at `BEGIN`, `COMMIT` or any statement — to `LOCK_TIMEOUT`. A failing
|
|
664
|
+
* rollback never replaces the original error; it is logged as an error,
|
|
665
|
+
* because the connection may then still be in the transaction (the next
|
|
666
|
+
* `BEGIN` fails, autocommit statements would join it).
|
|
667
|
+
*/
|
|
668
|
+
private _atomically;
|
|
624
669
|
/** Lists FTS5/vec0 shadow virtual tables for a content table. */
|
|
625
670
|
private _listShadowTables;
|
|
626
671
|
/** {@link _listShadowTables} with each virtual table's `CREATE` statement. */
|
|
@@ -676,7 +721,7 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
676
721
|
private _syncVecIndexes;
|
|
677
722
|
/** Creates a vec0 virtual shadow table with sync triggers and seeds it from existing rows. */
|
|
678
723
|
private _createVecTable;
|
|
679
|
-
/** Drops a vec0 virtual table and its sync triggers. */
|
|
724
|
+
/** Drops a vec0 virtual table and its sync triggers — all or nothing (since 0.1.178). */
|
|
680
725
|
private _dropVecTable;
|
|
681
726
|
/** Drops all vec0 virtual shadow tables and triggers for a content table. */
|
|
682
727
|
private _dropAllVecTables;
|
package/dist/index.mjs
CHANGED
|
@@ -855,6 +855,44 @@ function busyMapped(fn) {
|
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
857
|
/**
|
|
858
|
+
* A vector as sqlite-vec's compact form: float32, 4 bytes per number, in the
|
|
859
|
+
* host's byte order — the order sqlite-vec reads a BLOB in. The stored
|
|
860
|
+
* vector, its decode and the KNN query vector all use it.
|
|
861
|
+
*/
|
|
862
|
+
function float32Blob(values) {
|
|
863
|
+
return Buffer.from(new Float32Array(values).buffer);
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* Whether `field` is a JSON-stored array of numbers — a column that may hold
|
|
867
|
+
* a vector this adapter stored as a Float32 BLOB without being declared one
|
|
868
|
+
* (see `formatValue`).
|
|
869
|
+
*/
|
|
870
|
+
function isNumberArrayField(field) {
|
|
871
|
+
const type = field.type.type;
|
|
872
|
+
return field.storage === "json" && type.kind === "array" && type.of.type.kind === "" && type.of.type.designType === "number";
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* The numbers of a {@link float32Blob}; any other read value as is — JSON
|
|
876
|
+
* text is the mapper's to parse, and a blob whose length is not a multiple
|
|
877
|
+
* of 4 is no vector this adapter wrote. The bytes are copied into a fresh
|
|
878
|
+
* buffer first: a driver's blob is often a slice of a pooled `ArrayBuffer` at
|
|
879
|
+
* an offset a `Float32Array` view cannot start at (it needs 4-byte alignment).
|
|
880
|
+
*/
|
|
881
|
+
function decodeFloat32Blob(value) {
|
|
882
|
+
if (!(value instanceof Uint8Array) || value.byteLength % 4 !== 0) return value;
|
|
883
|
+
return Array.from(new Float32Array(new Uint8Array(value).buffer));
|
|
884
|
+
}
|
|
885
|
+
/** The numbers of JSON text holding an array of numbers, else `undefined`. */
|
|
886
|
+
function jsonNumberArray(text) {
|
|
887
|
+
let parsed;
|
|
888
|
+
try {
|
|
889
|
+
parsed = JSON.parse(text);
|
|
890
|
+
} catch {
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
return Array.isArray(parsed) && parsed.every((n) => typeof n === "number") ? parsed : void 0;
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
858
896
|
* SQLite adapter for {@link AtscriptDbTable}.
|
|
859
897
|
*
|
|
860
898
|
* Accepts any {@link TSqliteDriver} implementation — the actual SQLite engine
|
|
@@ -939,6 +977,8 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
939
977
|
_vectorPartitionFields = /* @__PURE__ */ new Map();
|
|
940
978
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
941
979
|
_gate;
|
|
980
|
+
/** Open {@link _atomically} units of the current (synchronous) call. */
|
|
981
|
+
_unitDepth = 0;
|
|
942
982
|
_txOptions;
|
|
943
983
|
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
944
984
|
_ftsTokenizers;
|
|
@@ -978,33 +1018,37 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
978
1018
|
}
|
|
979
1019
|
}
|
|
980
1020
|
/**
|
|
981
|
-
* A vector field
|
|
982
|
-
*
|
|
983
|
-
*
|
|
984
|
-
*
|
|
985
|
-
*
|
|
986
|
-
*
|
|
987
|
-
*
|
|
1021
|
+
* A vector field (since 0.1.178): with sqlite-vec a Float32 BLOB
|
|
1022
|
+
* ({@link float32Blob}), the column type `typeMapper` gives it — the mapper
|
|
1023
|
+
* hands the formatter JSON text, converted when it holds an array of
|
|
1024
|
+
* numbers (anything else is stored as is); without sqlite-vec, JSON text.
|
|
1025
|
+
* Rows written before hold JSON text and are not rewritten; a vector
|
|
1026
|
+
* changed by an array patch operator is stored as JSON text too
|
|
1027
|
+
* (`resolveArrayOps` writes without `toStorage`). Reads take both forms.
|
|
1028
|
+
* The extension is probed per value, not here — metadata is built where a
|
|
1029
|
+
* busy probe must not run (see {@link _detectVectorSupport}) — so a busy
|
|
1030
|
+
* probe fails the write with `LOCK_TIMEOUT`, never stores JSON text.
|
|
1031
|
+
*
|
|
1032
|
+
* Any other JSON `number[]` column reads a BLOB the same way: a view column
|
|
1033
|
+
* reading a vector (the annotation is not passed to a referring field), or
|
|
1034
|
+
* a field whose annotation was removed.
|
|
988
1035
|
*/
|
|
989
1036
|
formatValue(field) {
|
|
990
|
-
if (!this._vectorFields.has(field.path)) return
|
|
1037
|
+
if (!this._vectorFields.has(field.path)) return isNumberArrayField(field) ? {
|
|
1038
|
+
toStorage: (value) => value,
|
|
1039
|
+
fromStorage: decodeFloat32Blob
|
|
1040
|
+
} : void 0;
|
|
991
1041
|
return {
|
|
992
1042
|
toStorage: (value) => {
|
|
1043
|
+
if (typeof value === "string") {
|
|
1044
|
+
if (!this._detectVectorSupport()) return value;
|
|
1045
|
+
const values = jsonNumberArray(value);
|
|
1046
|
+
return values ? float32Blob(values) : value;
|
|
1047
|
+
}
|
|
993
1048
|
if (!Array.isArray(value)) return value;
|
|
994
|
-
return this._detectVectorSupport() ?
|
|
1049
|
+
return this._detectVectorSupport() ? float32Blob(value) : JSON.stringify(value);
|
|
995
1050
|
},
|
|
996
|
-
fromStorage:
|
|
997
|
-
if (value instanceof Uint8Array) {
|
|
998
|
-
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
999
|
-
return Array.from(new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4)));
|
|
1000
|
-
}
|
|
1001
|
-
if (typeof value === "string") try {
|
|
1002
|
-
return JSON.parse(value);
|
|
1003
|
-
} catch {
|
|
1004
|
-
return value;
|
|
1005
|
-
}
|
|
1006
|
-
return value;
|
|
1007
|
-
}
|
|
1051
|
+
fromStorage: decodeFloat32Blob
|
|
1008
1052
|
};
|
|
1009
1053
|
}
|
|
1010
1054
|
isVectorSearchable() {
|
|
@@ -1976,8 +2020,10 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1976
2020
|
action: "rebuild"
|
|
1977
2021
|
}, ftsTable, () => {
|
|
1978
2022
|
this._probeFtsTokenizer(index);
|
|
1979
|
-
this.
|
|
1980
|
-
|
|
2023
|
+
this._atomically(() => {
|
|
2024
|
+
this._dropFtsTable(ftsTable);
|
|
2025
|
+
this._createFtsTable(tableName, ftsTable, index);
|
|
2026
|
+
});
|
|
1981
2027
|
});
|
|
1982
2028
|
}
|
|
1983
2029
|
return changes;
|
|
@@ -2007,42 +2053,107 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
2007
2053
|
const desired = splitFulltextFields(index).text.map((f) => f.name);
|
|
2008
2054
|
return live.length === desired.length && live.every((name, i) => name === desired[i]);
|
|
2009
2055
|
}
|
|
2010
|
-
/**
|
|
2056
|
+
/**
|
|
2057
|
+
* Creates an FTS5 virtual table with sync triggers and rebuilds the index —
|
|
2058
|
+
* all or nothing (since 0.1.178, see {@link _atomically}).
|
|
2059
|
+
*/
|
|
2011
2060
|
_createFtsTable(tableName, ftsTable, index) {
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2061
|
+
this._atomically(() => {
|
|
2062
|
+
const fields = splitFulltextFields(index).text;
|
|
2063
|
+
const fieldList = fields.map((f) => `"${esc(f.name)}"`).join(", ");
|
|
2064
|
+
const tokenizer = ftsTokenizer(index, this._configuredFtsTokenizer(index));
|
|
2065
|
+
const tokenize = tokenizer ? `, tokenize='${tokenizer}'` : "";
|
|
2066
|
+
const prefix = this._ftsPrefix ? `, prefix='${this._ftsPrefix}'` : "";
|
|
2067
|
+
const createSql = `CREATE VIRTUAL TABLE IF NOT EXISTS "${esc(ftsTable)}" USING fts5(${fieldList}, content='${tableName.replace(/'/g, "''")}', content_rowid='rowid'${tokenize}${prefix})`;
|
|
2068
|
+
this._log(createSql);
|
|
2069
|
+
this.driver.exec(createSql);
|
|
2070
|
+
const newFields = fields.map((f) => `new."${esc(f.name)}"`).join(", ");
|
|
2071
|
+
const oldFields = fields.map((f) => `old."${esc(f.name)}"`).join(", ");
|
|
2072
|
+
const ef = esc(ftsTable);
|
|
2073
|
+
const aiSql = `CREATE TRIGGER IF NOT EXISTS "${esc(ftsTable + "__ai")}" AFTER INSERT ON "${esc(tableName)}" BEGIN INSERT INTO "${ef}"(rowid, ${fieldList}) VALUES (new.rowid, ${newFields}); END`;
|
|
2074
|
+
this._log(aiSql);
|
|
2075
|
+
this.driver.exec(aiSql);
|
|
2076
|
+
const adSql = `CREATE TRIGGER IF NOT EXISTS "${esc(ftsTable + "__ad")}" AFTER DELETE ON "${esc(tableName)}" BEGIN INSERT INTO "${ef}"("${ef}", rowid, ${fieldList}) VALUES ('delete', old.rowid, ${oldFields}); END`;
|
|
2077
|
+
this._log(adSql);
|
|
2078
|
+
this.driver.exec(adSql);
|
|
2079
|
+
const auSql = `CREATE TRIGGER IF NOT EXISTS "${esc(ftsTable + "__au")}" AFTER UPDATE ON "${esc(tableName)}" BEGIN INSERT INTO "${ef}"("${ef}", rowid, ${fieldList}) VALUES ('delete', old.rowid, ${oldFields}); INSERT INTO "${ef}"(rowid, ${fieldList}) VALUES (new.rowid, ${newFields}); END`;
|
|
2080
|
+
this._log(auSql);
|
|
2081
|
+
this.driver.exec(auSql);
|
|
2082
|
+
const rebuildSql = `INSERT INTO "${ef}"("${ef}") VALUES ('rebuild')`;
|
|
2083
|
+
this._log(rebuildSql);
|
|
2084
|
+
this.driver.exec(rebuildSql);
|
|
2085
|
+
});
|
|
2086
|
+
}
|
|
2087
|
+
/** Drops an FTS5 virtual table and its sync triggers — all or nothing (since 0.1.178). */
|
|
2037
2088
|
_dropFtsTable(ftsTable) {
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2089
|
+
this._atomically(() => {
|
|
2090
|
+
for (const suffix of [
|
|
2091
|
+
"__ai",
|
|
2092
|
+
"__ad",
|
|
2093
|
+
"__au"
|
|
2094
|
+
]) this.driver.exec(`DROP TRIGGER IF EXISTS "${esc(ftsTable + suffix)}"`);
|
|
2095
|
+
const sql = `DROP TABLE IF EXISTS "${esc(ftsTable)}"`;
|
|
2096
|
+
this._log(sql);
|
|
2097
|
+
this.driver.exec(sql);
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2100
|
+
/**
|
|
2101
|
+
* Runs the synchronous `fn` as one all-or-nothing unit (since 0.1.178) —
|
|
2102
|
+
* the FTS5 / vec0 shadow-table steps: a statement failing between a
|
|
2103
|
+
* `CREATE VIRTUAL TABLE` and its triggers left the table without them, and
|
|
2104
|
+
* the next sync, seeing the table, kept it: the index silently stopped
|
|
2105
|
+
* following writes.
|
|
2106
|
+
*
|
|
2107
|
+
* - The unit opens the transaction itself (none is open, no unit around
|
|
2108
|
+
* it): `BEGIN IMMEDIATE` … `COMMIT`, and on any failure — a `COMMIT`
|
|
2109
|
+
* refused while another connection reads (rollback-journal mode)
|
|
2110
|
+
* included — a full `ROLLBACK`, which ends the transaction. IMMEDIATE
|
|
2111
|
+
* takes the write lock up front, waiting on `busy_timeout`: a read-only
|
|
2112
|
+
* first statement (`DROP TRIGGER IF EXISTS` of a missing trigger) cannot
|
|
2113
|
+
* pin a WAL snapshot that a later write then fails on without waiting
|
|
2114
|
+
* (`SQLITE_BUSY_SNAPSHOT`).
|
|
2115
|
+
* - Inside a transaction (the adapter's own: `recreateTable`, a caller's
|
|
2116
|
+
* `withTransaction` around a schema call) or another unit (the FTS
|
|
2117
|
+
* rebuild wraps a drop and a create): a `SAVEPOINT`, rolled back to on
|
|
2118
|
+
* failure. Nothing commits there, so nothing waits on another connection.
|
|
2119
|
+
*
|
|
2120
|
+
* "Open" is the adapter's view — its transaction state and the unit depth;
|
|
2121
|
+
* the driver interface has no in-transaction flag. Every caller runs under
|
|
2122
|
+
* `_stmt` or `_withExclusiveConnection`, so another context's transaction
|
|
2123
|
+
* is never open on the connection meanwhile; one opened behind the
|
|
2124
|
+
* adapter's back makes `BEGIN IMMEDIATE` fail without running the unit.
|
|
2125
|
+
*
|
|
2126
|
+
* Errors propagate as thrown: the caller's boundary maps SQLITE_BUSY —
|
|
2127
|
+
* at `BEGIN`, `COMMIT` or any statement — to `LOCK_TIMEOUT`. A failing
|
|
2128
|
+
* rollback never replaces the original error; it is logged as an error,
|
|
2129
|
+
* because the connection may then still be in the transaction (the next
|
|
2130
|
+
* `BEGIN` fails, autocommit statements would join it).
|
|
2131
|
+
*/
|
|
2132
|
+
_atomically(fn) {
|
|
2133
|
+
const [begin, end, undo] = this._unitDepth > 0 || this._getTransactionState() !== void 0 ? [
|
|
2134
|
+
`SAVEPOINT "atscript_unit"`,
|
|
2135
|
+
`RELEASE "atscript_unit"`,
|
|
2136
|
+
[`ROLLBACK TO "atscript_unit"`, `RELEASE "atscript_unit"`]
|
|
2137
|
+
] : [
|
|
2138
|
+
"BEGIN IMMEDIATE",
|
|
2139
|
+
"COMMIT",
|
|
2140
|
+
["ROLLBACK"]
|
|
2141
|
+
];
|
|
2142
|
+
this.driver.exec(begin);
|
|
2143
|
+
this._unitDepth++;
|
|
2144
|
+
try {
|
|
2145
|
+
fn();
|
|
2146
|
+
this.driver.exec(end);
|
|
2147
|
+
} catch (error) {
|
|
2148
|
+
try {
|
|
2149
|
+
for (const sql of undo) this.driver.exec(sql);
|
|
2150
|
+
} catch (undoError) {
|
|
2151
|
+
this.logger.error(`[atscript-db-sqlite] ${undo.join("; ")} failed after a failed schema step — the connection may still be in its transaction: ${undoError?.message}`);
|
|
2152
|
+
}
|
|
2153
|
+
throw error;
|
|
2154
|
+
} finally {
|
|
2155
|
+
this._unitDepth--;
|
|
2156
|
+
}
|
|
2046
2157
|
}
|
|
2047
2158
|
/** Lists FTS5/vec0 shadow virtual tables for a content table. */
|
|
2048
2159
|
_listShadowTables(tableName, kind) {
|
|
@@ -2142,7 +2253,7 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
2142
2253
|
_buildVectorSearchBase(vector, query, indexName) {
|
|
2143
2254
|
const { vec, partitionPhysicalNames } = this._resolveVectorIndex(indexName);
|
|
2144
2255
|
if (vector.length !== vec.dimensions) throw new Error(`Vector dimension mismatch: index "${vec.indexName}" expects ${vec.dimensions}, got ${vector.length}`);
|
|
2145
|
-
const vecBuf =
|
|
2256
|
+
const vecBuf = float32Blob(vector);
|
|
2146
2257
|
const controls = query.controls || {};
|
|
2147
2258
|
const limit = controls.$limit ?? 20;
|
|
2148
2259
|
const skip = controls.$skip ?? 0;
|
|
@@ -2285,51 +2396,55 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
2285
2396
|
}
|
|
2286
2397
|
for (const c of partitionCols) if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(c.physicalName)) throw new Error(`vec0 partition column name "${c.physicalName}" is not a safe identifier (only [A-Za-z_][A-Za-z0-9_]* is allowed for @db.search.filter fields on SQLite).`);
|
|
2287
2398
|
const ddlCols = [partitionCols.map((c) => `${c.physicalName} ${c.sqlType} partition key`).join(", "), `embedding float[${vec.dimensions}] distance_metric=${metric}`].filter(Boolean).join(", ");
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2399
|
+
this._atomically(() => {
|
|
2400
|
+
const createSql = `CREATE VIRTUAL TABLE IF NOT EXISTS "${esc(vecTable)}" USING vec0(${ddlCols})`;
|
|
2401
|
+
this._log(createSql);
|
|
2402
|
+
this.driver.exec(createSql);
|
|
2403
|
+
const partCols = partitionCols.map((c) => `"${esc(c.physicalName)}"`);
|
|
2404
|
+
const embCol = `"${esc(embeddingCol)}"`;
|
|
2405
|
+
const insertCols = [
|
|
2406
|
+
"rowid",
|
|
2407
|
+
...partCols,
|
|
2408
|
+
"embedding"
|
|
2409
|
+
].join(", ");
|
|
2410
|
+
const insertNewVals = [
|
|
2411
|
+
"new.rowid",
|
|
2412
|
+
...partitionCols.map((c) => `new."${esc(c.physicalName)}"`),
|
|
2413
|
+
`new.${embCol}`
|
|
2414
|
+
].join(", ");
|
|
2415
|
+
const seedColList = [
|
|
2416
|
+
"rowid",
|
|
2417
|
+
...partCols,
|
|
2418
|
+
embCol
|
|
2419
|
+
].join(", ");
|
|
2420
|
+
const ev = esc(vecTable);
|
|
2421
|
+
const et = esc(tableName);
|
|
2422
|
+
const aiSql = `CREATE TRIGGER IF NOT EXISTS "${esc(vecTable + "__ai")}" AFTER INSERT ON "${et}" WHEN new.${embCol} IS NOT NULL BEGIN INSERT INTO "${ev}"(${insertCols}) VALUES(${insertNewVals}); END`;
|
|
2423
|
+
this._log(aiSql);
|
|
2424
|
+
this.driver.exec(aiSql);
|
|
2425
|
+
const adSql = `CREATE TRIGGER IF NOT EXISTS "${esc(vecTable + "__ad")}" AFTER DELETE ON "${et}" BEGIN DELETE FROM "${ev}" WHERE rowid = old.rowid; END`;
|
|
2426
|
+
this._log(adSql);
|
|
2427
|
+
this.driver.exec(adSql);
|
|
2428
|
+
const auSql = `CREATE TRIGGER IF NOT EXISTS "${esc(vecTable + "__au")}" AFTER UPDATE ON "${et}" BEGIN DELETE FROM "${ev}" WHERE rowid = old.rowid; INSERT INTO "${ev}"(${insertCols}) SELECT ${insertNewVals} WHERE new.${embCol} IS NOT NULL; END`;
|
|
2429
|
+
this._log(auSql);
|
|
2430
|
+
this.driver.exec(auSql);
|
|
2431
|
+
const seedSql = `INSERT INTO "${ev}"(${insertCols}) SELECT ${seedColList} FROM "${et}" WHERE ${embCol} IS NOT NULL`;
|
|
2432
|
+
this._log(seedSql);
|
|
2433
|
+
this.driver.exec(seedSql);
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
/** Drops a vec0 virtual table and its sync triggers — all or nothing (since 0.1.178). */
|
|
2324
2437
|
_dropVecTable(vecTable) {
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2438
|
+
this._atomically(() => {
|
|
2439
|
+
for (const suffix of [
|
|
2440
|
+
"__ai",
|
|
2441
|
+
"__ad",
|
|
2442
|
+
"__au"
|
|
2443
|
+
]) this.driver.exec(`DROP TRIGGER IF EXISTS "${esc(vecTable + suffix)}"`);
|
|
2444
|
+
const sql = `DROP TABLE IF EXISTS "${esc(vecTable)}"`;
|
|
2445
|
+
this._log(sql);
|
|
2446
|
+
this.driver.exec(sql);
|
|
2447
|
+
});
|
|
2333
2448
|
}
|
|
2334
2449
|
/** Drops all vec0 virtual shadow tables and triggers for a content table. */
|
|
2335
2450
|
_dropAllVecTables(tableName) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atscript/db-sqlite",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.178",
|
|
4
4
|
"description": "SQLite adapter for @atscript/db with swappable driver support.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"atscript",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"access": "public"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@atscript/db-sql-tools": "^0.1.
|
|
39
|
+
"@atscript/db-sql-tools": "^0.1.178"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"@atscript/core": "^0.2.12",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"@atscript/typescript": "^0.2.12",
|
|
53
53
|
"@uniqu/core": "^0.2.2",
|
|
54
54
|
"better-sqlite3": ">=11.0.0",
|
|
55
|
-
"@atscript/db": "^0.1.
|
|
55
|
+
"@atscript/db": "^0.1.178"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {
|
|
58
58
|
"better-sqlite3": {
|