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