@atscript/db-sqlite 0.1.176 → 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 +285 -120
- package/dist/index.d.cts +77 -6
- package/dist/index.d.mts +77 -6
- package/dist/index.mjs +285 -120
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -825,18 +825,73 @@ function ftsLanguageWarning(index, configured) {
|
|
|
825
825
|
//#endregion
|
|
826
826
|
//#region src/sqlite-adapter.ts
|
|
827
827
|
/**
|
|
828
|
-
*
|
|
829
|
-
*
|
|
830
|
-
*
|
|
828
|
+
* Whether `error` is an `SQLITE_BUSY` driver error — another connection held
|
|
829
|
+
* the database lock past `busy_timeout`. Any extended busy code counts (`code`
|
|
830
|
+
* starting with `SQLITE_BUSY`, or a numeric `errcode` whose primary code is
|
|
831
|
+
* 5); `SQLITE_LOCKED` (6) is a conflict on the same connection, not
|
|
832
|
+
* contention. A `DbError` never is.
|
|
831
833
|
*/
|
|
832
|
-
function
|
|
833
|
-
if (!error || typeof error !== "object") return
|
|
834
|
+
function isBusy(error) {
|
|
835
|
+
if (!error || typeof error !== "object") return false;
|
|
834
836
|
const { code, errcode } = error;
|
|
835
|
-
return typeof code === "string" && code.startsWith("SQLITE_BUSY") || typeof errcode === "number" && (errcode & 255) === 5
|
|
837
|
+
return typeof code === "string" && code.startsWith("SQLITE_BUSY") || typeof errcode === "number" && (errcode & 255) === 5;
|
|
838
|
+
}
|
|
839
|
+
/**
|
|
840
|
+
* The retryable `LOCK_TIMEOUT` of an {@link isBusy} driver error, with the
|
|
841
|
+
* driver error as `cause`; any other error as is (so mapping twice is harmless).
|
|
842
|
+
*/
|
|
843
|
+
function mapBusy(error) {
|
|
844
|
+
return isBusy(error) ? new DbError("LOCK_TIMEOUT", [{
|
|
836
845
|
path: "",
|
|
837
846
|
message: error.message
|
|
838
847
|
}], void 0, { cause: error }) : error;
|
|
839
848
|
}
|
|
849
|
+
/** Runs the synchronous `fn`, rethrowing an `SQLITE_BUSY` as {@link mapBusy}'s `LOCK_TIMEOUT`. */
|
|
850
|
+
function busyMapped(fn) {
|
|
851
|
+
try {
|
|
852
|
+
return fn();
|
|
853
|
+
} catch (error) {
|
|
854
|
+
throw mapBusy(error);
|
|
855
|
+
}
|
|
856
|
+
}
|
|
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
|
+
}
|
|
840
895
|
/**
|
|
841
896
|
* SQLite adapter for {@link AtscriptDbTable}.
|
|
842
897
|
*
|
|
@@ -922,6 +977,8 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
922
977
|
_vectorPartitionFields = /* @__PURE__ */ new Map();
|
|
923
978
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
924
979
|
_gate;
|
|
980
|
+
/** Open {@link _atomically} units of the current (synchronous) call. */
|
|
981
|
+
_unitDepth = 0;
|
|
925
982
|
_txOptions;
|
|
926
983
|
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
927
984
|
_ftsTokenizers;
|
|
@@ -960,42 +1017,58 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
960
1017
|
else this._vectorPartitionFields.set(indexName, [field]);
|
|
961
1018
|
}
|
|
962
1019
|
}
|
|
1020
|
+
/**
|
|
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.
|
|
1035
|
+
*/
|
|
963
1036
|
formatValue(field) {
|
|
964
|
-
if (!this._vectorFields.has(field.path)) return
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
if (value instanceof Buffer || value instanceof Uint8Array) {
|
|
969
|
-
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
970
|
-
const arr = new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4));
|
|
971
|
-
return Array.from(arr);
|
|
972
|
-
}
|
|
973
|
-
return value;
|
|
974
|
-
}
|
|
975
|
-
};
|
|
1037
|
+
if (!this._vectorFields.has(field.path)) return isNumberArrayField(field) ? {
|
|
1038
|
+
toStorage: (value) => value,
|
|
1039
|
+
fromStorage: decodeFloat32Blob
|
|
1040
|
+
} : void 0;
|
|
976
1041
|
return {
|
|
977
|
-
toStorage: (value) =>
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
return value;
|
|
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;
|
|
983
1047
|
}
|
|
984
|
-
return value;
|
|
985
|
-
|
|
1048
|
+
if (!Array.isArray(value)) return value;
|
|
1049
|
+
return this._detectVectorSupport() ? float32Blob(value) : JSON.stringify(value);
|
|
1050
|
+
},
|
|
1051
|
+
fromStorage: decodeFloat32Blob
|
|
986
1052
|
};
|
|
987
1053
|
}
|
|
988
1054
|
isVectorSearchable() {
|
|
989
1055
|
if (this._vectorFields.size === 0) return false;
|
|
990
1056
|
return this._detectVectorSupport();
|
|
991
1057
|
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Whether sqlite-vec is loaded: the driver's `hasVectorExt`, else a probe,
|
|
1060
|
+
* answered once. A busy probe answers nothing — it throws the retryable
|
|
1061
|
+
* `LOCK_TIMEOUT` (the caller's write, search or sync fails, the next call
|
|
1062
|
+
* probes again).
|
|
1063
|
+
*/
|
|
992
1064
|
_detectVectorSupport() {
|
|
993
1065
|
if (this._supportsVector !== void 0) return this._supportsVector;
|
|
994
1066
|
if (this.driver.hasVectorExt !== void 0) this._supportsVector = this.driver.hasVectorExt;
|
|
995
1067
|
else try {
|
|
996
1068
|
this.driver.get("SELECT vec_version()");
|
|
997
1069
|
this._supportsVector = true;
|
|
998
|
-
} catch {
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
if (isBusy(error)) throw mapBusy(error);
|
|
999
1072
|
this._supportsVector = false;
|
|
1000
1073
|
}
|
|
1001
1074
|
if (!this._supportsVector && this._vectorFields.size > 0) this._log("[atscript-db-sqlite] sqlite-vec extension not available — vector fields will be stored as JSON TEXT (no similarity search).");
|
|
@@ -1020,11 +1093,15 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1020
1093
|
* exclusive hold) it runs immediately; otherwise it waits until no
|
|
1021
1094
|
* transaction is open on the connection. The `held` check and the statement
|
|
1022
1095
|
* run in the same synchronous segment, so they cannot interleave with a
|
|
1023
|
-
* `BEGIN` from another context.
|
|
1096
|
+
* `BEGIN` from another context. A busy statement rejects with `LOCK_TIMEOUT`.
|
|
1024
1097
|
*/
|
|
1025
1098
|
async _stmt(fn) {
|
|
1026
|
-
|
|
1027
|
-
|
|
1099
|
+
try {
|
|
1100
|
+
if (!this._gate.held || this._ownsConnection()) return fn();
|
|
1101
|
+
return await this._gate.runWhenFree(fn, this._waitOpts());
|
|
1102
|
+
} catch (error) {
|
|
1103
|
+
throw mapBusy(error);
|
|
1104
|
+
}
|
|
1028
1105
|
}
|
|
1029
1106
|
/**
|
|
1030
1107
|
* Holds the connection for the duration of `fn` WITHOUT opening a
|
|
@@ -1035,11 +1112,15 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1035
1112
|
* request's transaction (PRAGMA changes are no-ops inside one). Inside our
|
|
1036
1113
|
* own transaction `fn` runs directly; re-entrant for the same async
|
|
1037
1114
|
* context; nested `withTransaction` calls inside `fn` still BEGIN/COMMIT
|
|
1038
|
-
* on the held connection.
|
|
1115
|
+
* on the held connection. A busy step rejects with `LOCK_TIMEOUT`, after
|
|
1116
|
+
* `fn`'s own `finally` blocks restored the connection's PRAGMAs.
|
|
1039
1117
|
*/
|
|
1040
1118
|
async _withExclusiveConnection(fn) {
|
|
1041
|
-
|
|
1042
|
-
|
|
1119
|
+
try {
|
|
1120
|
+
return this._getTransactionState() !== void 0 ? await fn() : await this._gate.runExclusive(fn, this._waitOpts());
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
throw mapBusy(error);
|
|
1123
|
+
}
|
|
1043
1124
|
}
|
|
1044
1125
|
async _beginTransaction() {
|
|
1045
1126
|
const holdsGate = !this._gate.heldByCurrentContext;
|
|
@@ -1050,7 +1131,7 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1050
1131
|
this.driver.exec("BEGIN IMMEDIATE");
|
|
1051
1132
|
} catch (error) {
|
|
1052
1133
|
state.release();
|
|
1053
|
-
throw error;
|
|
1134
|
+
throw mapBusy(error);
|
|
1054
1135
|
}
|
|
1055
1136
|
return state;
|
|
1056
1137
|
}
|
|
@@ -1359,10 +1440,11 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1359
1440
|
/**
|
|
1360
1441
|
* Seeds the sqlite_sequence table for auto-increment fields that have a start value.
|
|
1361
1442
|
* Only applies once per adapter instance (idempotent via INSERT OR IGNORE + flag).
|
|
1443
|
+
* The flag is set once the seed ran: a failed (busy) seed is retried by the
|
|
1444
|
+
* next `ensureTable`.
|
|
1362
1445
|
*/
|
|
1363
1446
|
_seedIncrementStart() {
|
|
1364
1447
|
if (this._incrementSeeded) return;
|
|
1365
|
-
this._incrementSeeded = true;
|
|
1366
1448
|
const tableName = this.resolveTableName();
|
|
1367
1449
|
for (const def of this._table.defaults.values()) if (def.kind === "fn" && def.fn === "increment" && typeof def.start === "number") {
|
|
1368
1450
|
const seedSql = `INSERT OR IGNORE INTO sqlite_sequence(name, seq) VALUES(?, ?)`;
|
|
@@ -1371,6 +1453,7 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1371
1453
|
this.driver.run(seedSql, params);
|
|
1372
1454
|
break;
|
|
1373
1455
|
}
|
|
1456
|
+
this._incrementSeeded = true;
|
|
1374
1457
|
}
|
|
1375
1458
|
async ensureView() {
|
|
1376
1459
|
return this._stmt(() => {
|
|
@@ -1637,6 +1720,14 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1637
1720
|
async syncIndexes() {
|
|
1638
1721
|
return this._withExclusiveConnection(() => this._syncIndexes(false));
|
|
1639
1722
|
}
|
|
1723
|
+
/**
|
|
1724
|
+
* The plan reads the live index state (`PRAGMA index_list` / `index_info`)
|
|
1725
|
+
* through the gate like {@link syncIndexes}: never inside another context's
|
|
1726
|
+
* open transaction, and a busy read rejects with `LOCK_TIMEOUT`.
|
|
1727
|
+
*/
|
|
1728
|
+
async planIndexes() {
|
|
1729
|
+
return this._withExclusiveConnection(() => this._syncIndexes(true));
|
|
1730
|
+
}
|
|
1640
1731
|
async _syncIndexes(dryRun) {
|
|
1641
1732
|
const tableName = this.resolveTableName();
|
|
1642
1733
|
const changes = await this.syncIndexesWithDiff({
|
|
@@ -1650,12 +1741,12 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1650
1741
|
const cols = index.fields.map((f) => `"${esc(f.name)}" ${f.sort === "desc" ? "DESC" : "ASC"}`).join(", ");
|
|
1651
1742
|
const sql = `CREATE ${unique}INDEX IF NOT EXISTS "${esc(index.key)}" ON "${esc(tableName)}" (${cols})`;
|
|
1652
1743
|
this._log(sql);
|
|
1653
|
-
this.driver.exec(sql);
|
|
1744
|
+
busyMapped(() => this.driver.exec(sql));
|
|
1654
1745
|
},
|
|
1655
1746
|
dropIndex: async (name) => {
|
|
1656
1747
|
const sql = `DROP INDEX IF EXISTS "${esc(name)}"`;
|
|
1657
1748
|
this._log(sql);
|
|
1658
|
-
this.driver.exec(sql);
|
|
1749
|
+
busyMapped(() => this.driver.exec(sql));
|
|
1659
1750
|
},
|
|
1660
1751
|
skipIndex: (index) => index.type === "fulltext" || index.type === "geo" ? null : void 0
|
|
1661
1752
|
});
|
|
@@ -1929,8 +2020,10 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1929
2020
|
action: "rebuild"
|
|
1930
2021
|
}, ftsTable, () => {
|
|
1931
2022
|
this._probeFtsTokenizer(index);
|
|
1932
|
-
this.
|
|
1933
|
-
|
|
2023
|
+
this._atomically(() => {
|
|
2024
|
+
this._dropFtsTable(ftsTable);
|
|
2025
|
+
this._createFtsTable(tableName, ftsTable, index);
|
|
2026
|
+
});
|
|
1934
2027
|
});
|
|
1935
2028
|
}
|
|
1936
2029
|
return changes;
|
|
@@ -1960,42 +2053,107 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1960
2053
|
const desired = splitFulltextFields(index).text.map((f) => f.name);
|
|
1961
2054
|
return live.length === desired.length && live.every((name, i) => name === desired[i]);
|
|
1962
2055
|
}
|
|
1963
|
-
/**
|
|
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
|
+
*/
|
|
1964
2060
|
_createFtsTable(tableName, ftsTable, index) {
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
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). */
|
|
1990
2088
|
_dropFtsTable(ftsTable) {
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
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
|
+
}
|
|
1999
2157
|
}
|
|
2000
2158
|
/** Lists FTS5/vec0 shadow virtual tables for a content table. */
|
|
2001
2159
|
_listShadowTables(tableName, kind) {
|
|
@@ -2095,7 +2253,7 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
2095
2253
|
_buildVectorSearchBase(vector, query, indexName) {
|
|
2096
2254
|
const { vec, partitionPhysicalNames } = this._resolveVectorIndex(indexName);
|
|
2097
2255
|
if (vector.length !== vec.dimensions) throw new Error(`Vector dimension mismatch: index "${vec.indexName}" expects ${vec.dimensions}, got ${vector.length}`);
|
|
2098
|
-
const vecBuf =
|
|
2256
|
+
const vecBuf = float32Blob(vector);
|
|
2099
2257
|
const controls = query.controls || {};
|
|
2100
2258
|
const limit = controls.$limit ?? 20;
|
|
2101
2259
|
const skip = controls.$skip ?? 0;
|
|
@@ -2129,7 +2287,9 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
2129
2287
|
* Geo search is available when SQLite has math functions
|
|
2130
2288
|
* (`SQLITE_ENABLE_MATH_FUNCTIONS` — on by default in better-sqlite3 builds).
|
|
2131
2289
|
* Distance is computed per row via haversine; declared geo indexes have no
|
|
2132
|
-
* physical artifact on SQLite.
|
|
2290
|
+
* physical artifact on SQLite. Probed once; a busy probe throws the
|
|
2291
|
+
* retryable `LOCK_TIMEOUT` and the next call probes again (a `false` would
|
|
2292
|
+
* turn into a non-retryable `GEO_NOT_SUPPORTED`).
|
|
2133
2293
|
*/
|
|
2134
2294
|
isGeoSearchable() {
|
|
2135
2295
|
return this._detectMathFns();
|
|
@@ -2138,7 +2298,8 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
2138
2298
|
if (this._supportsMathFns === void 0) try {
|
|
2139
2299
|
this.driver.get("SELECT radians(0) AS r");
|
|
2140
2300
|
this._supportsMathFns = true;
|
|
2141
|
-
} catch {
|
|
2301
|
+
} catch (error) {
|
|
2302
|
+
if (isBusy(error)) throw mapBusy(error);
|
|
2142
2303
|
this._supportsMathFns = false;
|
|
2143
2304
|
this._log("[atscript-db-sqlite] SQLite math functions unavailable — geo search disabled (rebuild SQLite with SQLITE_ENABLE_MATH_FUNCTIONS).");
|
|
2144
2305
|
}
|
|
@@ -2235,51 +2396,55 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
2235
2396
|
}
|
|
2236
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).`);
|
|
2237
2398
|
const ddlCols = [partitionCols.map((c) => `${c.physicalName} ${c.sqlType} partition key`).join(", "), `embedding float[${vec.dimensions}] distance_metric=${metric}`].filter(Boolean).join(", ");
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
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). */
|
|
2274
2437
|
_dropVecTable(vecTable) {
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
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
|
+
});
|
|
2283
2448
|
}
|
|
2284
2449
|
/** Drops all vec0 virtual shadow tables and triggers for a content table. */
|
|
2285
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": {
|