@atscript/db-sqlite 0.1.174 → 0.1.175
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 +123 -20
- package/dist/index.d.cts +45 -2
- package/dist/index.d.mts +45 -2
- package/dist/index.mjs +124 -21
- package/package.json +10 -10
package/dist/index.cjs
CHANGED
|
@@ -763,28 +763,82 @@ function quoteFtsTerm(text, match) {
|
|
|
763
763
|
}
|
|
764
764
|
return parts.length > 0 ? parts.join(match === "any" ? " OR " : " ") : "\"\"";
|
|
765
765
|
}
|
|
766
|
+
/** A tokenizer spec — words of letters, digits and `_`, separated by spaces (no quotes: it is inlined into DDL). */
|
|
767
|
+
const TOKENIZER_SPEC = /^[A-Za-z0-9_]+(?: +[A-Za-z0-9_]+)*$/;
|
|
766
768
|
/**
|
|
767
|
-
*
|
|
768
|
-
* (
|
|
769
|
+
* Checks `ftsTokenizers` (since 0.1.175): every key a `@db.index.fulltext.language`
|
|
770
|
+
* value, every tokenizer a plain spec (it is inlined into `CREATE VIRTUAL TABLE`).
|
|
771
|
+
* Throws on the first bad entry.
|
|
772
|
+
*/
|
|
773
|
+
function validateFtsTokenizers(tokenizers) {
|
|
774
|
+
for (const [language, tokenizer] of Object.entries(tokenizers ?? {})) {
|
|
775
|
+
if (tokenizer === void 0) continue;
|
|
776
|
+
if (!_atscript_db.DB_FULLTEXT_LANGUAGES.includes(language)) throw new Error(`[sqlite] ftsTokenizers: "${language}" is not a @db.index.fulltext.language value`);
|
|
777
|
+
if (typeof tokenizer !== "string" || !TOKENIZER_SPEC.test(tokenizer)) throw new Error(`[sqlite] ftsTokenizers.${language}: ${JSON.stringify(tokenizer)} is not a tokenizer spec — use words of letters, digits and "_" separated by spaces (e.g. "snowball russian unicode61")`);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
/** FTS5's limits on the `prefix` option: lengths 1–999, at most 31 prefix indexes. */
|
|
781
|
+
const FTS_PREFIX_MAX_LENGTH = 999;
|
|
782
|
+
const FTS_PREFIX_MAX_COUNT = 31;
|
|
783
|
+
/**
|
|
784
|
+
* Checks `ftsPrefix` (since 0.1.175) and returns its canonical FTS5 `prefix`
|
|
785
|
+
* value — the distinct lengths ascending, space-separated (`"2 3"`) — or
|
|
786
|
+
* `undefined` when unset or empty. Throws on anything but integers 1–999
|
|
787
|
+
* (at most 31 distinct).
|
|
788
|
+
*/
|
|
789
|
+
function ftsPrefixSpec(prefix) {
|
|
790
|
+
if (prefix === void 0) return void 0;
|
|
791
|
+
if (!Array.isArray(prefix)) throw new Error(`[sqlite] ftsPrefix: ${JSON.stringify(prefix)} is not an array of prefix lengths`);
|
|
792
|
+
for (const length of prefix) if (!Number.isInteger(length) || length < 1 || length > FTS_PREFIX_MAX_LENGTH) throw new Error(`[sqlite] ftsPrefix: ${JSON.stringify(length)} is not a prefix length — use integers from 1 to ${FTS_PREFIX_MAX_LENGTH}`);
|
|
793
|
+
const lengths = [...new Set(prefix)].toSorted((a, b) => a - b);
|
|
794
|
+
if (lengths.length > FTS_PREFIX_MAX_COUNT) throw new Error(`[sqlite] ftsPrefix: ${lengths.length} prefix lengths — FTS5 allows at most ${FTS_PREFIX_MAX_COUNT}`);
|
|
795
|
+
return lengths.length > 0 ? lengths.join(" ") : void 0;
|
|
796
|
+
}
|
|
797
|
+
/** Whether an FTS5 table's `CREATE` statement has exactly the prefix indexes `spec` ({@link ftsPrefixSpec}) asks for. */
|
|
798
|
+
function ftsPrefixMatch(createSql, spec) {
|
|
799
|
+
const lengths = (/\bprefix\s*=\s*'([^']*)'/i.exec(createSql)?.[1])?.split(/[\s,]+/).filter(Boolean).map(Number).toSorted((a, b) => a - b);
|
|
800
|
+
return (lengths && lengths.length > 0 ? lengths.join(" ") : void 0) === spec;
|
|
801
|
+
}
|
|
802
|
+
/**
|
|
803
|
+
* The FTS5 `tokenize` option of a fulltext index: `configured` — the
|
|
804
|
+
* `ftsTokenizers` entry of its `@db.index.fulltext.language` (since 0.1.175)
|
|
805
|
+
* — else `english` adds the Porter stemmer (since 0.1.168); every other
|
|
769
806
|
* language — FTS5 ships no other stemmer — and no language keep FTS5's
|
|
770
807
|
* default `unicode61` (`undefined`: no `tokenize` clause).
|
|
771
808
|
*/
|
|
772
|
-
function ftsTokenizer(index) {
|
|
773
|
-
return index.language === "english" ? "porter unicode61" : void 0;
|
|
809
|
+
function ftsTokenizer(index, configured) {
|
|
810
|
+
return configured ?? (index.language === "english" ? "porter unicode61" : void 0);
|
|
774
811
|
}
|
|
775
812
|
/** Whether an FTS5 table's `CREATE` statement has the tokenizer the index's language asks for. */
|
|
776
|
-
function ftsTokenizerMatch(createSql, index) {
|
|
777
|
-
return /tokenize\s*=\s*'([^']*)'/i.exec(createSql)?.[1] === ftsTokenizer(index);
|
|
813
|
+
function ftsTokenizerMatch(createSql, index, configured) {
|
|
814
|
+
return /tokenize\s*=\s*'([^']*)'/i.exec(createSql)?.[1] === ftsTokenizer(index, configured);
|
|
778
815
|
}
|
|
779
|
-
/**
|
|
780
|
-
|
|
816
|
+
/**
|
|
817
|
+
* The sync warning for a language FTS5 cannot stem, `undefined` when it can,
|
|
818
|
+
* none is set, or an `ftsTokenizers` entry (`configured`) covers it.
|
|
819
|
+
*/
|
|
820
|
+
function ftsLanguageWarning(index, configured) {
|
|
781
821
|
const { language } = index;
|
|
782
822
|
if (language === void 0 || language === "english" || language === "none") return void 0;
|
|
783
|
-
|
|
823
|
+
if (configured !== void 0) return void 0;
|
|
824
|
+
return `[sqlite] fulltext index "${index.name}": FTS5 has no ${language} stemmer — words are indexed unstemmed (unicode61); set the adapter's ftsTokenizers to use a stemming tokenizer`;
|
|
784
825
|
}
|
|
785
826
|
//#endregion
|
|
786
827
|
//#region src/sqlite-adapter.ts
|
|
787
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.
|
|
832
|
+
*/
|
|
833
|
+
function mapBusy(error) {
|
|
834
|
+
if (!error || typeof error !== "object") return error;
|
|
835
|
+
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", [{
|
|
837
|
+
path: "",
|
|
838
|
+
message: error.message
|
|
839
|
+
}], void 0, { cause: error }) : error;
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
788
842
|
* SQLite adapter for {@link AtscriptDbTable}.
|
|
789
843
|
*
|
|
790
844
|
* Accepts any {@link TSqliteDriver} implementation — the actual SQLite engine
|
|
@@ -870,14 +924,21 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
870
924
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
871
925
|
_gate;
|
|
872
926
|
_txOptions;
|
|
927
|
+
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
928
|
+
_ftsTokenizers;
|
|
929
|
+
/** `ftsPrefix` as the FTS5 `prefix` value (`"2 3"`), `undefined` when unset (since 0.1.175). */
|
|
930
|
+
_ftsPrefix;
|
|
873
931
|
/** Whether the driver has the calendar-bucket UDF — fixed at construction, when it is registered. */
|
|
874
932
|
_hasBucketFn;
|
|
875
933
|
constructor(driver, options) {
|
|
876
934
|
super();
|
|
877
935
|
this.driver = driver;
|
|
878
936
|
this._gate = getSqliteTxGate(driver);
|
|
879
|
-
const { viewJoinPruning, ...txOptions } = options ?? {};
|
|
937
|
+
const { viewJoinPruning, ftsTokenizers, ftsPrefix, ...txOptions } = options ?? {};
|
|
938
|
+
validateFtsTokenizers(ftsTokenizers);
|
|
880
939
|
this._txOptions = txOptions;
|
|
940
|
+
this._ftsTokenizers = ftsTokenizers;
|
|
941
|
+
this._ftsPrefix = ftsPrefixSpec(ftsPrefix);
|
|
881
942
|
this.viewJoinPruning = viewJoinPruning !== false;
|
|
882
943
|
this.driver.exec("PRAGMA foreign_keys = ON");
|
|
883
944
|
this._hasBucketFn = registerBucketFunction(driver);
|
|
@@ -998,9 +1059,10 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
998
1059
|
try {
|
|
999
1060
|
this._log("COMMIT");
|
|
1000
1061
|
this.driver.exec("COMMIT");
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1062
|
+
} catch (error) {
|
|
1063
|
+
throw mapBusy(error);
|
|
1003
1064
|
}
|
|
1065
|
+
state.release();
|
|
1004
1066
|
}
|
|
1005
1067
|
async _rollbackTransaction(state) {
|
|
1006
1068
|
try {
|
|
@@ -1631,7 +1693,7 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
1631
1693
|
const plan = this._searchPlan(text, indexName);
|
|
1632
1694
|
const controls = query.controls || {};
|
|
1633
1695
|
const sorted = (0, _atscript_db_sql_tools.orderByList)(sqliteDialect, controls.$sort, controls.$nulls, "t.");
|
|
1634
|
-
if (!plan.join && (sorted || plan.textFields === 0)) {
|
|
1696
|
+
if (controls.$rank === false || !plan.join && (sorted || plan.textFields === 0)) {
|
|
1635
1697
|
const { sql, params } = buildSelect(this.resolveTableName(), andWhere(plan.predicate, buildWhere(query.filter)), query.controls, (0, _atscript_db_sql_tools.searchRankOrder)(sqliteDialect, {
|
|
1636
1698
|
...plan.exact,
|
|
1637
1699
|
pkColumns: this._pkColumns()
|
|
@@ -1823,6 +1885,21 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
1823
1885
|
};
|
|
1824
1886
|
}
|
|
1825
1887
|
/**
|
|
1888
|
+
* The FTS5 settings adapter options give the index — its language's
|
|
1889
|
+
* `ftsTokenizers` entry and `ftsPrefix` (`"trigram; prefix=2 3"`) — part of
|
|
1890
|
+
* the schema hash (since 0.1.175). `undefined` when neither is set.
|
|
1891
|
+
*/
|
|
1892
|
+
fulltextEngineConfig(index) {
|
|
1893
|
+
const tokenizer = this._configuredFtsTokenizer(index);
|
|
1894
|
+
if (this._ftsPrefix === void 0) return tokenizer;
|
|
1895
|
+
const prefix = `prefix=${this._ftsPrefix}`;
|
|
1896
|
+
return tokenizer === void 0 ? prefix : `${tokenizer}; ${prefix}`;
|
|
1897
|
+
}
|
|
1898
|
+
/** The `ftsTokenizers` entry of the index's language (since 0.1.175). */
|
|
1899
|
+
_configuredFtsTokenizer(index) {
|
|
1900
|
+
return index.language === void 0 ? void 0 : this._ftsTokenizers?.[index.language];
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1826
1903
|
* Creates/drops FTS5 virtual tables and sync triggers to match desired fulltext indexes.
|
|
1827
1904
|
*/
|
|
1828
1905
|
async _syncFtsIndexes(tableName, dryRun) {
|
|
@@ -1830,7 +1907,7 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
1830
1907
|
const ftIndexes = this._getFulltextIndexes().filter((idx) => (0, _atscript_db.splitFulltextFields)(idx).text.length > 0);
|
|
1831
1908
|
const desiredFtsTables = new Set(ftIndexes.map((idx) => this._ftsTableName(idx.name)));
|
|
1832
1909
|
if (!dryRun) for (const index of ftIndexes) {
|
|
1833
|
-
const warning = ftsLanguageWarning(index);
|
|
1910
|
+
const warning = ftsLanguageWarning(index, this._configuredFtsTokenizer(index));
|
|
1834
1911
|
if (warning) this.logger.warn(warning);
|
|
1835
1912
|
}
|
|
1836
1913
|
const existingFts = this._shadowTableSql(tableName, "fts");
|
|
@@ -1844,17 +1921,40 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
1844
1921
|
if (liveSql === void 0) await apply({
|
|
1845
1922
|
name: ftsTable,
|
|
1846
1923
|
action: "add"
|
|
1847
|
-
}, ftsTable, () =>
|
|
1848
|
-
|
|
1924
|
+
}, ftsTable, () => {
|
|
1925
|
+
this._probeFtsTokenizer(index);
|
|
1926
|
+
this._createFtsTable(tableName, ftsTable, index);
|
|
1927
|
+
});
|
|
1928
|
+
else if (!this._ftsColumnsMatch(ftsTable, index) || !ftsTokenizerMatch(liveSql, index, this._configuredFtsTokenizer(index)) || !ftsPrefixMatch(liveSql, this._ftsPrefix)) await apply({
|
|
1849
1929
|
name: ftsTable,
|
|
1850
1930
|
action: "rebuild"
|
|
1851
1931
|
}, ftsTable, () => {
|
|
1932
|
+
this._probeFtsTokenizer(index);
|
|
1852
1933
|
this._dropFtsTable(ftsTable);
|
|
1853
1934
|
this._createFtsTable(tableName, ftsTable, index);
|
|
1854
1935
|
});
|
|
1855
1936
|
}
|
|
1856
1937
|
return changes;
|
|
1857
1938
|
}
|
|
1939
|
+
/**
|
|
1940
|
+
* Throws a clear error when SQLite lacks the index's configured tokenizer
|
|
1941
|
+
* (since 0.1.175) — a tokenizer FTS5 does not ship (`snowball`, …) comes
|
|
1942
|
+
* from an extension. Creates and drops a `temp` FTS5 table with it, so a
|
|
1943
|
+
* rebuild fails before it drops the live table.
|
|
1944
|
+
*/
|
|
1945
|
+
_probeFtsTokenizer(index) {
|
|
1946
|
+
const tokenizer = this._configuredFtsTokenizer(index);
|
|
1947
|
+
if (!tokenizer) return;
|
|
1948
|
+
const probe = `temp."__atscript_fts_probe"`;
|
|
1949
|
+
try {
|
|
1950
|
+
this.driver.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${probe} USING fts5(x, tokenize='${tokenizer}')`);
|
|
1951
|
+
} catch (error) {
|
|
1952
|
+
const message = error?.message ?? "";
|
|
1953
|
+
if (!/no such tokenizer/i.test(message)) throw error;
|
|
1954
|
+
throw new Error(`[sqlite] fulltext index "${index.name}": FTS5 tokenizer "${tokenizer}" is not available (${message}) — load the SQLite extension that provides it with the driver's loadExtensions option`, { cause: error });
|
|
1955
|
+
}
|
|
1956
|
+
this.driver.exec(`DROP TABLE IF EXISTS ${probe}`);
|
|
1957
|
+
}
|
|
1858
1958
|
/** Whether an existing FTS5 table has exactly the index's text columns, in order. */
|
|
1859
1959
|
_ftsColumnsMatch(ftsTable, index) {
|
|
1860
1960
|
const live = this.driver.all(`PRAGMA table_info("${esc(ftsTable)}")`).map((c) => c.name);
|
|
@@ -1865,9 +1965,10 @@ var SqliteAdapter = class SqliteAdapter extends _atscript_db.BaseDbAdapter {
|
|
|
1865
1965
|
_createFtsTable(tableName, ftsTable, index) {
|
|
1866
1966
|
const fields = (0, _atscript_db.splitFulltextFields)(index).text;
|
|
1867
1967
|
const fieldList = fields.map((f) => `"${esc(f.name)}"`).join(", ");
|
|
1868
|
-
const tokenizer = ftsTokenizer(index);
|
|
1968
|
+
const tokenizer = ftsTokenizer(index, this._configuredFtsTokenizer(index));
|
|
1869
1969
|
const tokenize = tokenizer ? `, tokenize='${tokenizer}'` : "";
|
|
1870
|
-
const
|
|
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})`;
|
|
1871
1972
|
this._log(createSql);
|
|
1872
1973
|
this.driver.exec(createSql);
|
|
1873
1974
|
const newFields = fields.map((f) => `new."${esc(f.name)}"`).join(", ");
|
|
@@ -2207,12 +2308,14 @@ function normalizeSqliteDefault(value) {
|
|
|
2207
2308
|
//#endregion
|
|
2208
2309
|
//#region src/index.ts
|
|
2209
2310
|
function createAdapter(connection, options) {
|
|
2210
|
-
const { transactionWaitTimeoutMs, transactionWaitWarnMs, viewJoinPruning, ...driverOptions } = options ?? {};
|
|
2311
|
+
const { transactionWaitTimeoutMs, transactionWaitWarnMs, viewJoinPruning, ftsTokenizers, ftsPrefix, ...driverOptions } = options ?? {};
|
|
2211
2312
|
const driver = new BetterSqlite3Driver(connection, driverOptions);
|
|
2212
2313
|
const adapterOptions = {
|
|
2213
2314
|
transactionWaitTimeoutMs,
|
|
2214
2315
|
transactionWaitWarnMs,
|
|
2215
|
-
viewJoinPruning
|
|
2316
|
+
viewJoinPruning,
|
|
2317
|
+
ftsTokenizers,
|
|
2318
|
+
ftsPrefix
|
|
2216
2319
|
};
|
|
2217
2320
|
return new _atscript_db.DbSpace(() => new SqliteAdapter(driver, adapterOptions), { onClose: () => driver.close() });
|
|
2218
2321
|
}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AggregateFn, BaseDbAdapter, BucketUnit, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbDeleteManyOptions, TDbDeleteResult, TDbFieldMeta, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbUpdateOptions, TDbUpdateResult, TEnsureTableOptions, TExistingColumn, TFieldOps, TGenericLogger, TIndexChange, TJsonCopyTarget, TReferencingForeignKey, TSearchIndexInfo, TSyncColumnResult, TValueFormatterPair, TViewCapability } from "@atscript/db";
|
|
1
|
+
import { AggregateFn, BaseDbAdapter, BucketUnit, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbDeleteManyOptions, TDbDeleteResult, TDbFieldMeta, TDbFulltextLanguage, TDbIndex, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbUpdateOptions, TDbUpdateResult, TEnsureTableOptions, TExistingColumn, TFieldOps, TGenericLogger, TIndexChange, TJsonCopyTarget, TReferencingForeignKey, TSearchIndexInfo, TSyncColumnResult, TValueFormatterPair, TViewCapability } from "@atscript/db";
|
|
2
2
|
import { TMetadataMap } from "@atscript/typescript/utils";
|
|
3
3
|
import { FilterExpr as FilterExpr$1 } from "@uniqu/core";
|
|
4
4
|
import { TFilterVisitorOptions, TSqlFragment, TSqlFragment as TSqlFragment$1 } from "@atscript/db-sql-tools";
|
|
@@ -162,7 +162,10 @@ interface SqliteTxWaitOptions {
|
|
|
162
162
|
/** Logger for the wait warning (the adapter passes its own). */
|
|
163
163
|
logger?: TGenericLogger;
|
|
164
164
|
}
|
|
165
|
-
/**
|
|
165
|
+
/**
|
|
166
|
+
* Options accepted by `SqliteAdapter` / `createAdapter`: the transaction
|
|
167
|
+
* gate's, plus `viewJoinPruning`, `ftsTokenizers` and `ftsPrefix`.
|
|
168
|
+
*/
|
|
166
169
|
type SqliteAdapterOptions = Pick<SqliteTxWaitOptions, "transactionWaitTimeoutMs" | "transactionWaitWarnMs"> & {
|
|
167
170
|
/**
|
|
168
171
|
* Read a managed view through an inline definition without the LEFT joins
|
|
@@ -171,6 +174,27 @@ type SqliteAdapterOptions = Pick<SqliteTxWaitOptions, "transactionWaitTimeoutMs"
|
|
|
171
174
|
* @since 0.1.153
|
|
172
175
|
*/
|
|
173
176
|
viewJoinPruning?: boolean;
|
|
177
|
+
/**
|
|
178
|
+
* The FTS5 tokenizer per `@db.index.fulltext.language`, e.g.
|
|
179
|
+
* `{ russian: "snowball russian unicode61" }` — replaces the default
|
|
180
|
+
* (`porter unicode61` for `english`, `unicode61` for the rest), and a
|
|
181
|
+
* configured language gets no "no stemmer" warning. A tokenizer FTS5 does
|
|
182
|
+
* not ship comes from a SQLite extension loaded through the driver's
|
|
183
|
+
* `loadExtensions`. Words, digits, `_` and spaces only. Changing it rebuilds
|
|
184
|
+
* the index on the next schema sync.
|
|
185
|
+
* @since 0.1.175
|
|
186
|
+
*/
|
|
187
|
+
ftsTokenizers?: Partial<Record<TDbFulltextLanguage, string>>;
|
|
188
|
+
/**
|
|
189
|
+
* FTS5 prefix indexes: the prefix lengths, in characters, every fulltext
|
|
190
|
+
* index of this adapter is built with (FTS5 `prefix` option), e.g. `[2, 3]`
|
|
191
|
+
* — prefix searches (`$search: "quo*"`) of those lengths read a prebuilt
|
|
192
|
+
* index instead of scanning the term list. Integers 1–999, at most 31 of
|
|
193
|
+
* them; order and duplicates do not matter. Changing it rebuilds the FTS5
|
|
194
|
+
* tables on the next schema sync. Unset or `[]`: no prefix indexes.
|
|
195
|
+
* @since 0.1.175
|
|
196
|
+
*/
|
|
197
|
+
ftsPrefix?: readonly number[];
|
|
174
198
|
};
|
|
175
199
|
/**
|
|
176
200
|
* One waiter for the gate, created once per `_stmt` / `acquire` call and kept
|
|
@@ -331,6 +355,10 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
331
355
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
332
356
|
private readonly _gate;
|
|
333
357
|
private readonly _txOptions;
|
|
358
|
+
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
359
|
+
private readonly _ftsTokenizers;
|
|
360
|
+
/** `ftsPrefix` as the FTS5 `prefix` value (`"2 3"`), `undefined` when unset (since 0.1.175). */
|
|
361
|
+
private readonly _ftsPrefix;
|
|
334
362
|
/** Whether the driver has the calendar-bucket UDF — fixed at construction, when it is registered. */
|
|
335
363
|
private readonly _hasBucketFn;
|
|
336
364
|
constructor(driver: TSqliteDriver, options?: SqliteAdapterOptions);
|
|
@@ -544,10 +572,25 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
544
572
|
* Both data and count queries reuse this to avoid duplicating index resolution and filter translation.
|
|
545
573
|
*/
|
|
546
574
|
private _buildFtsBase;
|
|
575
|
+
/**
|
|
576
|
+
* The FTS5 settings adapter options give the index — its language's
|
|
577
|
+
* `ftsTokenizers` entry and `ftsPrefix` (`"trigram; prefix=2 3"`) — part of
|
|
578
|
+
* the schema hash (since 0.1.175). `undefined` when neither is set.
|
|
579
|
+
*/
|
|
580
|
+
fulltextEngineConfig(index: TDbIndex): string | undefined;
|
|
581
|
+
/** The `ftsTokenizers` entry of the index's language (since 0.1.175). */
|
|
582
|
+
private _configuredFtsTokenizer;
|
|
547
583
|
/**
|
|
548
584
|
* Creates/drops FTS5 virtual tables and sync triggers to match desired fulltext indexes.
|
|
549
585
|
*/
|
|
550
586
|
private _syncFtsIndexes;
|
|
587
|
+
/**
|
|
588
|
+
* Throws a clear error when SQLite lacks the index's configured tokenizer
|
|
589
|
+
* (since 0.1.175) — a tokenizer FTS5 does not ship (`snowball`, …) comes
|
|
590
|
+
* from an extension. Creates and drops a `temp` FTS5 table with it, so a
|
|
591
|
+
* rebuild fails before it drops the live table.
|
|
592
|
+
*/
|
|
593
|
+
private _probeFtsTokenizer;
|
|
551
594
|
/** Whether an existing FTS5 table has exactly the index's text columns, in order. */
|
|
552
595
|
private _ftsColumnsMatch;
|
|
553
596
|
/** Creates an FTS5 virtual table with sync triggers and rebuilds the index. */
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AggregateFn, BaseDbAdapter, BucketUnit, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbDeleteManyOptions, TDbDeleteResult, TDbFieldMeta, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbUpdateOptions, TDbUpdateResult, TEnsureTableOptions, TExistingColumn, TFieldOps, TGenericLogger, TIndexChange, TJsonCopyTarget, TReferencingForeignKey, TSearchIndexInfo, TSyncColumnResult, TValueFormatterPair, TViewCapability } from "@atscript/db";
|
|
1
|
+
import { AggregateFn, BaseDbAdapter, BucketUnit, DbQuery, DbSpace, FilterExpr, TColumnDiff, TDbDeleteManyOptions, TDbDeleteResult, TDbFieldMeta, TDbFulltextLanguage, TDbIndex, TDbInsertIgnoreSlot, TDbInsertManyResult, TDbInsertResult, TDbIsolationLevel, TDbObjectKind, TDbUpdateOptions, TDbUpdateResult, TEnsureTableOptions, TExistingColumn, TFieldOps, TGenericLogger, TIndexChange, TJsonCopyTarget, TReferencingForeignKey, TSearchIndexInfo, TSyncColumnResult, TValueFormatterPair, TViewCapability } from "@atscript/db";
|
|
2
2
|
import { TFilterVisitorOptions, TSqlFragment, TSqlFragment as TSqlFragment$1 } from "@atscript/db-sql-tools";
|
|
3
3
|
import { FilterExpr as FilterExpr$1 } from "@uniqu/core";
|
|
4
4
|
import { TMetadataMap } from "@atscript/typescript/utils";
|
|
@@ -162,7 +162,10 @@ interface SqliteTxWaitOptions {
|
|
|
162
162
|
/** Logger for the wait warning (the adapter passes its own). */
|
|
163
163
|
logger?: TGenericLogger;
|
|
164
164
|
}
|
|
165
|
-
/**
|
|
165
|
+
/**
|
|
166
|
+
* Options accepted by `SqliteAdapter` / `createAdapter`: the transaction
|
|
167
|
+
* gate's, plus `viewJoinPruning`, `ftsTokenizers` and `ftsPrefix`.
|
|
168
|
+
*/
|
|
166
169
|
type SqliteAdapterOptions = Pick<SqliteTxWaitOptions, "transactionWaitTimeoutMs" | "transactionWaitWarnMs"> & {
|
|
167
170
|
/**
|
|
168
171
|
* Read a managed view through an inline definition without the LEFT joins
|
|
@@ -171,6 +174,27 @@ type SqliteAdapterOptions = Pick<SqliteTxWaitOptions, "transactionWaitTimeoutMs"
|
|
|
171
174
|
* @since 0.1.153
|
|
172
175
|
*/
|
|
173
176
|
viewJoinPruning?: boolean;
|
|
177
|
+
/**
|
|
178
|
+
* The FTS5 tokenizer per `@db.index.fulltext.language`, e.g.
|
|
179
|
+
* `{ russian: "snowball russian unicode61" }` — replaces the default
|
|
180
|
+
* (`porter unicode61` for `english`, `unicode61` for the rest), and a
|
|
181
|
+
* configured language gets no "no stemmer" warning. A tokenizer FTS5 does
|
|
182
|
+
* not ship comes from a SQLite extension loaded through the driver's
|
|
183
|
+
* `loadExtensions`. Words, digits, `_` and spaces only. Changing it rebuilds
|
|
184
|
+
* the index on the next schema sync.
|
|
185
|
+
* @since 0.1.175
|
|
186
|
+
*/
|
|
187
|
+
ftsTokenizers?: Partial<Record<TDbFulltextLanguage, string>>;
|
|
188
|
+
/**
|
|
189
|
+
* FTS5 prefix indexes: the prefix lengths, in characters, every fulltext
|
|
190
|
+
* index of this adapter is built with (FTS5 `prefix` option), e.g. `[2, 3]`
|
|
191
|
+
* — prefix searches (`$search: "quo*"`) of those lengths read a prebuilt
|
|
192
|
+
* index instead of scanning the term list. Integers 1–999, at most 31 of
|
|
193
|
+
* them; order and duplicates do not matter. Changing it rebuilds the FTS5
|
|
194
|
+
* tables on the next schema sync. Unset or `[]`: no prefix indexes.
|
|
195
|
+
* @since 0.1.175
|
|
196
|
+
*/
|
|
197
|
+
ftsPrefix?: readonly number[];
|
|
174
198
|
};
|
|
175
199
|
/**
|
|
176
200
|
* One waiter for the gate, created once per `_stmt` / `acquire` call and kept
|
|
@@ -331,6 +355,10 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
331
355
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
332
356
|
private readonly _gate;
|
|
333
357
|
private readonly _txOptions;
|
|
358
|
+
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
359
|
+
private readonly _ftsTokenizers;
|
|
360
|
+
/** `ftsPrefix` as the FTS5 `prefix` value (`"2 3"`), `undefined` when unset (since 0.1.175). */
|
|
361
|
+
private readonly _ftsPrefix;
|
|
334
362
|
/** Whether the driver has the calendar-bucket UDF — fixed at construction, when it is registered. */
|
|
335
363
|
private readonly _hasBucketFn;
|
|
336
364
|
constructor(driver: TSqliteDriver, options?: SqliteAdapterOptions);
|
|
@@ -544,10 +572,25 @@ declare class SqliteAdapter extends BaseDbAdapter {
|
|
|
544
572
|
* Both data and count queries reuse this to avoid duplicating index resolution and filter translation.
|
|
545
573
|
*/
|
|
546
574
|
private _buildFtsBase;
|
|
575
|
+
/**
|
|
576
|
+
* The FTS5 settings adapter options give the index — its language's
|
|
577
|
+
* `ftsTokenizers` entry and `ftsPrefix` (`"trigram; prefix=2 3"`) — part of
|
|
578
|
+
* the schema hash (since 0.1.175). `undefined` when neither is set.
|
|
579
|
+
*/
|
|
580
|
+
fulltextEngineConfig(index: TDbIndex): string | undefined;
|
|
581
|
+
/** The `ftsTokenizers` entry of the index's language (since 0.1.175). */
|
|
582
|
+
private _configuredFtsTokenizer;
|
|
547
583
|
/**
|
|
548
584
|
* Creates/drops FTS5 virtual tables and sync triggers to match desired fulltext indexes.
|
|
549
585
|
*/
|
|
550
586
|
private _syncFtsIndexes;
|
|
587
|
+
/**
|
|
588
|
+
* Throws a clear error when SQLite lacks the index's configured tokenizer
|
|
589
|
+
* (since 0.1.175) — a tokenizer FTS5 does not ship (`snowball`, …) comes
|
|
590
|
+
* from an extension. Creates and drops a `temp` FTS5 table with it, so a
|
|
591
|
+
* rebuild fails before it drops the live table.
|
|
592
|
+
*/
|
|
593
|
+
private _probeFtsTokenizer;
|
|
551
594
|
/** Whether an existing FTS5 table has exactly the index's text columns, in order. */
|
|
552
595
|
private _ftsColumnsMatch;
|
|
553
596
|
/** Creates an FTS5 virtual table with sync triggers and rebuilds the index. */
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
import { ALL_AGGREGATE_FNS, ALL_BUCKET_UNITS, ALL_ISOLATION_LEVELS, ALL_VIEW_CAPABILITIES, BaseDbAdapter, DbError, DbSpace, constraintViolation, createChangeRecorder, defaultFulltextIndex, describeFulltext, fkColumns, searchIndexNotFoundMessage, searchTermInteger, splitFulltextFields, vectorIndexNotFoundMessage } from "@atscript/db";
|
|
2
|
+
import { ALL_AGGREGATE_FNS, ALL_BUCKET_UNITS, ALL_ISOLATION_LEVELS, ALL_VIEW_CAPABILITIES, BaseDbAdapter, DB_FULLTEXT_LANGUAGES, DbError, DbSpace, constraintViolation, createChangeRecorder, defaultFulltextIndex, describeFulltext, fkColumns, searchIndexNotFoundMessage, searchTermInteger, splitFulltextFields, vectorIndexNotFoundMessage } from "@atscript/db";
|
|
3
3
|
import { resolveAggregateSearch } from "@atscript/db/agg";
|
|
4
4
|
import { EMPTY_AND, InsertSqlCache, SEARCH_SOURCE_ALIAS, buildAggregateCount, buildAggregateSelect, buildCreateView, buildDelete, buildGeoSearchCount, buildGeoSearchSelect, buildJsonColumnCopy, buildJsonifyText, buildKeyViolationCount, buildPartitionedSelect, buildSelect, buildUpdate, buildVectorSearchCount, buildVectorSearchSelect, buildWhere as buildWhere$1, defaultValueForType, defaultValueToSqlLiteral, derivedColumnExpr, fillReplacePayload, fromSourceSql, geoWindowFromControls, jsonDollarPath, orFragment, orderByList, parseRegexString, refActionToSql, renameGeoDistance, replaceColumnsFor, searchRankOrder, sqlStringLiteral, sqlTimeZoneLiteral, stripPartitionRowNumber, toSqlValue, unquoteSqlStringLiteral, viewReadSource, writeLimitWhere } from "@atscript/db-sql-tools";
|
|
5
5
|
import { bucketer } from "@uniqu/core";
|
|
@@ -762,28 +762,82 @@ function quoteFtsTerm(text, match) {
|
|
|
762
762
|
}
|
|
763
763
|
return parts.length > 0 ? parts.join(match === "any" ? " OR " : " ") : "\"\"";
|
|
764
764
|
}
|
|
765
|
+
/** A tokenizer spec — words of letters, digits and `_`, separated by spaces (no quotes: it is inlined into DDL). */
|
|
766
|
+
const TOKENIZER_SPEC = /^[A-Za-z0-9_]+(?: +[A-Za-z0-9_]+)*$/;
|
|
765
767
|
/**
|
|
766
|
-
*
|
|
767
|
-
* (
|
|
768
|
+
* Checks `ftsTokenizers` (since 0.1.175): every key a `@db.index.fulltext.language`
|
|
769
|
+
* value, every tokenizer a plain spec (it is inlined into `CREATE VIRTUAL TABLE`).
|
|
770
|
+
* Throws on the first bad entry.
|
|
771
|
+
*/
|
|
772
|
+
function validateFtsTokenizers(tokenizers) {
|
|
773
|
+
for (const [language, tokenizer] of Object.entries(tokenizers ?? {})) {
|
|
774
|
+
if (tokenizer === void 0) continue;
|
|
775
|
+
if (!DB_FULLTEXT_LANGUAGES.includes(language)) throw new Error(`[sqlite] ftsTokenizers: "${language}" is not a @db.index.fulltext.language value`);
|
|
776
|
+
if (typeof tokenizer !== "string" || !TOKENIZER_SPEC.test(tokenizer)) throw new Error(`[sqlite] ftsTokenizers.${language}: ${JSON.stringify(tokenizer)} is not a tokenizer spec — use words of letters, digits and "_" separated by spaces (e.g. "snowball russian unicode61")`);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
/** FTS5's limits on the `prefix` option: lengths 1–999, at most 31 prefix indexes. */
|
|
780
|
+
const FTS_PREFIX_MAX_LENGTH = 999;
|
|
781
|
+
const FTS_PREFIX_MAX_COUNT = 31;
|
|
782
|
+
/**
|
|
783
|
+
* Checks `ftsPrefix` (since 0.1.175) and returns its canonical FTS5 `prefix`
|
|
784
|
+
* value — the distinct lengths ascending, space-separated (`"2 3"`) — or
|
|
785
|
+
* `undefined` when unset or empty. Throws on anything but integers 1–999
|
|
786
|
+
* (at most 31 distinct).
|
|
787
|
+
*/
|
|
788
|
+
function ftsPrefixSpec(prefix) {
|
|
789
|
+
if (prefix === void 0) return void 0;
|
|
790
|
+
if (!Array.isArray(prefix)) throw new Error(`[sqlite] ftsPrefix: ${JSON.stringify(prefix)} is not an array of prefix lengths`);
|
|
791
|
+
for (const length of prefix) if (!Number.isInteger(length) || length < 1 || length > FTS_PREFIX_MAX_LENGTH) throw new Error(`[sqlite] ftsPrefix: ${JSON.stringify(length)} is not a prefix length — use integers from 1 to ${FTS_PREFIX_MAX_LENGTH}`);
|
|
792
|
+
const lengths = [...new Set(prefix)].toSorted((a, b) => a - b);
|
|
793
|
+
if (lengths.length > FTS_PREFIX_MAX_COUNT) throw new Error(`[sqlite] ftsPrefix: ${lengths.length} prefix lengths — FTS5 allows at most ${FTS_PREFIX_MAX_COUNT}`);
|
|
794
|
+
return lengths.length > 0 ? lengths.join(" ") : void 0;
|
|
795
|
+
}
|
|
796
|
+
/** Whether an FTS5 table's `CREATE` statement has exactly the prefix indexes `spec` ({@link ftsPrefixSpec}) asks for. */
|
|
797
|
+
function ftsPrefixMatch(createSql, spec) {
|
|
798
|
+
const lengths = (/\bprefix\s*=\s*'([^']*)'/i.exec(createSql)?.[1])?.split(/[\s,]+/).filter(Boolean).map(Number).toSorted((a, b) => a - b);
|
|
799
|
+
return (lengths && lengths.length > 0 ? lengths.join(" ") : void 0) === spec;
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* The FTS5 `tokenize` option of a fulltext index: `configured` — the
|
|
803
|
+
* `ftsTokenizers` entry of its `@db.index.fulltext.language` (since 0.1.175)
|
|
804
|
+
* — else `english` adds the Porter stemmer (since 0.1.168); every other
|
|
768
805
|
* language — FTS5 ships no other stemmer — and no language keep FTS5's
|
|
769
806
|
* default `unicode61` (`undefined`: no `tokenize` clause).
|
|
770
807
|
*/
|
|
771
|
-
function ftsTokenizer(index) {
|
|
772
|
-
return index.language === "english" ? "porter unicode61" : void 0;
|
|
808
|
+
function ftsTokenizer(index, configured) {
|
|
809
|
+
return configured ?? (index.language === "english" ? "porter unicode61" : void 0);
|
|
773
810
|
}
|
|
774
811
|
/** Whether an FTS5 table's `CREATE` statement has the tokenizer the index's language asks for. */
|
|
775
|
-
function ftsTokenizerMatch(createSql, index) {
|
|
776
|
-
return /tokenize\s*=\s*'([^']*)'/i.exec(createSql)?.[1] === ftsTokenizer(index);
|
|
812
|
+
function ftsTokenizerMatch(createSql, index, configured) {
|
|
813
|
+
return /tokenize\s*=\s*'([^']*)'/i.exec(createSql)?.[1] === ftsTokenizer(index, configured);
|
|
777
814
|
}
|
|
778
|
-
/**
|
|
779
|
-
|
|
815
|
+
/**
|
|
816
|
+
* The sync warning for a language FTS5 cannot stem, `undefined` when it can,
|
|
817
|
+
* none is set, or an `ftsTokenizers` entry (`configured`) covers it.
|
|
818
|
+
*/
|
|
819
|
+
function ftsLanguageWarning(index, configured) {
|
|
780
820
|
const { language } = index;
|
|
781
821
|
if (language === void 0 || language === "english" || language === "none") return void 0;
|
|
782
|
-
|
|
822
|
+
if (configured !== void 0) return void 0;
|
|
823
|
+
return `[sqlite] fulltext index "${index.name}": FTS5 has no ${language} stemmer — words are indexed unstemmed (unicode61); set the adapter's ftsTokenizers to use a stemming tokenizer`;
|
|
783
824
|
}
|
|
784
825
|
//#endregion
|
|
785
826
|
//#region src/sqlite-adapter.ts
|
|
786
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.
|
|
831
|
+
*/
|
|
832
|
+
function mapBusy(error) {
|
|
833
|
+
if (!error || typeof error !== "object") return error;
|
|
834
|
+
const { code, errcode } = error;
|
|
835
|
+
return typeof code === "string" && code.startsWith("SQLITE_BUSY") || typeof errcode === "number" && (errcode & 255) === 5 ? new DbError("LOCK_TIMEOUT", [{
|
|
836
|
+
path: "",
|
|
837
|
+
message: error.message
|
|
838
|
+
}], void 0, { cause: error }) : error;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
787
841
|
* SQLite adapter for {@link AtscriptDbTable}.
|
|
788
842
|
*
|
|
789
843
|
* Accepts any {@link TSqliteDriver} implementation — the actual SQLite engine
|
|
@@ -869,14 +923,21 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
869
923
|
/** Per-driver transaction gate (shared by every adapter over this driver). */
|
|
870
924
|
_gate;
|
|
871
925
|
_txOptions;
|
|
926
|
+
/** `ftsTokenizers` — the FTS5 tokenizer per fulltext language (since 0.1.175). */
|
|
927
|
+
_ftsTokenizers;
|
|
928
|
+
/** `ftsPrefix` as the FTS5 `prefix` value (`"2 3"`), `undefined` when unset (since 0.1.175). */
|
|
929
|
+
_ftsPrefix;
|
|
872
930
|
/** Whether the driver has the calendar-bucket UDF — fixed at construction, when it is registered. */
|
|
873
931
|
_hasBucketFn;
|
|
874
932
|
constructor(driver, options) {
|
|
875
933
|
super();
|
|
876
934
|
this.driver = driver;
|
|
877
935
|
this._gate = getSqliteTxGate(driver);
|
|
878
|
-
const { viewJoinPruning, ...txOptions } = options ?? {};
|
|
936
|
+
const { viewJoinPruning, ftsTokenizers, ftsPrefix, ...txOptions } = options ?? {};
|
|
937
|
+
validateFtsTokenizers(ftsTokenizers);
|
|
879
938
|
this._txOptions = txOptions;
|
|
939
|
+
this._ftsTokenizers = ftsTokenizers;
|
|
940
|
+
this._ftsPrefix = ftsPrefixSpec(ftsPrefix);
|
|
880
941
|
this.viewJoinPruning = viewJoinPruning !== false;
|
|
881
942
|
this.driver.exec("PRAGMA foreign_keys = ON");
|
|
882
943
|
this._hasBucketFn = registerBucketFunction(driver);
|
|
@@ -997,9 +1058,10 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
997
1058
|
try {
|
|
998
1059
|
this._log("COMMIT");
|
|
999
1060
|
this.driver.exec("COMMIT");
|
|
1000
|
-
}
|
|
1001
|
-
|
|
1061
|
+
} catch (error) {
|
|
1062
|
+
throw mapBusy(error);
|
|
1002
1063
|
}
|
|
1064
|
+
state.release();
|
|
1003
1065
|
}
|
|
1004
1066
|
async _rollbackTransaction(state) {
|
|
1005
1067
|
try {
|
|
@@ -1630,7 +1692,7 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1630
1692
|
const plan = this._searchPlan(text, indexName);
|
|
1631
1693
|
const controls = query.controls || {};
|
|
1632
1694
|
const sorted = orderByList(sqliteDialect, controls.$sort, controls.$nulls, "t.");
|
|
1633
|
-
if (!plan.join && (sorted || plan.textFields === 0)) {
|
|
1695
|
+
if (controls.$rank === false || !plan.join && (sorted || plan.textFields === 0)) {
|
|
1634
1696
|
const { sql, params } = buildSelect$1(this.resolveTableName(), andWhere(plan.predicate, buildWhere(query.filter)), query.controls, searchRankOrder(sqliteDialect, {
|
|
1635
1697
|
...plan.exact,
|
|
1636
1698
|
pkColumns: this._pkColumns()
|
|
@@ -1822,6 +1884,21 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1822
1884
|
};
|
|
1823
1885
|
}
|
|
1824
1886
|
/**
|
|
1887
|
+
* The FTS5 settings adapter options give the index — its language's
|
|
1888
|
+
* `ftsTokenizers` entry and `ftsPrefix` (`"trigram; prefix=2 3"`) — part of
|
|
1889
|
+
* the schema hash (since 0.1.175). `undefined` when neither is set.
|
|
1890
|
+
*/
|
|
1891
|
+
fulltextEngineConfig(index) {
|
|
1892
|
+
const tokenizer = this._configuredFtsTokenizer(index);
|
|
1893
|
+
if (this._ftsPrefix === void 0) return tokenizer;
|
|
1894
|
+
const prefix = `prefix=${this._ftsPrefix}`;
|
|
1895
|
+
return tokenizer === void 0 ? prefix : `${tokenizer}; ${prefix}`;
|
|
1896
|
+
}
|
|
1897
|
+
/** The `ftsTokenizers` entry of the index's language (since 0.1.175). */
|
|
1898
|
+
_configuredFtsTokenizer(index) {
|
|
1899
|
+
return index.language === void 0 ? void 0 : this._ftsTokenizers?.[index.language];
|
|
1900
|
+
}
|
|
1901
|
+
/**
|
|
1825
1902
|
* Creates/drops FTS5 virtual tables and sync triggers to match desired fulltext indexes.
|
|
1826
1903
|
*/
|
|
1827
1904
|
async _syncFtsIndexes(tableName, dryRun) {
|
|
@@ -1829,7 +1906,7 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1829
1906
|
const ftIndexes = this._getFulltextIndexes().filter((idx) => splitFulltextFields(idx).text.length > 0);
|
|
1830
1907
|
const desiredFtsTables = new Set(ftIndexes.map((idx) => this._ftsTableName(idx.name)));
|
|
1831
1908
|
if (!dryRun) for (const index of ftIndexes) {
|
|
1832
|
-
const warning = ftsLanguageWarning(index);
|
|
1909
|
+
const warning = ftsLanguageWarning(index, this._configuredFtsTokenizer(index));
|
|
1833
1910
|
if (warning) this.logger.warn(warning);
|
|
1834
1911
|
}
|
|
1835
1912
|
const existingFts = this._shadowTableSql(tableName, "fts");
|
|
@@ -1843,17 +1920,40 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1843
1920
|
if (liveSql === void 0) await apply({
|
|
1844
1921
|
name: ftsTable,
|
|
1845
1922
|
action: "add"
|
|
1846
|
-
}, ftsTable, () =>
|
|
1847
|
-
|
|
1923
|
+
}, ftsTable, () => {
|
|
1924
|
+
this._probeFtsTokenizer(index);
|
|
1925
|
+
this._createFtsTable(tableName, ftsTable, index);
|
|
1926
|
+
});
|
|
1927
|
+
else if (!this._ftsColumnsMatch(ftsTable, index) || !ftsTokenizerMatch(liveSql, index, this._configuredFtsTokenizer(index)) || !ftsPrefixMatch(liveSql, this._ftsPrefix)) await apply({
|
|
1848
1928
|
name: ftsTable,
|
|
1849
1929
|
action: "rebuild"
|
|
1850
1930
|
}, ftsTable, () => {
|
|
1931
|
+
this._probeFtsTokenizer(index);
|
|
1851
1932
|
this._dropFtsTable(ftsTable);
|
|
1852
1933
|
this._createFtsTable(tableName, ftsTable, index);
|
|
1853
1934
|
});
|
|
1854
1935
|
}
|
|
1855
1936
|
return changes;
|
|
1856
1937
|
}
|
|
1938
|
+
/**
|
|
1939
|
+
* Throws a clear error when SQLite lacks the index's configured tokenizer
|
|
1940
|
+
* (since 0.1.175) — a tokenizer FTS5 does not ship (`snowball`, …) comes
|
|
1941
|
+
* from an extension. Creates and drops a `temp` FTS5 table with it, so a
|
|
1942
|
+
* rebuild fails before it drops the live table.
|
|
1943
|
+
*/
|
|
1944
|
+
_probeFtsTokenizer(index) {
|
|
1945
|
+
const tokenizer = this._configuredFtsTokenizer(index);
|
|
1946
|
+
if (!tokenizer) return;
|
|
1947
|
+
const probe = `temp."__atscript_fts_probe"`;
|
|
1948
|
+
try {
|
|
1949
|
+
this.driver.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS ${probe} USING fts5(x, tokenize='${tokenizer}')`);
|
|
1950
|
+
} catch (error) {
|
|
1951
|
+
const message = error?.message ?? "";
|
|
1952
|
+
if (!/no such tokenizer/i.test(message)) throw error;
|
|
1953
|
+
throw new Error(`[sqlite] fulltext index "${index.name}": FTS5 tokenizer "${tokenizer}" is not available (${message}) — load the SQLite extension that provides it with the driver's loadExtensions option`, { cause: error });
|
|
1954
|
+
}
|
|
1955
|
+
this.driver.exec(`DROP TABLE IF EXISTS ${probe}`);
|
|
1956
|
+
}
|
|
1857
1957
|
/** Whether an existing FTS5 table has exactly the index's text columns, in order. */
|
|
1858
1958
|
_ftsColumnsMatch(ftsTable, index) {
|
|
1859
1959
|
const live = this.driver.all(`PRAGMA table_info("${esc(ftsTable)}")`).map((c) => c.name);
|
|
@@ -1864,9 +1964,10 @@ var SqliteAdapter = class SqliteAdapter extends BaseDbAdapter {
|
|
|
1864
1964
|
_createFtsTable(tableName, ftsTable, index) {
|
|
1865
1965
|
const fields = splitFulltextFields(index).text;
|
|
1866
1966
|
const fieldList = fields.map((f) => `"${esc(f.name)}"`).join(", ");
|
|
1867
|
-
const tokenizer = ftsTokenizer(index);
|
|
1967
|
+
const tokenizer = ftsTokenizer(index, this._configuredFtsTokenizer(index));
|
|
1868
1968
|
const tokenize = tokenizer ? `, tokenize='${tokenizer}'` : "";
|
|
1869
|
-
const
|
|
1969
|
+
const prefix = this._ftsPrefix ? `, prefix='${this._ftsPrefix}'` : "";
|
|
1970
|
+
const createSql = `CREATE VIRTUAL TABLE IF NOT EXISTS "${esc(ftsTable)}" USING fts5(${fieldList}, content='${tableName.replace(/'/g, "''")}', content_rowid='rowid'${tokenize}${prefix})`;
|
|
1870
1971
|
this._log(createSql);
|
|
1871
1972
|
this.driver.exec(createSql);
|
|
1872
1973
|
const newFields = fields.map((f) => `new."${esc(f.name)}"`).join(", ");
|
|
@@ -2206,12 +2307,14 @@ function normalizeSqliteDefault(value) {
|
|
|
2206
2307
|
//#endregion
|
|
2207
2308
|
//#region src/index.ts
|
|
2208
2309
|
function createAdapter(connection, options) {
|
|
2209
|
-
const { transactionWaitTimeoutMs, transactionWaitWarnMs, viewJoinPruning, ...driverOptions } = options ?? {};
|
|
2310
|
+
const { transactionWaitTimeoutMs, transactionWaitWarnMs, viewJoinPruning, ftsTokenizers, ftsPrefix, ...driverOptions } = options ?? {};
|
|
2210
2311
|
const driver = new BetterSqlite3Driver(connection, driverOptions);
|
|
2211
2312
|
const adapterOptions = {
|
|
2212
2313
|
transactionWaitTimeoutMs,
|
|
2213
2314
|
transactionWaitWarnMs,
|
|
2214
|
-
viewJoinPruning
|
|
2315
|
+
viewJoinPruning,
|
|
2316
|
+
ftsTokenizers,
|
|
2317
|
+
ftsPrefix
|
|
2215
2318
|
};
|
|
2216
2319
|
return new DbSpace(() => new SqliteAdapter(driver, adapterOptions), { onClose: () => driver.close() });
|
|
2217
2320
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atscript/db-sqlite",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.175",
|
|
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.
|
|
39
|
+
"@atscript/db-sql-tools": "^0.1.175"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@atscript/core": "^0.2.
|
|
43
|
-
"@atscript/typescript": "^0.2.
|
|
42
|
+
"@atscript/core": "^0.2.11",
|
|
43
|
+
"@atscript/typescript": "^0.2.11",
|
|
44
44
|
"@types/better-sqlite3": "^7.6.13",
|
|
45
|
-
"@uniqu/core": "^0.2.
|
|
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.
|
|
48
|
+
"unplugin-atscript": "^0.2.11"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"@atscript/core": "^0.2.
|
|
52
|
-
"@atscript/typescript": "^0.2.
|
|
53
|
-
"@uniqu/core": "^0.2.
|
|
51
|
+
"@atscript/core": "^0.2.11",
|
|
52
|
+
"@atscript/typescript": "^0.2.11",
|
|
53
|
+
"@uniqu/core": "^0.2.2",
|
|
54
54
|
"better-sqlite3": ">=11.0.0",
|
|
55
|
-
"@atscript/db": "^0.1.
|
|
55
|
+
"@atscript/db": "^0.1.175"
|
|
56
56
|
},
|
|
57
57
|
"peerDependenciesMeta": {
|
|
58
58
|
"better-sqlite3": {
|