@mistriwork/search-sqlite 0.0.0-stage → 1.2.0
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/LICENSE +21 -0
- package/README.md +56 -2
- package/dist/index.d.ts +15 -0
- package/dist/index.js +85 -0
- package/dist/sqliteFts.d.ts +85 -0
- package/dist/sqliteFts.js +295 -0
- package/package.json +39 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Baljinder Randhawa
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,57 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mistriwork/search-sqlite
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
SQLite FTS5 as the search provider for a mistri App's `search` blocks.
|
|
4
|
+
|
|
5
|
+
## What it is
|
|
6
|
+
|
|
7
|
+
Search is an index, never a source of truth. The index holds a copy of the
|
|
8
|
+
fields a resource declares searchable, keyed by the record's primary key,
|
|
9
|
+
and answers a phrase with keys; the rows are re-read from the database under
|
|
10
|
+
the reader's own grants. The pack holds only what is SQLite's:
|
|
11
|
+
|
|
12
|
+
- `SqliteFtsIndex`: one FTS5 table per collection in one file, on Node's
|
|
13
|
+
built-in `node:sqlite` (zero extra runtime dependencies). It writes a
|
|
14
|
+
tenant's scope as an exact match on a column, ranks by bm25 with an
|
|
15
|
+
earlier declared field weighing more (full-text ranking: a rare word in a
|
|
16
|
+
later field can still outrank a common word in an earlier one), and
|
|
17
|
+
rebuilds a table when a declaration adds a field — FTS5 tables cannot be
|
|
18
|
+
altered. Collection and field names must be word characters; anything else
|
|
19
|
+
is refused rather than quoted.
|
|
20
|
+
- `sqliteSearchConnectionOf` & `sqliteSearch`: validates connection entries
|
|
21
|
+
and creates a `SearchProvider` whose `close()` releases open SQLite handles.
|
|
22
|
+
|
|
23
|
+
## How it plugs in
|
|
24
|
+
|
|
25
|
+
Pass the provider to `createHandler({ search })` from `@mistriwork/mistri/handler`,
|
|
26
|
+
or plug it into a `Registry` with `plugSearch` from `@mistriwork/mistri/search`:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { createHandler } from '@mistriwork/mistri/handler';
|
|
30
|
+
import { sqliteSearch } from '@mistriwork/search-sqlite';
|
|
31
|
+
|
|
32
|
+
const mistri = createHandler({
|
|
33
|
+
config: './mistri.json',
|
|
34
|
+
basePath: '/desk',
|
|
35
|
+
publicOrigin: 'https://example.com',
|
|
36
|
+
search: sqliteSearch([{ name: 'fts', file: './search.db' }]),
|
|
37
|
+
});
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
An App names the connection in its resource:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
resources: { ticket: { search: { connection: 'fts', fields: ['subject', 'requester.name'] } } }
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The file is opened on first use. `:memory:` holds the index in the process
|
|
47
|
+
only, like the built-in `memory` provider, and suits tests; a file survives
|
|
48
|
+
a restart, so no reindex is needed after one. `${VAR}` references in `file`
|
|
49
|
+
expand when the file opens.
|
|
50
|
+
|
|
51
|
+
## What it is not
|
|
52
|
+
|
|
53
|
+
- **Postgres tsvector.** Use `@mistriwork/search-postgres` when your
|
|
54
|
+
deployment runs PostgreSQL and wants GIN-indexed `tsvector` tables beside
|
|
55
|
+
its database.
|
|
56
|
+
- **A large catalog.** FTS5 in one file suits moderate tables. A large
|
|
57
|
+
catalog wants a dedicated engine such as Typesense.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { SearchProvider } from '@mistriwork/mistri/search';
|
|
2
|
+
export { SqliteFtsIndex } from './sqliteFts.js';
|
|
3
|
+
export interface SqliteSearchConnectionConfig {
|
|
4
|
+
name: string;
|
|
5
|
+
/** The index file; `:memory:` holds it in this process only, like the memory provider. */
|
|
6
|
+
file: string;
|
|
7
|
+
/** Collections are `<prefix>_<app>_<resource>`, so deployments can share one file. Default `mistri`. */
|
|
8
|
+
collectionPrefix?: string;
|
|
9
|
+
}
|
|
10
|
+
/** A connection entry, checked; `where` names it in a refusal. A config someone wrote is refused rather than half-read. */
|
|
11
|
+
export declare function sqliteSearchConnectionOf(entry: Record<string, unknown>, where: string): SqliteSearchConnectionConfig;
|
|
12
|
+
/** The provider core plugs in (`plugSearch(registry, sqliteSearch([...]))`): each connection by its name. */
|
|
13
|
+
export declare function sqliteSearch(connections: readonly SqliteSearchConnectionConfig[]): SearchProvider & {
|
|
14
|
+
close(): void;
|
|
15
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @mistriwork/search-sqlite: SQLite FTS5 as an App's search provider.
|
|
3
|
+
*
|
|
4
|
+
* Core asks a provider for the index a resource's `search.connection` names
|
|
5
|
+
* (packages/mistri/src/server/app/searchProvider.ts); this pack answers with
|
|
6
|
+
* an FTS5 table per collection in one SQLite file, over Node's built-in
|
|
7
|
+
* `node:sqlite` — no service, no SDK, no network. The connection is written
|
|
8
|
+
* as the deployment's own file:
|
|
9
|
+
*
|
|
10
|
+
* { "name": "fts", "file": "./search.db", "collectionPrefix": "acme" }
|
|
11
|
+
*
|
|
12
|
+
* and checked by `sqliteSearchConnectionOf` the same way.
|
|
13
|
+
*
|
|
14
|
+
* A file is opened on first use, never at plug-in, so a deployment that
|
|
15
|
+
* declares the connection but serves no searched App never touches the
|
|
16
|
+
* disk; `${VAR}` references in `file` expand when it opens, as a service
|
|
17
|
+
* URL's do, and are never logged. One file holds every collection, and one
|
|
18
|
+
* handle serves every App in the process; `close()` is for tests and
|
|
19
|
+
* shutdown, after which the next call reopens the file.
|
|
20
|
+
*/
|
|
21
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
22
|
+
import { SqliteFtsIndex } from './sqliteFts.js';
|
|
23
|
+
export { SqliteFtsIndex } from './sqliteFts.js';
|
|
24
|
+
function expandEnvReferences(value, env = process.env) {
|
|
25
|
+
return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
|
|
26
|
+
const resolved = env[name];
|
|
27
|
+
if (resolved === undefined) {
|
|
28
|
+
throw new Error(`Connection references $${name}, which is not set. Export it, or remove it from the connection.`);
|
|
29
|
+
}
|
|
30
|
+
return resolved;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
const KEYS = ['name', 'file', 'collectionPrefix'];
|
|
34
|
+
/** A connection entry, checked; `where` names it in a refusal. A config someone wrote is refused rather than half-read. */
|
|
35
|
+
export function sqliteSearchConnectionOf(entry, where) {
|
|
36
|
+
const unknown = Object.keys(entry).filter((key) => !KEYS.includes(key));
|
|
37
|
+
if (unknown.length)
|
|
38
|
+
throw new Error(`${where} names ${unknown.join(', ')}, which a SQLite search connection does not take (it takes ${KEYS.join(', ')}).`);
|
|
39
|
+
if (typeof entry.name !== 'string' || !entry.name)
|
|
40
|
+
throw new Error(`${where} has no "name".`);
|
|
41
|
+
if (typeof entry.file !== 'string' || !entry.file)
|
|
42
|
+
throw new Error(`${where} has no "file".`);
|
|
43
|
+
if (entry.collectionPrefix !== undefined &&
|
|
44
|
+
(typeof entry.collectionPrefix !== 'string' || !/^[A-Za-z][A-Za-z0-9_]{0,31}$/.test(entry.collectionPrefix))) {
|
|
45
|
+
throw new Error(`${where} has a "collectionPrefix" that is not a name of letters, digits and underscores, starting with a letter.`);
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
name: entry.name,
|
|
49
|
+
file: entry.file,
|
|
50
|
+
...(typeof entry.collectionPrefix === 'string' ? { collectionPrefix: entry.collectionPrefix } : {}),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** The provider core plugs in (`plugSearch(registry, sqliteSearch([...]))`): each connection by its name. */
|
|
54
|
+
export function sqliteSearch(connections) {
|
|
55
|
+
const names = connections.map((connection) => connection.name);
|
|
56
|
+
const twice = names.find((name, i) => names.indexOf(name) !== i);
|
|
57
|
+
if (twice)
|
|
58
|
+
throw new Error(`A search connection named "${twice}" is already configured.`);
|
|
59
|
+
const opened = new Map();
|
|
60
|
+
const open = (connection) => {
|
|
61
|
+
const known = opened.get(connection.name);
|
|
62
|
+
if (known)
|
|
63
|
+
return known.index;
|
|
64
|
+
const db = new DatabaseSync(expandEnvReferences(connection.file));
|
|
65
|
+
/* node:sqlite is synchronous, so a lock held by another process stalls the event loop for as long as this waits.
|
|
66
|
+
WAL lets a reader and a writer share the file without waiting on each other, and the short timeout bounds
|
|
67
|
+
the wait that remains to a blip rather than five seconds of a frozen server. */
|
|
68
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
69
|
+
db.exec('PRAGMA busy_timeout = 150');
|
|
70
|
+
const index = new SqliteFtsIndex(db, connection.collectionPrefix ?? 'mistri');
|
|
71
|
+
opened.set(connection.name, { db, index });
|
|
72
|
+
return index;
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
index(name) {
|
|
76
|
+
const connection = connections.find((each) => each.name === name);
|
|
77
|
+
return connection ? open(connection) : undefined;
|
|
78
|
+
},
|
|
79
|
+
close() {
|
|
80
|
+
for (const { db } of opened.values())
|
|
81
|
+
db.close();
|
|
82
|
+
opened.clear();
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A SQLite FTS5 index, on Node's built-in `node:sqlite` — the same driver
|
|
3
|
+
* the engine's SQLite adapter uses, so the pack adds no dependency and no
|
|
4
|
+
* service: the index is a file beside the deployment, one FTS5 table per
|
|
5
|
+
* collection, and it survives a restart, which the in-memory provider does
|
|
6
|
+
* not. That is the pack for an App whose tables are the moderate ones
|
|
7
|
+
* Mistri's home turf holds and whose deployment wants no external engine;
|
|
8
|
+
* a large catalog still wants the Typesense pack.
|
|
9
|
+
*
|
|
10
|
+
* Search is an index, never a source of truth: it holds a copy of the
|
|
11
|
+
* fields a resource declares searchable, keyed by the record's primary key,
|
|
12
|
+
* and answers a phrase with keys — the rows themselves are re-read from
|
|
13
|
+
* the database under the reader's own grants. It is core's `SearchIndex`
|
|
14
|
+
* (packages/mistri/src/server/app/searchProvider.ts), and nothing of
|
|
15
|
+
* SQLite's own shape leaves this file: a tenant's scope becomes an exact
|
|
16
|
+
* match on a column here, not in core.
|
|
17
|
+
*
|
|
18
|
+
* Ranking is FTS5's bm25, with an earlier declared field weighing more
|
|
19
|
+
* than a later one, and ties falling to the key, so two runs over the same
|
|
20
|
+
* index answer in the same order. It is full-text ranking, not the memory
|
|
21
|
+
* provider's strict field order: a rare word in a later field can outrank a
|
|
22
|
+
* common word in an earlier one, because bm25 weighs a word by how few
|
|
23
|
+
* documents hold it. A whole-phrase hit is asked beside each word hit
|
|
24
|
+
* (`"stone countertop" OR stone OR countertop`, per field), so a record
|
|
25
|
+
* holding the phrase ranks with the word hits rather than apart from them.
|
|
26
|
+
*
|
|
27
|
+
* FTS5 tables cannot be altered, so a field added to a declaration after
|
|
28
|
+
* the collection exists rebuilds the table: the rows are copied into a new
|
|
29
|
+
* table with the wider shape, the old table is dropped, and the new one is
|
|
30
|
+
* renamed, inside one transaction. A field is never dropped — a declaration
|
|
31
|
+
* that stops naming one leaves its column, unread, rather than rewriting
|
|
32
|
+
* the index.
|
|
33
|
+
*
|
|
34
|
+
* Core already passes the tenant field in with the declared fields, and
|
|
35
|
+
* the definition appends it once, so `ensureCollection` drops it from the
|
|
36
|
+
* incoming list first — naming it twice refuses the create, on every
|
|
37
|
+
* tenant App.
|
|
38
|
+
*
|
|
39
|
+
* FTS5's `id` is an ordinary unindexed column, so a delete by key scans
|
|
40
|
+
* the whole table and a full reindex grows quadratically. A second table
|
|
41
|
+
* maps each (tenant, key) to its FTS rowid, so an update deletes and
|
|
42
|
+
* re-inserts by rowid — a lookup, not a scan — and a rebuild copies rowids
|
|
43
|
+
* with the rows, so the map survives it. The map is backfilled from every
|
|
44
|
+
* row when it is created and holds every row written after, so a key the
|
|
45
|
+
* map lacks is a key the index lacks: nothing falls back to a scan. A
|
|
46
|
+
* record is keyed by its tenant and its id, so two tenants whose records
|
|
47
|
+
* share a primary key hold two documents.
|
|
48
|
+
*
|
|
49
|
+
* Identifiers are never interpolated unchecked: a collection name and every
|
|
50
|
+
* field name must be word characters (the runtime already sanitises a
|
|
51
|
+
* collection to `<prefix>_<app>_<resource>`), and anything else is refused.
|
|
52
|
+
* The names that pass are still quoted in a column list, so a field called
|
|
53
|
+
* `order` or `group` is a column, not a keyword; `rank` and `rowid` are
|
|
54
|
+
* refused by name, because FTS5 reserves them for its own columns.
|
|
55
|
+
*/
|
|
56
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
57
|
+
import { type SearchDocument, type SearchIndex, type SearchScope } from '@mistriwork/mistri/search';
|
|
58
|
+
/** One collection's table, in one file. */
|
|
59
|
+
export declare class SqliteFtsIndex implements SearchIndex {
|
|
60
|
+
private readonly db;
|
|
61
|
+
readonly collectionPrefix: string;
|
|
62
|
+
/** The fields each collection holds, as `ensureCollection` last left them. */
|
|
63
|
+
private readonly fields;
|
|
64
|
+
constructor(db: DatabaseSync, collectionPrefix: string);
|
|
65
|
+
/** The collection exists and holds every field named; a field added later rebuilds the table to hold it. */
|
|
66
|
+
ensureCollection(name: string, fields: readonly string[]): Promise<void>;
|
|
67
|
+
/** The (tenant, key)-to-rowid map for `table`, created when absent and backfilled once from the rows already there. An untenanted record keys on the empty tenant. */
|
|
68
|
+
private ensureKeys;
|
|
69
|
+
/** One unit of work or none: a delete without its insert would lose a document. */
|
|
70
|
+
private transact;
|
|
71
|
+
/** The record's document, replacing the document its tenant and key already had; a document whose collection was never ensured is ensured from its own fields. */
|
|
72
|
+
upsert(collection: string, document: SearchDocument): Promise<void>;
|
|
73
|
+
/** The rowid the key map holds for this tenant's `id`, or undefined where the map holds none. */
|
|
74
|
+
private keyRowid;
|
|
75
|
+
/**
|
|
76
|
+
* Gone from the index; a document that was never there is gone already, and a collection never ensured holds
|
|
77
|
+
* nothing — as does a name the index cannot hold. With a tenant scope only that tenant's document goes; without
|
|
78
|
+
* one, every tenant's document under that key does; core names the tenant of a tenant-owned row's removal (appSearchRuntime.ts).
|
|
79
|
+
*/
|
|
80
|
+
remove(collection: string, id: string, scope?: SearchScope): Promise<void>;
|
|
81
|
+
/** The keys of the best matches for `phrase` across `fields`, best first, at most `limit`; a collection never indexed matches nothing, and neither does a name the index cannot hold. */
|
|
82
|
+
search(collection: string, phrase: string, fields: readonly string[], limit: number, scope?: SearchScope): Promise<string[]>;
|
|
83
|
+
/** The fields a table on disk holds, remembered for the next call; undefined when the table is not there. */
|
|
84
|
+
private readFields;
|
|
85
|
+
}
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A SQLite FTS5 index, on Node's built-in `node:sqlite` — the same driver
|
|
3
|
+
* the engine's SQLite adapter uses, so the pack adds no dependency and no
|
|
4
|
+
* service: the index is a file beside the deployment, one FTS5 table per
|
|
5
|
+
* collection, and it survives a restart, which the in-memory provider does
|
|
6
|
+
* not. That is the pack for an App whose tables are the moderate ones
|
|
7
|
+
* Mistri's home turf holds and whose deployment wants no external engine;
|
|
8
|
+
* a large catalog still wants the Typesense pack.
|
|
9
|
+
*
|
|
10
|
+
* Search is an index, never a source of truth: it holds a copy of the
|
|
11
|
+
* fields a resource declares searchable, keyed by the record's primary key,
|
|
12
|
+
* and answers a phrase with keys — the rows themselves are re-read from
|
|
13
|
+
* the database under the reader's own grants. It is core's `SearchIndex`
|
|
14
|
+
* (packages/mistri/src/server/app/searchProvider.ts), and nothing of
|
|
15
|
+
* SQLite's own shape leaves this file: a tenant's scope becomes an exact
|
|
16
|
+
* match on a column here, not in core.
|
|
17
|
+
*
|
|
18
|
+
* Ranking is FTS5's bm25, with an earlier declared field weighing more
|
|
19
|
+
* than a later one, and ties falling to the key, so two runs over the same
|
|
20
|
+
* index answer in the same order. It is full-text ranking, not the memory
|
|
21
|
+
* provider's strict field order: a rare word in a later field can outrank a
|
|
22
|
+
* common word in an earlier one, because bm25 weighs a word by how few
|
|
23
|
+
* documents hold it. A whole-phrase hit is asked beside each word hit
|
|
24
|
+
* (`"stone countertop" OR stone OR countertop`, per field), so a record
|
|
25
|
+
* holding the phrase ranks with the word hits rather than apart from them.
|
|
26
|
+
*
|
|
27
|
+
* FTS5 tables cannot be altered, so a field added to a declaration after
|
|
28
|
+
* the collection exists rebuilds the table: the rows are copied into a new
|
|
29
|
+
* table with the wider shape, the old table is dropped, and the new one is
|
|
30
|
+
* renamed, inside one transaction. A field is never dropped — a declaration
|
|
31
|
+
* that stops naming one leaves its column, unread, rather than rewriting
|
|
32
|
+
* the index.
|
|
33
|
+
*
|
|
34
|
+
* Core already passes the tenant field in with the declared fields, and
|
|
35
|
+
* the definition appends it once, so `ensureCollection` drops it from the
|
|
36
|
+
* incoming list first — naming it twice refuses the create, on every
|
|
37
|
+
* tenant App.
|
|
38
|
+
*
|
|
39
|
+
* FTS5's `id` is an ordinary unindexed column, so a delete by key scans
|
|
40
|
+
* the whole table and a full reindex grows quadratically. A second table
|
|
41
|
+
* maps each (tenant, key) to its FTS rowid, so an update deletes and
|
|
42
|
+
* re-inserts by rowid — a lookup, not a scan — and a rebuild copies rowids
|
|
43
|
+
* with the rows, so the map survives it. The map is backfilled from every
|
|
44
|
+
* row when it is created and holds every row written after, so a key the
|
|
45
|
+
* map lacks is a key the index lacks: nothing falls back to a scan. A
|
|
46
|
+
* record is keyed by its tenant and its id, so two tenants whose records
|
|
47
|
+
* share a primary key hold two documents.
|
|
48
|
+
*
|
|
49
|
+
* Identifiers are never interpolated unchecked: a collection name and every
|
|
50
|
+
* field name must be word characters (the runtime already sanitises a
|
|
51
|
+
* collection to `<prefix>_<app>_<resource>`), and anything else is refused.
|
|
52
|
+
* The names that pass are still quoted in a column list, so a field called
|
|
53
|
+
* `order` or `group` is a column, not a keyword; `rank` and `rowid` are
|
|
54
|
+
* refused by name, because FTS5 reserves them for its own columns.
|
|
55
|
+
*/
|
|
56
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
57
|
+
import { SearchUnavailable } from '@mistriwork/mistri/search';
|
|
58
|
+
/** The document field that holds a tenant-owned record's tenant (appSearchRuntime.ts); kept in every table, unindexed. */
|
|
59
|
+
const TENANT_FIELD = 'mistri_tenant';
|
|
60
|
+
/** A name this file interpolates into SQL: word characters only, so no quoting is ever needed. */
|
|
61
|
+
const isIdentifier = (name) => /^[A-Za-z0-9_]+$/.test(name);
|
|
62
|
+
const identifier = (name, what) => {
|
|
63
|
+
if (!isIdentifier(name))
|
|
64
|
+
throw new Error(`${what} "${name}" is not a name of letters, digits and underscores.`);
|
|
65
|
+
return name;
|
|
66
|
+
};
|
|
67
|
+
/** A searched field: a name, and not one FTS5 keeps for its own columns (`rank`, `rowid`), which a column of that name would shadow. */
|
|
68
|
+
const searchedField = (name) => {
|
|
69
|
+
identifier(name, 'A searched field');
|
|
70
|
+
if (/^(rank|rowid)$/i.test(name)) {
|
|
71
|
+
throw new Error(`A searched field "${name}" is a name FTS5 reserves for its own column; rename the field.`);
|
|
72
|
+
}
|
|
73
|
+
return name;
|
|
74
|
+
};
|
|
75
|
+
const quote = (column) => `"${column}"`;
|
|
76
|
+
/** The FTS5 definition of a collection: the key unindexed, each declared field searchable, the tenant unindexed. */
|
|
77
|
+
const definition = (fields) => ['id UNINDEXED', ...fields.map((field) => quote(searchedField(field))), `${TENANT_FIELD} UNINDEXED`].join(', ');
|
|
78
|
+
/** The tokens FTS5's unicode61 tokenizer would read from a phrase: letters, digits and underscores, in order. */
|
|
79
|
+
const tokensOf = (phrase) => phrase.match(/[\p{L}\p{N}_]+/gu) ?? [];
|
|
80
|
+
/** One token as an FTS5 phrase atom: quoted, so a hyphen or other syntax in it is a word, not an operator. */
|
|
81
|
+
const atom = (token) => `"${token.replace(/"/g, '""')}"`;
|
|
82
|
+
/**
|
|
83
|
+
* The MATCH expression for `phrase` across `fields`: for each field, the
|
|
84
|
+
* whole phrase beside each word, so a phrase hit and a word hit are both
|
|
85
|
+
* asked and bm25 orders them. Empty when the phrase holds no token.
|
|
86
|
+
*/
|
|
87
|
+
const matchOf = (phrase, fields) => {
|
|
88
|
+
const tokens = tokensOf(phrase);
|
|
89
|
+
if (!tokens.length)
|
|
90
|
+
return undefined;
|
|
91
|
+
const atoms = [...(tokens.length > 1 ? [tokens.map(atom).join(' ')] : []), ...tokens.map(atom)];
|
|
92
|
+
const parts = [];
|
|
93
|
+
for (const field of fields)
|
|
94
|
+
for (const phraseAtom of atoms)
|
|
95
|
+
parts.push(`{${field}} : ${phraseAtom}`);
|
|
96
|
+
return parts.join(' OR ');
|
|
97
|
+
};
|
|
98
|
+
/** One collection's table, in one file. */
|
|
99
|
+
export class SqliteFtsIndex {
|
|
100
|
+
db;
|
|
101
|
+
collectionPrefix;
|
|
102
|
+
/** The fields each collection holds, as `ensureCollection` last left them. */
|
|
103
|
+
fields = new Map();
|
|
104
|
+
constructor(db, collectionPrefix) {
|
|
105
|
+
this.db = db;
|
|
106
|
+
this.collectionPrefix = collectionPrefix;
|
|
107
|
+
}
|
|
108
|
+
/** The collection exists and holds every field named; a field added later rebuilds the table to hold it. */
|
|
109
|
+
async ensureCollection(name, fields) {
|
|
110
|
+
const table = identifier(name, 'A search collection');
|
|
111
|
+
/* Core already passes the tenant field in; the definition appends it
|
|
112
|
+
once, so it is dropped here first — naming it twice refuses the
|
|
113
|
+
create, on every tenant App. */
|
|
114
|
+
const wanted = fields.filter((field) => field !== TENANT_FIELD).map(searchedField);
|
|
115
|
+
const have = this.fields.get(table) ?? this.readFields(table);
|
|
116
|
+
if (!have) {
|
|
117
|
+
this.db.exec(`CREATE VIRTUAL TABLE "${table}" USING fts5(${definition(wanted)}, tokenize='unicode61')`);
|
|
118
|
+
this.fields.set(table, [...wanted]);
|
|
119
|
+
this.ensureKeys(table);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
this.ensureKeys(table);
|
|
123
|
+
const missing = wanted.filter((field) => !have.includes(field));
|
|
124
|
+
if (!missing.length)
|
|
125
|
+
return;
|
|
126
|
+
const next = [...have, ...missing];
|
|
127
|
+
this.db.exec('BEGIN');
|
|
128
|
+
try {
|
|
129
|
+
this.db.exec(`CREATE VIRTUAL TABLE "${table}__next" USING fts5(${definition(next)}, tokenize='unicode61')`);
|
|
130
|
+
/* Rowids travel with the rows, so the key map still names the same
|
|
131
|
+
rows after the rename — it is not rebuilt, only the table is. */
|
|
132
|
+
const columns = ['rowid', 'id', ...have, TENANT_FIELD].map(quote).join(', ');
|
|
133
|
+
this.db.exec(`INSERT INTO "${table}__next"(${columns}) SELECT ${columns} FROM "${table}"`);
|
|
134
|
+
this.db.exec(`DROP TABLE "${table}"`);
|
|
135
|
+
this.db.exec(`ALTER TABLE "${table}__next" RENAME TO "${table}"`);
|
|
136
|
+
this.db.exec('COMMIT');
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
try {
|
|
140
|
+
this.db.exec('ROLLBACK');
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
/* The rollback itself failed; the error below is the one that matters. */
|
|
144
|
+
}
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
this.fields.set(table, next);
|
|
148
|
+
}
|
|
149
|
+
/** The (tenant, key)-to-rowid map for `table`, created when absent and backfilled once from the rows already there. An untenanted record keys on the empty tenant. */
|
|
150
|
+
ensureKeys(table) {
|
|
151
|
+
const keys = `${table}__keys`;
|
|
152
|
+
const found = this.db.prepare(`SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name = ?`).get(keys);
|
|
153
|
+
if (found && found.count > 0)
|
|
154
|
+
return;
|
|
155
|
+
this.db.exec(`CREATE TABLE "${keys}"(tenant TEXT NOT NULL, id TEXT NOT NULL, rowid INTEGER NOT NULL, PRIMARY KEY (tenant, id))`);
|
|
156
|
+
this.db.exec(`INSERT INTO "${keys}"(tenant, id, rowid) SELECT coalesce("${TENANT_FIELD}", ''), id, rowid FROM "${table}"`);
|
|
157
|
+
}
|
|
158
|
+
/** One unit of work or none: a delete without its insert would lose a document. */
|
|
159
|
+
transact(work) {
|
|
160
|
+
this.db.exec('BEGIN');
|
|
161
|
+
try {
|
|
162
|
+
work();
|
|
163
|
+
this.db.exec('COMMIT');
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
try {
|
|
167
|
+
this.db.exec('ROLLBACK');
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
/* The rollback itself failed; the error below is the one that matters. */
|
|
171
|
+
}
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/** The record's document, replacing the document its tenant and key already had; a document whose collection was never ensured is ensured from its own fields. */
|
|
176
|
+
async upsert(collection, document) {
|
|
177
|
+
const table = identifier(collection, 'A search collection');
|
|
178
|
+
const fields = Object.keys(document).filter((key) => key !== 'id' && key !== TENANT_FIELD);
|
|
179
|
+
await this.ensureCollection(table, fields);
|
|
180
|
+
const held = this.fields.get(table);
|
|
181
|
+
const keys = `${table}__keys`;
|
|
182
|
+
const tenant = document[TENANT_FIELD] ?? '';
|
|
183
|
+
const columns = ['id', ...held, TENANT_FIELD];
|
|
184
|
+
const values = columns.map((column) => column === 'id' ? document.id : (document[column] ?? null));
|
|
185
|
+
const insert = (extra, extraValues) => this.db
|
|
186
|
+
.prepare(`INSERT INTO "${table}"(${[...extra, ...columns].map(quote).join(', ')}) VALUES (${[...extra, ...columns].map(() => '?').join(', ')})`)
|
|
187
|
+
.run(...extraValues, ...values);
|
|
188
|
+
/* A known key reuses its rowid: the old row is deleted by rowid and
|
|
189
|
+
the new one takes the same rowid, so the map never moves. A new key
|
|
190
|
+
records the rowid its insert got. The map holds every row (see
|
|
191
|
+
ensureKeys), so a key it lacks has no row to delete — a delete by
|
|
192
|
+
`id` would scan the whole table, since FTS5 indexes no such column. */
|
|
193
|
+
this.transact(() => {
|
|
194
|
+
const known = this.keyRowid(table, tenant, document.id);
|
|
195
|
+
if (known !== undefined) {
|
|
196
|
+
this.db.prepare(`DELETE FROM "${table}" WHERE rowid = ?`).run(known);
|
|
197
|
+
insert(['rowid'], [known]);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const result = insert([], []);
|
|
201
|
+
this.db.prepare(`INSERT INTO "${keys}"(tenant, id, rowid) VALUES (?, ?, ?)`).run(tenant, document.id, result.lastInsertRowid);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
/** The rowid the key map holds for this tenant's `id`, or undefined where the map holds none. */
|
|
205
|
+
keyRowid(table, tenant, id) {
|
|
206
|
+
const row = this.db.prepare(`SELECT rowid FROM "${table}__keys" WHERE tenant = ? AND id = ?`).get(tenant, id);
|
|
207
|
+
return row?.rowid;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Gone from the index; a document that was never there is gone already, and a collection never ensured holds
|
|
211
|
+
* nothing — as does a name the index cannot hold. With a tenant scope only that tenant's document goes; without
|
|
212
|
+
* one, every tenant's document under that key does; core names the tenant of a tenant-owned row's removal (appSearchRuntime.ts).
|
|
213
|
+
*/
|
|
214
|
+
async remove(collection, id, scope) {
|
|
215
|
+
if (!isIdentifier(collection))
|
|
216
|
+
return;
|
|
217
|
+
const table = collection;
|
|
218
|
+
if (!this.readFields(table))
|
|
219
|
+
return;
|
|
220
|
+
this.ensureKeys(table);
|
|
221
|
+
const keys = `${table}__keys`;
|
|
222
|
+
const tenant = scope?.field === TENANT_FIELD ? scope.value : undefined;
|
|
223
|
+
this.transact(() => {
|
|
224
|
+
const rows = (tenant === undefined
|
|
225
|
+
? this.db.prepare(`SELECT rowid FROM "${keys}" WHERE id = ?`).all(id)
|
|
226
|
+
: this.db.prepare(`SELECT rowid FROM "${keys}" WHERE tenant = ? AND id = ?`).all(tenant, id));
|
|
227
|
+
for (const row of rows)
|
|
228
|
+
this.db.prepare(`DELETE FROM "${table}" WHERE rowid = ?`).run(row.rowid);
|
|
229
|
+
if (tenant === undefined)
|
|
230
|
+
this.db.prepare(`DELETE FROM "${keys}" WHERE id = ?`).run(id);
|
|
231
|
+
else
|
|
232
|
+
this.db.prepare(`DELETE FROM "${keys}" WHERE tenant = ? AND id = ?`).run(tenant, id);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
/** The keys of the best matches for `phrase` across `fields`, best first, at most `limit`; a collection never indexed matches nothing, and neither does a name the index cannot hold. */
|
|
236
|
+
async search(collection, phrase, fields, limit, scope) {
|
|
237
|
+
if (limit <= 0 || !isIdentifier(collection))
|
|
238
|
+
return [];
|
|
239
|
+
const table = collection;
|
|
240
|
+
const held = this.fields.get(table) ?? this.readFields(table);
|
|
241
|
+
if (!held)
|
|
242
|
+
return [];
|
|
243
|
+
const asked = fields.filter((field) => isIdentifier(field) && held.includes(field));
|
|
244
|
+
if (!asked.length)
|
|
245
|
+
return [];
|
|
246
|
+
const match = matchOf(phrase, asked);
|
|
247
|
+
if (!match)
|
|
248
|
+
return [];
|
|
249
|
+
/* bm25 weights follow the table's columns in order, the key and the
|
|
250
|
+
tenant included at zero: a searched field weighs by its place in the
|
|
251
|
+
asked order (an earlier field more), and an unsearched column weighs
|
|
252
|
+
nothing, so it cannot lift a match. */
|
|
253
|
+
const weights = [
|
|
254
|
+
'0.0',
|
|
255
|
+
...held.map((field) => {
|
|
256
|
+
const at = asked.indexOf(field);
|
|
257
|
+
return at < 0 ? '0.0' : String(asked.length - at);
|
|
258
|
+
}),
|
|
259
|
+
'0.0',
|
|
260
|
+
];
|
|
261
|
+
const params = [match];
|
|
262
|
+
let where = `"${table}" MATCH ?`;
|
|
263
|
+
if (scope) {
|
|
264
|
+
if (!isIdentifier(scope.field))
|
|
265
|
+
return [];
|
|
266
|
+
if (scope.field !== TENANT_FIELD && !held.includes(scope.field))
|
|
267
|
+
return [];
|
|
268
|
+
where += ` AND "${scope.field}" = ?`;
|
|
269
|
+
params.push(scope.value);
|
|
270
|
+
}
|
|
271
|
+
params.push(Math.floor(limit));
|
|
272
|
+
try {
|
|
273
|
+
return this.db
|
|
274
|
+
.prepare(`SELECT id FROM "${table}" WHERE ${where} ORDER BY bm25("${table}", ${weights.join(', ')}), id LIMIT ?`)
|
|
275
|
+
.all(...params).map((row) => row.id);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
throw new SearchUnavailable(`search "${table}" could not be asked: ${error.message}`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/** The fields a table on disk holds, remembered for the next call; undefined when the table is not there. */
|
|
282
|
+
readFields(table) {
|
|
283
|
+
try {
|
|
284
|
+
const rows = this.db.prepare(`SELECT name FROM pragma_table_info(?)`).all(table);
|
|
285
|
+
if (!rows.length)
|
|
286
|
+
return undefined;
|
|
287
|
+
const held = rows.map((row) => row.name).filter((name) => name !== 'id' && name !== TENANT_FIELD);
|
|
288
|
+
this.fields.set(table, held);
|
|
289
|
+
return held;
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
return undefined;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mistriwork/search-sqlite",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "SQLite FTS5 search provider pack for mistri Apps, over Node's built-in node:sqlite with zero extra dependencies.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mistri",
|
|
7
|
+
"search",
|
|
8
|
+
"sqlite",
|
|
9
|
+
"fts5",
|
|
10
|
+
"full-text-search"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://mistriwork.dev",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/rbaljinder/mistri/issues"
|
|
15
|
+
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"author": "Baljinder Randhawa",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/rbaljinder/mistri.git",
|
|
21
|
+
"directory": "packages/search-sqlite"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"type": "module",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@mistriwork/mistri": "1.2.0"
|
|
37
|
+
},
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=24"
|
|
40
|
+
}
|
|
41
|
+
}
|