@atscript/db-sqlite 0.1.175 → 0.1.177

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,35 @@ 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
+ }
841
858
  /**
842
859
  * SQLite adapter for {@link AtscriptDbTable}.
843
860
  *
@@ -961,22 +978,27 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
961
978
  else this._vectorPartitionFields.set(indexName, [field]);
962
979
  }
963
980
  }
981
+ /**
982
+ * A vector field. A write reaches the formatter already serialized (the
983
+ * mapper turns json-storage fields into JSON text first) and is stored as
984
+ * is; an array that does reach it becomes a Float32 BLOB with sqlite-vec,
985
+ * JSON text without it. A read accepts either form. Called once while the
986
+ * table metadata is built, where the extension probe must not run (it may
987
+ * be busy — see {@link _detectVectorSupport}), so a value decides when it
988
+ * is formatted.
989
+ */
964
990
  formatValue(field) {
965
991
  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,
992
+ return {
993
+ toStorage: (value) => {
994
+ if (!Array.isArray(value)) return value;
995
+ return this._detectVectorSupport() ? Buffer.from(new Float32Array(value).buffer) : JSON.stringify(value);
996
+ },
968
997
  fromStorage: (value) => {
969
- if (value instanceof Buffer || value instanceof Uint8Array) {
998
+ if (value instanceof Uint8Array) {
970
999
  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);
1000
+ return Array.from(new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4)));
973
1001
  }
974
- return value;
975
- }
976
- };
977
- return {
978
- toStorage: (value) => Array.isArray(value) ? JSON.stringify(value) : value,
979
- fromStorage: (value) => {
980
1002
  if (typeof value === "string") try {
981
1003
  return JSON.parse(value);
982
1004
  } catch {
@@ -990,13 +1012,20 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
990
1012
  if (this._vectorFields.size === 0) return false;
991
1013
  return this._detectVectorSupport();
992
1014
  }
1015
+ /**
1016
+ * Whether sqlite-vec is loaded: the driver's `hasVectorExt`, else a probe,
1017
+ * answered once. A busy probe answers nothing — it throws the retryable
1018
+ * `LOCK_TIMEOUT` (the caller's write, search or sync fails, the next call
1019
+ * probes again).
1020
+ */
993
1021
  _detectVectorSupport() {
994
1022
  if (this._supportsVector !== void 0) return this._supportsVector;
995
1023
  if (this.driver.hasVectorExt !== void 0) this._supportsVector = this.driver.hasVectorExt;
996
1024
  else try {
997
1025
  this.driver.get("SELECT vec_version()");
998
1026
  this._supportsVector = true;
999
- } catch {
1027
+ } catch (error) {
1028
+ if (isBusy(error)) throw mapBusy(error);
1000
1029
  this._supportsVector = false;
1001
1030
  }
1002
1031
  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 +1050,15 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
1021
1050
  * exclusive hold) it runs immediately; otherwise it waits until no
1022
1051
  * transaction is open on the connection. The `held` check and the statement
1023
1052
  * run in the same synchronous segment, so they cannot interleave with a
1024
- * `BEGIN` from another context.
1053
+ * `BEGIN` from another context. A busy statement rejects with `LOCK_TIMEOUT`.
1025
1054
  */
1026
1055
  async _stmt(fn) {
1027
- if (!this._gate.held || this._ownsConnection()) return fn();
1028
- return this._gate.runWhenFree(fn, this._waitOpts());
1056
+ try {
1057
+ if (!this._gate.held || this._ownsConnection()) return fn();
1058
+ return await this._gate.runWhenFree(fn, this._waitOpts());
1059
+ } catch (error) {
1060
+ throw mapBusy(error);
1061
+ }
1029
1062
  }
1030
1063
  /**
1031
1064
  * Holds the connection for the duration of `fn` WITHOUT opening a
@@ -1036,11 +1069,15 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
1036
1069
  * request's transaction (PRAGMA changes are no-ops inside one). Inside our
1037
1070
  * own transaction `fn` runs directly; re-entrant for the same async
1038
1071
  * context; nested `withTransaction` calls inside `fn` still BEGIN/COMMIT
1039
- * on the held connection.
1072
+ * on the held connection. A busy step rejects with `LOCK_TIMEOUT`, after
1073
+ * `fn`'s own `finally` blocks restored the connection's PRAGMAs.
1040
1074
  */
1041
1075
  async _withExclusiveConnection(fn) {
1042
- if (this._getTransactionState() !== void 0) return fn();
1043
- return this._gate.runExclusive(fn, this._waitOpts());
1076
+ try {
1077
+ return this._getTransactionState() !== void 0 ? await fn() : await this._gate.runExclusive(fn, this._waitOpts());
1078
+ } catch (error) {
1079
+ throw mapBusy(error);
1080
+ }
1044
1081
  }
1045
1082
  async _beginTransaction() {
1046
1083
  const holdsGate = !this._gate.heldByCurrentContext;
@@ -1051,7 +1088,7 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
1051
1088
  this.driver.exec("BEGIN IMMEDIATE");
1052
1089
  } catch (error) {
1053
1090
  state.release();
1054
- throw error;
1091
+ throw mapBusy(error);
1055
1092
  }
1056
1093
  return state;
1057
1094
  }
@@ -1360,10 +1397,11 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
1360
1397
  /**
1361
1398
  * Seeds the sqlite_sequence table for auto-increment fields that have a start value.
1362
1399
  * Only applies once per adapter instance (idempotent via INSERT OR IGNORE + flag).
1400
+ * The flag is set once the seed ran: a failed (busy) seed is retried by the
1401
+ * next `ensureTable`.
1363
1402
  */
1364
1403
  _seedIncrementStart() {
1365
1404
  if (this._incrementSeeded) return;
1366
- this._incrementSeeded = true;
1367
1405
  const tableName = this.resolveTableName();
1368
1406
  for (const def of this._table.defaults.values()) if (def.kind === "fn" && def.fn === "increment" && typeof def.start === "number") {
1369
1407
  const seedSql = `INSERT OR IGNORE INTO sqlite_sequence(name, seq) VALUES(?, ?)`;
@@ -1372,6 +1410,7 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
1372
1410
  this.driver.run(seedSql, params);
1373
1411
  break;
1374
1412
  }
1413
+ this._incrementSeeded = true;
1375
1414
  }
1376
1415
  async ensureView() {
1377
1416
  return this._stmt(() => {
@@ -1638,6 +1677,14 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
1638
1677
  async syncIndexes() {
1639
1678
  return this._withExclusiveConnection(() => this._syncIndexes(false));
1640
1679
  }
1680
+ /**
1681
+ * The plan reads the live index state (`PRAGMA index_list` / `index_info`)
1682
+ * through the gate like {@link syncIndexes}: never inside another context's
1683
+ * open transaction, and a busy read rejects with `LOCK_TIMEOUT`.
1684
+ */
1685
+ async planIndexes() {
1686
+ return this._withExclusiveConnection(() => this._syncIndexes(true));
1687
+ }
1641
1688
  async _syncIndexes(dryRun) {
1642
1689
  const tableName = this.resolveTableName();
1643
1690
  const changes = await this.syncIndexesWithDiff({
@@ -1651,12 +1698,12 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
1651
1698
  const cols = index.fields.map((f) => `"${esc(f.name)}" ${f.sort === "desc" ? "DESC" : "ASC"}`).join(", ");
1652
1699
  const sql = `CREATE ${unique}INDEX IF NOT EXISTS "${esc(index.key)}" ON "${esc(tableName)}" (${cols})`;
1653
1700
  this._log(sql);
1654
- this.driver.exec(sql);
1701
+ busyMapped(() => this.driver.exec(sql));
1655
1702
  },
1656
1703
  dropIndex: async (name) => {
1657
1704
  const sql = `DROP INDEX IF EXISTS "${esc(name)}"`;
1658
1705
  this._log(sql);
1659
- this.driver.exec(sql);
1706
+ busyMapped(() => this.driver.exec(sql));
1660
1707
  },
1661
1708
  skipIndex: (index) => index.type === "fulltext" || index.type === "geo" ? null : void 0
1662
1709
  });
@@ -2130,7 +2177,9 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
2130
2177
  * Geo search is available when SQLite has math functions
2131
2178
  * (`SQLITE_ENABLE_MATH_FUNCTIONS` — on by default in better-sqlite3 builds).
2132
2179
  * Distance is computed per row via haversine; declared geo indexes have no
2133
- * physical artifact on SQLite.
2180
+ * physical artifact on SQLite. Probed once; a busy probe throws the
2181
+ * retryable `LOCK_TIMEOUT` and the next call probes again (a `false` would
2182
+ * turn into a non-retryable `GEO_NOT_SUPPORTED`).
2134
2183
  */
2135
2184
  isGeoSearchable() {
2136
2185
  return this._detectMathFns();
@@ -2139,7 +2188,8 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
2139
2188
  if (this._supportsMathFns === void 0) try {
2140
2189
  this.driver.get("SELECT radians(0) AS r");
2141
2190
  this._supportsMathFns = true;
2142
- } catch {
2191
+ } catch (error) {
2192
+ if (isBusy(error)) throw mapBusy(error);
2143
2193
  this._supportsMathFns = false;
2144
2194
  this._log("[atscript-db-sqlite] SQLite math functions unavailable — geo search disabled (rebuild SQLite with SQLITE_ENABLE_MATH_FUNCTIONS).");
2145
2195
  }
package/dist/index.d.cts CHANGED
@@ -363,8 +363,23 @@ declare class SqliteAdapter extends BaseDbAdapter {
363
363
  private readonly _hasBucketFn;
364
364
  constructor(driver: TSqliteDriver, options?: SqliteAdapterOptions);
365
365
  onFieldScanned(field: string, _type: unknown, metadata: TMetadataMap<AtscriptMetadata>): void;
366
+ /**
367
+ * A vector field. A write reaches the formatter already serialized (the
368
+ * mapper turns json-storage fields into JSON text first) and is stored as
369
+ * is; an array that does reach it becomes a Float32 BLOB with sqlite-vec,
370
+ * JSON text without it. A read accepts either form. Called once while the
371
+ * table metadata is built, where the extension probe must not run (it may
372
+ * be busy — see {@link _detectVectorSupport}), so a value decides when it
373
+ * is formatted.
374
+ */
366
375
  formatValue(field: TDbFieldMeta): TValueFormatterPair | undefined;
367
376
  isVectorSearchable(): boolean;
377
+ /**
378
+ * Whether sqlite-vec is loaded: the driver's `hasVectorExt`, else a probe,
379
+ * answered once. A busy probe answers nothing — it throws the retryable
380
+ * `LOCK_TIMEOUT` (the caller's write, search or sync fails, the next call
381
+ * probes again).
382
+ */
368
383
  private _detectVectorSupport;
369
384
  private _waitOpts;
370
385
  /** Every adapter over this driver shares one transaction — and one gate (since 0.1.128). */
@@ -376,7 +391,7 @@ declare class SqliteAdapter extends BaseDbAdapter {
376
391
  * exclusive hold) it runs immediately; otherwise it waits until no
377
392
  * transaction is open on the connection. The `held` check and the statement
378
393
  * run in the same synchronous segment, so they cannot interleave with a
379
- * `BEGIN` from another context.
394
+ * `BEGIN` from another context. A busy statement rejects with `LOCK_TIMEOUT`.
380
395
  */
381
396
  private _stmt;
382
397
  /**
@@ -388,7 +403,8 @@ declare class SqliteAdapter extends BaseDbAdapter {
388
403
  * request's transaction (PRAGMA changes are no-ops inside one). Inside our
389
404
  * own transaction `fn` runs directly; re-entrant for the same async
390
405
  * context; nested `withTransaction` calls inside `fn` still BEGIN/COMMIT
391
- * on the held connection.
406
+ * on the held connection. A busy step rejects with `LOCK_TIMEOUT`, after
407
+ * `fn`'s own `finally` blocks restored the connection's PRAGMAs.
392
408
  */
393
409
  protected _withExclusiveConnection<T>(fn: () => Promise<T>): Promise<T>;
394
410
  protected _beginTransaction(): Promise<SqliteTxState>;
@@ -479,6 +495,8 @@ declare class SqliteAdapter extends BaseDbAdapter {
479
495
  /**
480
496
  * Seeds the sqlite_sequence table for auto-increment fields that have a start value.
481
497
  * Only applies once per adapter instance (idempotent via INSERT OR IGNORE + flag).
498
+ * The flag is set once the seed ran: a failed (busy) seed is retried by the
499
+ * next `ensureTable`.
482
500
  */
483
501
  private _seedIncrementStart;
484
502
  ensureView(): Promise<void>;
@@ -522,6 +540,12 @@ declare class SqliteAdapter extends BaseDbAdapter {
522
540
  */
523
541
  getExistingColumnsForTable(tableName: string): Promise<TExistingColumn[]>;
524
542
  syncIndexes(): Promise<TIndexChange[]>;
543
+ /**
544
+ * The plan reads the live index state (`PRAGMA index_list` / `index_info`)
545
+ * through the gate like {@link syncIndexes}: never inside another context's
546
+ * open transaction, and a busy read rejects with `LOCK_TIMEOUT`.
547
+ */
548
+ planIndexes(): Promise<TIndexChange[]>;
525
549
  protected _syncIndexes(dryRun: boolean): Promise<TIndexChange[]>;
526
550
  getSearchIndexes(): TSearchIndexInfo[];
527
551
  search(text: string, query: DbQuery, indexName?: string): Promise<Array<Record<string, unknown>>>;
@@ -630,7 +654,9 @@ declare class SqliteAdapter extends BaseDbAdapter {
630
654
  * Geo search is available when SQLite has math functions
631
655
  * (`SQLITE_ENABLE_MATH_FUNCTIONS` — on by default in better-sqlite3 builds).
632
656
  * Distance is computed per row via haversine; declared geo indexes have no
633
- * physical artifact on SQLite.
657
+ * physical artifact on SQLite. Probed once; a busy probe throws the
658
+ * retryable `LOCK_TIMEOUT` and the next call probes again (a `false` would
659
+ * turn into a non-retryable `GEO_NOT_SUPPORTED`).
634
660
  */
635
661
  isGeoSearchable(): boolean;
636
662
  private _detectMathFns;
package/dist/index.d.mts CHANGED
@@ -363,8 +363,23 @@ declare class SqliteAdapter extends BaseDbAdapter {
363
363
  private readonly _hasBucketFn;
364
364
  constructor(driver: TSqliteDriver, options?: SqliteAdapterOptions);
365
365
  onFieldScanned(field: string, _type: unknown, metadata: TMetadataMap<AtscriptMetadata>): void;
366
+ /**
367
+ * A vector field. A write reaches the formatter already serialized (the
368
+ * mapper turns json-storage fields into JSON text first) and is stored as
369
+ * is; an array that does reach it becomes a Float32 BLOB with sqlite-vec,
370
+ * JSON text without it. A read accepts either form. Called once while the
371
+ * table metadata is built, where the extension probe must not run (it may
372
+ * be busy — see {@link _detectVectorSupport}), so a value decides when it
373
+ * is formatted.
374
+ */
366
375
  formatValue(field: TDbFieldMeta): TValueFormatterPair | undefined;
367
376
  isVectorSearchable(): boolean;
377
+ /**
378
+ * Whether sqlite-vec is loaded: the driver's `hasVectorExt`, else a probe,
379
+ * answered once. A busy probe answers nothing — it throws the retryable
380
+ * `LOCK_TIMEOUT` (the caller's write, search or sync fails, the next call
381
+ * probes again).
382
+ */
368
383
  private _detectVectorSupport;
369
384
  private _waitOpts;
370
385
  /** Every adapter over this driver shares one transaction — and one gate (since 0.1.128). */
@@ -376,7 +391,7 @@ declare class SqliteAdapter extends BaseDbAdapter {
376
391
  * exclusive hold) it runs immediately; otherwise it waits until no
377
392
  * transaction is open on the connection. The `held` check and the statement
378
393
  * run in the same synchronous segment, so they cannot interleave with a
379
- * `BEGIN` from another context.
394
+ * `BEGIN` from another context. A busy statement rejects with `LOCK_TIMEOUT`.
380
395
  */
381
396
  private _stmt;
382
397
  /**
@@ -388,7 +403,8 @@ declare class SqliteAdapter extends BaseDbAdapter {
388
403
  * request's transaction (PRAGMA changes are no-ops inside one). Inside our
389
404
  * own transaction `fn` runs directly; re-entrant for the same async
390
405
  * context; nested `withTransaction` calls inside `fn` still BEGIN/COMMIT
391
- * on the held connection.
406
+ * on the held connection. A busy step rejects with `LOCK_TIMEOUT`, after
407
+ * `fn`'s own `finally` blocks restored the connection's PRAGMAs.
392
408
  */
393
409
  protected _withExclusiveConnection<T>(fn: () => Promise<T>): Promise<T>;
394
410
  protected _beginTransaction(): Promise<SqliteTxState>;
@@ -479,6 +495,8 @@ declare class SqliteAdapter extends BaseDbAdapter {
479
495
  /**
480
496
  * Seeds the sqlite_sequence table for auto-increment fields that have a start value.
481
497
  * Only applies once per adapter instance (idempotent via INSERT OR IGNORE + flag).
498
+ * The flag is set once the seed ran: a failed (busy) seed is retried by the
499
+ * next `ensureTable`.
482
500
  */
483
501
  private _seedIncrementStart;
484
502
  ensureView(): Promise<void>;
@@ -522,6 +540,12 @@ declare class SqliteAdapter extends BaseDbAdapter {
522
540
  */
523
541
  getExistingColumnsForTable(tableName: string): Promise<TExistingColumn[]>;
524
542
  syncIndexes(): Promise<TIndexChange[]>;
543
+ /**
544
+ * The plan reads the live index state (`PRAGMA index_list` / `index_info`)
545
+ * through the gate like {@link syncIndexes}: never inside another context's
546
+ * open transaction, and a busy read rejects with `LOCK_TIMEOUT`.
547
+ */
548
+ planIndexes(): Promise<TIndexChange[]>;
525
549
  protected _syncIndexes(dryRun: boolean): Promise<TIndexChange[]>;
526
550
  getSearchIndexes(): TSearchIndexInfo[];
527
551
  search(text: string, query: DbQuery, indexName?: string): Promise<Array<Record<string, unknown>>>;
@@ -630,7 +654,9 @@ declare class SqliteAdapter extends BaseDbAdapter {
630
654
  * Geo search is available when SQLite has math functions
631
655
  * (`SQLITE_ENABLE_MATH_FUNCTIONS` — on by default in better-sqlite3 builds).
632
656
  * Distance is computed per row via haversine; declared geo indexes have no
633
- * physical artifact on SQLite.
657
+ * physical artifact on SQLite. Probed once; a busy probe throws the
658
+ * retryable `LOCK_TIMEOUT` and the next call probes again (a `false` would
659
+ * turn into a non-retryable `GEO_NOT_SUPPORTED`).
634
660
  */
635
661
  isGeoSearchable(): boolean;
636
662
  private _detectMathFns;
package/dist/index.mjs CHANGED
@@ -825,18 +825,35 @@ function ftsLanguageWarning(index, configured) {
825
825
  //#endregion
826
826
  //#region src/sqlite-adapter.ts
827
827
  /**
828
- * The retryable `LOCK_TIMEOUT` of an `SQLITE_BUSY` driver error (another
829
- * connection holds the database lock past `busy_timeout`), with the driver
830
- * error as `cause`; any other error as is.
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 mapBusy(error) {
833
- if (!error || typeof error !== "object") return error;
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 ? new DbError("LOCK_TIMEOUT", [{
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
+ }
840
857
  /**
841
858
  * SQLite adapter for {@link AtscriptDbTable}.
842
859
  *
@@ -960,22 +977,27 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
960
977
  else this._vectorPartitionFields.set(indexName, [field]);
961
978
  }
962
979
  }
980
+ /**
981
+ * A vector field. A write reaches the formatter already serialized (the
982
+ * mapper turns json-storage fields into JSON text first) and is stored as
983
+ * is; an array that does reach it becomes a Float32 BLOB with sqlite-vec,
984
+ * JSON text without it. A read accepts either form. Called once while the
985
+ * table metadata is built, where the extension probe must not run (it may
986
+ * be busy — see {@link _detectVectorSupport}), so a value decides when it
987
+ * is formatted.
988
+ */
963
989
  formatValue(field) {
964
990
  if (!this._vectorFields.has(field.path)) return;
965
- if (this._detectVectorSupport()) return {
966
- toStorage: (value) => Array.isArray(value) ? Buffer.from(new Float32Array(value).buffer) : value,
991
+ return {
992
+ toStorage: (value) => {
993
+ if (!Array.isArray(value)) return value;
994
+ return this._detectVectorSupport() ? Buffer.from(new Float32Array(value).buffer) : JSON.stringify(value);
995
+ },
967
996
  fromStorage: (value) => {
968
- if (value instanceof Buffer || value instanceof Uint8Array) {
997
+ if (value instanceof Uint8Array) {
969
998
  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);
999
+ return Array.from(new Float32Array(buf.buffer, buf.byteOffset, Math.floor(buf.byteLength / 4)));
972
1000
  }
973
- return value;
974
- }
975
- };
976
- return {
977
- toStorage: (value) => Array.isArray(value) ? JSON.stringify(value) : value,
978
- fromStorage: (value) => {
979
1001
  if (typeof value === "string") try {
980
1002
  return JSON.parse(value);
981
1003
  } catch {
@@ -989,13 +1011,20 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
989
1011
  if (this._vectorFields.size === 0) return false;
990
1012
  return this._detectVectorSupport();
991
1013
  }
1014
+ /**
1015
+ * Whether sqlite-vec is loaded: the driver's `hasVectorExt`, else a probe,
1016
+ * answered once. A busy probe answers nothing — it throws the retryable
1017
+ * `LOCK_TIMEOUT` (the caller's write, search or sync fails, the next call
1018
+ * probes again).
1019
+ */
992
1020
  _detectVectorSupport() {
993
1021
  if (this._supportsVector !== void 0) return this._supportsVector;
994
1022
  if (this.driver.hasVectorExt !== void 0) this._supportsVector = this.driver.hasVectorExt;
995
1023
  else try {
996
1024
  this.driver.get("SELECT vec_version()");
997
1025
  this._supportsVector = true;
998
- } catch {
1026
+ } catch (error) {
1027
+ if (isBusy(error)) throw mapBusy(error);
999
1028
  this._supportsVector = false;
1000
1029
  }
1001
1030
  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 +1049,15 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
1020
1049
  * exclusive hold) it runs immediately; otherwise it waits until no
1021
1050
  * transaction is open on the connection. The `held` check and the statement
1022
1051
  * run in the same synchronous segment, so they cannot interleave with a
1023
- * `BEGIN` from another context.
1052
+ * `BEGIN` from another context. A busy statement rejects with `LOCK_TIMEOUT`.
1024
1053
  */
1025
1054
  async _stmt(fn) {
1026
- if (!this._gate.held || this._ownsConnection()) return fn();
1027
- return this._gate.runWhenFree(fn, this._waitOpts());
1055
+ try {
1056
+ if (!this._gate.held || this._ownsConnection()) return fn();
1057
+ return await this._gate.runWhenFree(fn, this._waitOpts());
1058
+ } catch (error) {
1059
+ throw mapBusy(error);
1060
+ }
1028
1061
  }
1029
1062
  /**
1030
1063
  * Holds the connection for the duration of `fn` WITHOUT opening a
@@ -1035,11 +1068,15 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
1035
1068
  * request's transaction (PRAGMA changes are no-ops inside one). Inside our
1036
1069
  * own transaction `fn` runs directly; re-entrant for the same async
1037
1070
  * context; nested `withTransaction` calls inside `fn` still BEGIN/COMMIT
1038
- * on the held connection.
1071
+ * on the held connection. A busy step rejects with `LOCK_TIMEOUT`, after
1072
+ * `fn`'s own `finally` blocks restored the connection's PRAGMAs.
1039
1073
  */
1040
1074
  async _withExclusiveConnection(fn) {
1041
- if (this._getTransactionState() !== void 0) return fn();
1042
- return this._gate.runExclusive(fn, this._waitOpts());
1075
+ try {
1076
+ return this._getTransactionState() !== void 0 ? await fn() : await this._gate.runExclusive(fn, this._waitOpts());
1077
+ } catch (error) {
1078
+ throw mapBusy(error);
1079
+ }
1043
1080
  }
1044
1081
  async _beginTransaction() {
1045
1082
  const holdsGate = !this._gate.heldByCurrentContext;
@@ -1050,7 +1087,7 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
1050
1087
  this.driver.exec("BEGIN IMMEDIATE");
1051
1088
  } catch (error) {
1052
1089
  state.release();
1053
- throw error;
1090
+ throw mapBusy(error);
1054
1091
  }
1055
1092
  return state;
1056
1093
  }
@@ -1359,10 +1396,11 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
1359
1396
  /**
1360
1397
  * Seeds the sqlite_sequence table for auto-increment fields that have a start value.
1361
1398
  * Only applies once per adapter instance (idempotent via INSERT OR IGNORE + flag).
1399
+ * The flag is set once the seed ran: a failed (busy) seed is retried by the
1400
+ * next `ensureTable`.
1362
1401
  */
1363
1402
  _seedIncrementStart() {
1364
1403
  if (this._incrementSeeded) return;
1365
- this._incrementSeeded = true;
1366
1404
  const tableName = this.resolveTableName();
1367
1405
  for (const def of this._table.defaults.values()) if (def.kind === "fn" && def.fn === "increment" && typeof def.start === "number") {
1368
1406
  const seedSql = `INSERT OR IGNORE INTO sqlite_sequence(name, seq) VALUES(?, ?)`;
@@ -1371,6 +1409,7 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
1371
1409
  this.driver.run(seedSql, params);
1372
1410
  break;
1373
1411
  }
1412
+ this._incrementSeeded = true;
1374
1413
  }
1375
1414
  async ensureView() {
1376
1415
  return this._stmt(() => {
@@ -1637,6 +1676,14 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
1637
1676
  async syncIndexes() {
1638
1677
  return this._withExclusiveConnection(() => this._syncIndexes(false));
1639
1678
  }
1679
+ /**
1680
+ * The plan reads the live index state (`PRAGMA index_list` / `index_info`)
1681
+ * through the gate like {@link syncIndexes}: never inside another context's
1682
+ * open transaction, and a busy read rejects with `LOCK_TIMEOUT`.
1683
+ */
1684
+ async planIndexes() {
1685
+ return this._withExclusiveConnection(() => this._syncIndexes(true));
1686
+ }
1640
1687
  async _syncIndexes(dryRun) {
1641
1688
  const tableName = this.resolveTableName();
1642
1689
  const changes = await this.syncIndexesWithDiff({
@@ -1650,12 +1697,12 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
1650
1697
  const cols = index.fields.map((f) => `"${esc(f.name)}" ${f.sort === "desc" ? "DESC" : "ASC"}`).join(", ");
1651
1698
  const sql = `CREATE ${unique}INDEX IF NOT EXISTS "${esc(index.key)}" ON "${esc(tableName)}" (${cols})`;
1652
1699
  this._log(sql);
1653
- this.driver.exec(sql);
1700
+ busyMapped(() => this.driver.exec(sql));
1654
1701
  },
1655
1702
  dropIndex: async (name) => {
1656
1703
  const sql = `DROP INDEX IF EXISTS "${esc(name)}"`;
1657
1704
  this._log(sql);
1658
- this.driver.exec(sql);
1705
+ busyMapped(() => this.driver.exec(sql));
1659
1706
  },
1660
1707
  skipIndex: (index) => index.type === "fulltext" || index.type === "geo" ? null : void 0
1661
1708
  });
@@ -2129,7 +2176,9 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
2129
2176
  * Geo search is available when SQLite has math functions
2130
2177
  * (`SQLITE_ENABLE_MATH_FUNCTIONS` — on by default in better-sqlite3 builds).
2131
2178
  * Distance is computed per row via haversine; declared geo indexes have no
2132
- * physical artifact on SQLite.
2179
+ * physical artifact on SQLite. Probed once; a busy probe throws the
2180
+ * retryable `LOCK_TIMEOUT` and the next call probes again (a `false` would
2181
+ * turn into a non-retryable `GEO_NOT_SUPPORTED`).
2133
2182
  */
2134
2183
  isGeoSearchable() {
2135
2184
  return this._detectMathFns();
@@ -2138,7 +2187,8 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
2138
2187
  if (this._supportsMathFns === void 0) try {
2139
2188
  this.driver.get("SELECT radians(0) AS r");
2140
2189
  this._supportsMathFns = true;
2141
- } catch {
2190
+ } catch (error) {
2191
+ if (isBusy(error)) throw mapBusy(error);
2142
2192
  this._supportsMathFns = false;
2143
2193
  this._log("[atscript-db-sqlite] SQLite math functions unavailable — geo search disabled (rebuild SQLite with SQLITE_ENABLE_MATH_FUNCTIONS).");
2144
2194
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-sqlite",
3
- "version": "0.1.175",
3
+ "version": "0.1.177",
4
4
  "description": "SQLite adapter for @atscript/db with swappable driver support.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -36,23 +36,23 @@
36
36
  "access": "public"
37
37
  },
38
38
  "dependencies": {
39
- "@atscript/db-sql-tools": "^0.1.175"
39
+ "@atscript/db-sql-tools": "^0.1.177"
40
40
  },
41
41
  "devDependencies": {
42
- "@atscript/core": "^0.2.11",
43
- "@atscript/typescript": "^0.2.11",
42
+ "@atscript/core": "^0.2.12",
43
+ "@atscript/typescript": "^0.2.12",
44
44
  "@types/better-sqlite3": "^7.6.13",
45
45
  "@uniqu/core": "^0.2.2",
46
46
  "better-sqlite3": "^12.6.2",
47
47
  "sqlite-vec": "^0.1.9",
48
- "unplugin-atscript": "^0.2.11"
48
+ "unplugin-atscript": "^0.2.12"
49
49
  },
50
50
  "peerDependencies": {
51
- "@atscript/core": "^0.2.11",
52
- "@atscript/typescript": "^0.2.11",
51
+ "@atscript/core": "^0.2.12",
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.175"
55
+ "@atscript/db": "^0.1.177"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "better-sqlite3": {