@mistriwork/search-postgres 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 +59 -2
- package/dist/index.d.ts +40 -0
- package/dist/index.js +58 -0
- package/dist/postgresTsvector.d.ts +33 -0
- package/dist/postgresTsvector.js +377 -0
- package/package.json +46 -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,60 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mistriwork/search-postgres
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
PostgreSQL `tsvector` + GIN 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 PostgreSQL's:
|
|
11
|
+
|
|
12
|
+
- `PostgresTsvectorIndex`: one table per collection in the database the
|
|
13
|
+
connection names, over `pg` (loaded lazily on first use). Each table holds
|
|
14
|
+
`id text NOT NULL`, each declared field as `text`, `mistri_tenant text`,
|
|
15
|
+
one generated `tsvector` column per field (`to_tsvector('simple', coalesce(field, ''))`)
|
|
16
|
+
with a GIN index per vector column, and a unique index on
|
|
17
|
+
`(id, coalesce(mistri_tenant, ''))`. It ranks by `ts_rank` with an earlier
|
|
18
|
+
asked field weighing more and ties falling to `id`, and rebuilds a table
|
|
19
|
+
under an advisory lock when a declaration adds a field. Field lists are
|
|
20
|
+
cached per process and refreshed from the catalog when another process
|
|
21
|
+
rebuilds the table.
|
|
22
|
+
- `postgresSearchConnectionOf` & `postgresSearch`: validates connection
|
|
23
|
+
entries and creates a `SearchProvider` whose `close()` drains open pools.
|
|
24
|
+
|
|
25
|
+
## How it plugs in
|
|
26
|
+
|
|
27
|
+
Pass the provider to `createHandler({ search })` from `@mistriwork/mistri/handler`,
|
|
28
|
+
or plug it into a `Registry` with `plugSearch` from `@mistriwork/mistri/search`:
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { createHandler } from '@mistriwork/mistri/handler';
|
|
32
|
+
import { postgresSearch } from '@mistriwork/search-postgres';
|
|
33
|
+
|
|
34
|
+
const mistri = createHandler({
|
|
35
|
+
config: './mistri.json',
|
|
36
|
+
basePath: '/desk',
|
|
37
|
+
publicOrigin: 'https://example.com',
|
|
38
|
+
search: postgresSearch([{ name: 'pgsearch', url: '${DATABASE_URL}' }]),
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
An App names the connection in its resource:
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
resources: { ticket: { search: { connection: 'pgsearch', fields: ['subject', 'requester.name'] } } }
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The pool is opened on first use. `${VAR}` references in `url` expand when it
|
|
49
|
+
opens and are never logged. The index lives in PostgreSQL tables, so it
|
|
50
|
+
survives restarts with no reindex required.
|
|
51
|
+
|
|
52
|
+
## What it is not
|
|
53
|
+
|
|
54
|
+
- **A large catalog.** `tsvector` tables beside the deployment's database
|
|
55
|
+
suit moderate tables. A large catalog wants a dedicated engine such as
|
|
56
|
+
Typesense.
|
|
57
|
+
- **A schema-scoped runtime store.** Provisioning is lazy on
|
|
58
|
+
`ensureCollection`; point the connection at a dedicated database or a role
|
|
59
|
+
with a pinned `search_path` when the index should not share a schema with
|
|
60
|
+
business tables.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @mistriwork/search-postgres: Postgres tsvector 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
|
+
* a tsvector table per collection in the database the connection names, over
|
|
7
|
+
* `pg` — already an optional dependency of the engine, loaded on first use,
|
|
8
|
+
* so the pack adds no dependency. The connection is written as the
|
|
9
|
+
* deployment's own database URL:
|
|
10
|
+
*
|
|
11
|
+
* { "name": "pgsearch", "url": "${DATABASE_URL}", "collectionPrefix": "acme" }
|
|
12
|
+
*
|
|
13
|
+
* and checked by `postgresSearchConnectionOf` the same way.
|
|
14
|
+
*
|
|
15
|
+
* A pool is opened on first use, never at plug-in, so a deployment that
|
|
16
|
+
* declares the connection but serves no searched App never connects;
|
|
17
|
+
* `${VAR}` references in `url` expand when it opens, as a service URL's do,
|
|
18
|
+
* and are never logged. One database holds every collection, and one pool
|
|
19
|
+
* serves every App in the process; `close()` is for tests and shutdown,
|
|
20
|
+
* after which the next call reopens the pool. The index itself is tables
|
|
21
|
+
* in Postgres, so it survives a restart and no reindex is needed after one.
|
|
22
|
+
* The index is a copy: a record deleted outside the App keeps its document
|
|
23
|
+
* until the next write or reindex, and searches already hide rows the
|
|
24
|
+
* database no longer has.
|
|
25
|
+
*/
|
|
26
|
+
import type { SearchProvider } from '@mistriwork/mistri/search';
|
|
27
|
+
export { PostgresTsvectorIndex } from './postgresTsvector.js';
|
|
28
|
+
export interface PostgresSearchConnectionConfig {
|
|
29
|
+
name: string;
|
|
30
|
+
/** The database that holds the index tables; a Postgres URL, as a mistri connection's `url` is. */
|
|
31
|
+
url: string;
|
|
32
|
+
/** Collections are `<prefix>_<app>_<resource>`, so deployments can share one database. Default `mistri`. */
|
|
33
|
+
collectionPrefix?: string;
|
|
34
|
+
}
|
|
35
|
+
/** A connection entry, checked; `where` names it in a refusal. A config someone wrote is refused rather than half-read. */
|
|
36
|
+
export declare function postgresSearchConnectionOf(entry: Record<string, unknown>, where: string): PostgresSearchConnectionConfig;
|
|
37
|
+
/** The provider core plugs in (`plugSearch(registry, postgresSearch([...]))`): each connection by its name. */
|
|
38
|
+
export declare function postgresSearch(connections: readonly PostgresSearchConnectionConfig[]): SearchProvider & {
|
|
39
|
+
close(): Promise<void>;
|
|
40
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { PostgresTsvectorIndex } from './postgresTsvector.js';
|
|
2
|
+
export { PostgresTsvectorIndex } from './postgresTsvector.js';
|
|
3
|
+
function expandEnvReferences(value, env = process.env) {
|
|
4
|
+
return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
|
|
5
|
+
const resolved = env[name];
|
|
6
|
+
if (resolved === undefined) {
|
|
7
|
+
throw new Error(`Connection references $${name}, which is not set. Export it, or remove it from the connection.`);
|
|
8
|
+
}
|
|
9
|
+
return resolved;
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
const KEYS = ['name', 'url', 'collectionPrefix'];
|
|
13
|
+
/** A connection entry, checked; `where` names it in a refusal. A config someone wrote is refused rather than half-read. */
|
|
14
|
+
export function postgresSearchConnectionOf(entry, where) {
|
|
15
|
+
const unknown = Object.keys(entry).filter((key) => !KEYS.includes(key));
|
|
16
|
+
if (unknown.length)
|
|
17
|
+
throw new Error(`${where} names ${unknown.join(', ')}, which a Postgres search connection does not take (it takes ${KEYS.join(', ')}).`);
|
|
18
|
+
if (typeof entry.name !== 'string' || !entry.name)
|
|
19
|
+
throw new Error(`${where} has no "name".`);
|
|
20
|
+
if (typeof entry.url !== 'string' || !entry.url)
|
|
21
|
+
throw new Error(`${where} has no "url".`);
|
|
22
|
+
if (entry.collectionPrefix !== undefined &&
|
|
23
|
+
(typeof entry.collectionPrefix !== 'string' || !/^[A-Za-z][A-Za-z0-9_]{0,31}$/.test(entry.collectionPrefix))) {
|
|
24
|
+
throw new Error(`${where} has a "collectionPrefix" that is not a name of letters, digits and underscores, starting with a letter.`);
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
name: entry.name,
|
|
28
|
+
url: entry.url,
|
|
29
|
+
...(typeof entry.collectionPrefix === 'string' ? { collectionPrefix: entry.collectionPrefix } : {}),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** The provider core plugs in (`plugSearch(registry, postgresSearch([...]))`): each connection by its name. */
|
|
33
|
+
export function postgresSearch(connections) {
|
|
34
|
+
const names = connections.map((connection) => connection.name);
|
|
35
|
+
const twice = names.find((name, i) => names.indexOf(name) !== i);
|
|
36
|
+
if (twice)
|
|
37
|
+
throw new Error(`A search connection named "${twice}" is already configured.`);
|
|
38
|
+
const opened = new Map();
|
|
39
|
+
const open = (connection) => {
|
|
40
|
+
const known = opened.get(connection.name);
|
|
41
|
+
if (known)
|
|
42
|
+
return known;
|
|
43
|
+
const index = new PostgresTsvectorIndex(expandEnvReferences(connection.url), connection.collectionPrefix ?? 'mistri');
|
|
44
|
+
opened.set(connection.name, index);
|
|
45
|
+
return index;
|
|
46
|
+
};
|
|
47
|
+
return {
|
|
48
|
+
index(name) {
|
|
49
|
+
const connection = connections.find((each) => each.name === name);
|
|
50
|
+
return connection ? open(connection) : undefined;
|
|
51
|
+
},
|
|
52
|
+
async close() {
|
|
53
|
+
for (const index of opened.values())
|
|
54
|
+
await index.close();
|
|
55
|
+
opened.clear();
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type SearchDocument, type SearchIndex, type SearchScope } from '@mistriwork/mistri/search';
|
|
2
|
+
/** One collection's table, in one database. */
|
|
3
|
+
export declare class PostgresTsvectorIndex implements SearchIndex {
|
|
4
|
+
private readonly connectionString;
|
|
5
|
+
readonly collectionPrefix: string;
|
|
6
|
+
private pool;
|
|
7
|
+
/** The searchable fields each table held when last read; see `readFields` for when it is read again. */
|
|
8
|
+
private readonly fields;
|
|
9
|
+
constructor(connectionString: string, collectionPrefix: string);
|
|
10
|
+
/** The pool, opened on first use, never at plug-in, so a deployment that declares the connection but serves no searched App never connects. */
|
|
11
|
+
private db;
|
|
12
|
+
/** Ends the pool; the next call reopens it. For tests and shutdown — the index itself is tables in Postgres and survives. */
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
/** The collection exists and holds every field named; a field added later rebuilds the table to hold it. */
|
|
15
|
+
ensureCollection(name: string, fields: readonly string[]): Promise<void>;
|
|
16
|
+
/** 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. */
|
|
17
|
+
upsert(collection: string, document: SearchDocument): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* Gone from the index; a document that was never there is gone already, and a collection never ensured holds
|
|
20
|
+
* nothing — as does a name the index cannot hold. With a tenant scope only that tenant's document goes; without
|
|
21
|
+
* one, every tenant's document under that key does; core names the tenant of a tenant-owned row's removal (appSearchRuntime.ts).
|
|
22
|
+
*/
|
|
23
|
+
remove(collection: string, id: string, scope?: SearchScope): Promise<void>;
|
|
24
|
+
/** 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. */
|
|
25
|
+
search(collection: string, phrase: string, fields: readonly string[], limit: number, scope?: SearchScope): Promise<string[]>;
|
|
26
|
+
private ask;
|
|
27
|
+
/** Runs `run`; a statement that meets an undefined column ran against a stale field list, so it runs once more on a fresh one. */
|
|
28
|
+
private afresh;
|
|
29
|
+
/** The searchable fields a table holds: the process's cache, or the catalog when `fresh` or not yet read; undefined when the table is not there (never cached, so a table another process creates is seen). */
|
|
30
|
+
private readFields;
|
|
31
|
+
/** The searchable fields a table holds, from the catalog. Text columns only, so a vector column never reads as a field. */
|
|
32
|
+
private catalogFields;
|
|
33
|
+
}
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A Postgres tsvector index, on the `pg` package — already an optional
|
|
3
|
+
* dependency of the engine, loaded the way the engine loads it (a dynamic
|
|
4
|
+
* import, so a deployment without `pg` is told to install it rather than
|
|
5
|
+
* crashing on a missing import), so the pack adds no dependency and no
|
|
6
|
+
* service: the index is tables in the database the connection names, one
|
|
7
|
+
* table per collection, and it survives a restart, which the in-memory
|
|
8
|
+
* provider does not. That is the pack for an App whose deployment already
|
|
9
|
+
* runs Postgres and wants its search beside its tables; a large catalog
|
|
10
|
+
* still wants the Typesense pack.
|
|
11
|
+
*
|
|
12
|
+
* Search is an index, never a source of truth: it holds a copy of the
|
|
13
|
+
* fields a resource declares searchable, keyed by the record's primary key,
|
|
14
|
+
* and answers a phrase with keys — the rows themselves are re-read from
|
|
15
|
+
* the database under the reader's own grants. It is core's `SearchIndex`
|
|
16
|
+
* (packages/mistri/src/server/app/searchProvider.ts), and nothing of
|
|
17
|
+
* Postgres's own shape leaves this file: a tenant's scope becomes an exact
|
|
18
|
+
* match on a column here, not in core.
|
|
19
|
+
*
|
|
20
|
+
* One table per collection, in the connection's search path (no schema
|
|
21
|
+
* option: a dedicated database, or a role whose search path names one, is
|
|
22
|
+
* the isolation, as it is for the connection's own database):
|
|
23
|
+
*
|
|
24
|
+
* id text, each declared field text, mistri_tenant text, one
|
|
25
|
+
* generated tsvector column per field, one GIN index per vector column,
|
|
26
|
+
* and one unique index on (id, mistri_tenant) — a record is keyed by its
|
|
27
|
+
* tenant and its id, so two tenants whose records share a primary key
|
|
28
|
+
* hold two documents rather than overwriting one. The vector is `to_tsvector('simple', coalesce(field, ''))`:
|
|
29
|
+
* the `simple` configuration on both the vector and the query, so no
|
|
30
|
+
* stemming and no stop words — the closest Postgres analogue to the
|
|
31
|
+
* SQLite pack's unicode61 tokens — and the server's
|
|
32
|
+
* `default_text_search_config` never changes what an index holds.
|
|
33
|
+
*
|
|
34
|
+
* A phrase is asked the way the SQLite pack asks it: the whole phrase
|
|
35
|
+
* beside each word, so a record holding the phrase ranks with the word
|
|
36
|
+
* hits rather than apart from them. The query is a tsquery built from the
|
|
37
|
+
* phrase's tokens (letters, digits and underscores, lowercased, each
|
|
38
|
+
* quoted, so a word like `or` is a word, not an operator) and passed as a
|
|
39
|
+
* parameter to `to_tsquery('simple', $1)`; every other value is a
|
|
40
|
+
* parameter too. The filter is an OR over the asked fields' vector
|
|
41
|
+
* columns, so each column's GIN index can serve its own column and the
|
|
42
|
+
* planner bitmap-ORs them; the rank is the asked fields' `ts_rank` values
|
|
43
|
+
* weighted by asked order (an earlier asked field more), ties falling to
|
|
44
|
+
* the key, so two runs over the same index answer in the same order. The
|
|
45
|
+
* weights live in the query, not in the vectors: a search that asks a
|
|
46
|
+
* subset of the declared fields ranks by that subset, and a hit in a field
|
|
47
|
+
* the search did not ask cannot lift a record — a combined vector over all
|
|
48
|
+
* declared fields would let it, which is why there is one vector column
|
|
49
|
+
* per field rather than one per table.
|
|
50
|
+
*
|
|
51
|
+
* Generated columns cannot change their expression by ALTER, so a field
|
|
52
|
+
* added to a declaration after the collection exists rebuilds the table
|
|
53
|
+
* the way the SQLite pack rebuilds an FTS5 table: the rows are copied
|
|
54
|
+
* into a new table with the wider shape, the old table is dropped, and
|
|
55
|
+
* the new one is renamed, inside one transaction. A field is never
|
|
56
|
+
* dropped — a declaration that stops naming one leaves its column, unread,
|
|
57
|
+
* rather than rewriting the index.
|
|
58
|
+
*
|
|
59
|
+
* The runtime passes a tenant App's tenant field inside
|
|
60
|
+
* `ensureCollection`'s field list (appSearchRuntime.ts), so both packs drop
|
|
61
|
+
* it from the incoming list, or it would be held twice, once as a searched
|
|
62
|
+
* field and once as the tenant column. Here `mistri_tenant` — and `id`, the
|
|
63
|
+
* document key — are stripped from the searchable set and always present as
|
|
64
|
+
* plain columns, never as vector columns. One divergence from the SQLite
|
|
65
|
+
* pack: a Postgres deployment is multi-process, so another process may have
|
|
66
|
+
* rebuilt the table since this one last looked. The field list is cached per
|
|
67
|
+
* process and per table, and re-read from the catalog once when a statement
|
|
68
|
+
* meets an undefined column or a search asks a field the cache lacks; a
|
|
69
|
+
* rebuild re-reads it under an advisory lock, so two processes growing the
|
|
70
|
+
* same table cannot both rebuild it.
|
|
71
|
+
*
|
|
72
|
+
* There is no migration history and no store layout for search indexes:
|
|
73
|
+
* provisioning is lazy, on `ensureCollection`, exactly as the SQLite
|
|
74
|
+
* pack's is. The runtime stores' layouts (storeLayouts.ts) are for
|
|
75
|
+
* runtime stores, not for a pack's index tables.
|
|
76
|
+
*
|
|
77
|
+
* Identifiers are never interpolated unchecked: a collection name and
|
|
78
|
+
* every field name must be word characters, and anything else is refused
|
|
79
|
+
* rather than quoted. Postgres's 63-byte identifier limit applies to the
|
|
80
|
+
* table and index names this file derives; a collection whose name, with
|
|
81
|
+
* the rebuild table's `__next`, would pass it is refused with that reason —
|
|
82
|
+
* on the first statement for it, in `collectionTable` — not truncated into a
|
|
83
|
+
* name that collides with another table or that nothing finds again.
|
|
84
|
+
*/
|
|
85
|
+
import { createHash } from 'node:crypto';
|
|
86
|
+
import { SearchUnavailable } from '@mistriwork/mistri/search';
|
|
87
|
+
/** The document field that holds a tenant-owned record's tenant (appSearchRuntime.ts); kept in every table, unindexed. */
|
|
88
|
+
const TENANT_FIELD = 'mistri_tenant';
|
|
89
|
+
/** The text-search configuration on every vector and every query: no stemming, no stop words. */
|
|
90
|
+
const TEXT_CONFIG = 'simple';
|
|
91
|
+
/** A name this file interpolates into SQL: word characters only, so no quoting is ever needed beyond the quotes themselves. */
|
|
92
|
+
const isIdentifier = (name) => /^[A-Za-z0-9_]+$/.test(name);
|
|
93
|
+
const identifier = (name, what) => {
|
|
94
|
+
if (!isIdentifier(name))
|
|
95
|
+
throw new Error(`${what} "${name}" is not a name of letters, digits and underscores.`);
|
|
96
|
+
return name;
|
|
97
|
+
};
|
|
98
|
+
/** Postgres truncates an identifier past 63 bytes, with only a NOTICE: the table would exist under a name no later statement uses. The rebuild table adds `__next`, so a collection that may ever grow is held to what leaves room for it. */
|
|
99
|
+
const MAX_COLLECTION_BYTES = 63 - '__next'.length;
|
|
100
|
+
/** A collection's table name, or a refusal that names the collection and says what to shorten: truncating it would index into a table nothing can find. */
|
|
101
|
+
const collectionTable = (name, prefix) => {
|
|
102
|
+
identifier(name, 'A search collection');
|
|
103
|
+
if (Buffer.byteLength(name) > MAX_COLLECTION_BYTES) {
|
|
104
|
+
throw new Error(`A search collection "${name}" is ${Buffer.byteLength(name)} bytes; Postgres allows 63 and the rebuild table needs 6 of them, so at most ${MAX_COLLECTION_BYTES}. ` +
|
|
105
|
+
`Shorten the App id or the resource name, or the collection prefix ("${prefix}").`);
|
|
106
|
+
}
|
|
107
|
+
return name;
|
|
108
|
+
};
|
|
109
|
+
/** A name inside Postgres's 63-byte identifier limit, with a hash of the full name when it would not fit. */
|
|
110
|
+
const bounded = (base) => base.length <= 63 ? base : `${base.slice(0, 54)}_${createHash('sha1').update(base).digest('hex').slice(0, 8)}`;
|
|
111
|
+
/** The vector column for a field: the field's name, so a search can ask one field without reading the others. */
|
|
112
|
+
const vectorColumn = (field) => `${field}__tsv`;
|
|
113
|
+
/** A GIN index's name, kept inside Postgres's 63-byte identifier limit with a hash of the full name when it would not fit. */
|
|
114
|
+
const indexName = (table, field) => bounded(`${table}_${field}__tsv_idx`);
|
|
115
|
+
/** The unique index that keys a document by its tenant and its id; an untenanted record keys on the empty tenant. */
|
|
116
|
+
const keyIndexSql = (table) => `CREATE UNIQUE INDEX IF NOT EXISTS "${bounded(`${table}__key_idx`)}" ON "${table}" ("id", (coalesce("${TENANT_FIELD}", '')))`;
|
|
117
|
+
/** The searchable fields of a declaration: word characters, without the reserved names, without repeats. */
|
|
118
|
+
const searchableFields = (fields) => {
|
|
119
|
+
const wanted = [];
|
|
120
|
+
for (const field of fields) {
|
|
121
|
+
const name = identifier(field, 'A searched field');
|
|
122
|
+
if (name === 'id' || name === TENANT_FIELD)
|
|
123
|
+
continue;
|
|
124
|
+
if (!wanted.includes(name))
|
|
125
|
+
wanted.push(name);
|
|
126
|
+
}
|
|
127
|
+
for (const field of wanted) {
|
|
128
|
+
if (wanted.includes(vectorColumn(field))) {
|
|
129
|
+
throw new Error(`A searched field "${field}" collides with the index's vector column for another field; rename the field.`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return wanted;
|
|
133
|
+
};
|
|
134
|
+
/** The tokens `to_tsquery` would read from a phrase: letters, digits and underscores, in order, lowercased. */
|
|
135
|
+
const tokensOf = (phrase) => (phrase.match(/[\p{L}\p{N}_]+/gu) ?? []).map((token) => token.toLowerCase());
|
|
136
|
+
/** One token as a tsquery lexeme: quoted, so a word like `or` is a word, not an operator. Tokens hold no quotes by construction. */
|
|
137
|
+
const lexeme = (token) => `'${token}'`;
|
|
138
|
+
/**
|
|
139
|
+
* The tsquery for `phrase` across the asked fields: for a multi-word
|
|
140
|
+
* phrase, the whole phrase beside each word, so a phrase hit and a word
|
|
141
|
+
* hit are both asked. Empty when the phrase holds no token.
|
|
142
|
+
*/
|
|
143
|
+
const tsqueryOf = (phrase) => {
|
|
144
|
+
const tokens = tokensOf(phrase);
|
|
145
|
+
if (!tokens.length)
|
|
146
|
+
return undefined;
|
|
147
|
+
const parts = tokens.map(lexeme);
|
|
148
|
+
if (tokens.length > 1)
|
|
149
|
+
parts.unshift(tokens.map(lexeme).join(' <-> '));
|
|
150
|
+
return parts.join(' | ');
|
|
151
|
+
};
|
|
152
|
+
/** The `CREATE TABLE` for a collection: the key, each field as text, the tenant as text, one generated vector per field. */
|
|
153
|
+
const createTableSql = (table, fields, ifNotExists) => {
|
|
154
|
+
const parts = [
|
|
155
|
+
'"id" text NOT NULL',
|
|
156
|
+
...fields.map((field) => `"${field}" text`),
|
|
157
|
+
`"${TENANT_FIELD}" text`,
|
|
158
|
+
...fields.map((field) => `"${vectorColumn(field)}" tsvector GENERATED ALWAYS AS (to_tsvector('${TEXT_CONFIG}', coalesce("${field}", ''))) STORED`),
|
|
159
|
+
];
|
|
160
|
+
return `CREATE TABLE ${ifNotExists ? 'IF NOT EXISTS ' : ''}"${table}" (${parts.join(', ')})`;
|
|
161
|
+
};
|
|
162
|
+
const quoted = (columns) => columns.map((column) => `"${column}"`).join(', ');
|
|
163
|
+
/** The `pg` pool, loaded the way the engine loads it: a missing package is a sentence, not a crash on import. */
|
|
164
|
+
async function openPool(connectionString) {
|
|
165
|
+
const specifier = 'pg';
|
|
166
|
+
const pg = (await import(specifier).catch(() => {
|
|
167
|
+
throw new Error('Postgres search needs the "pg" package. Install it with: npm install pg');
|
|
168
|
+
}));
|
|
169
|
+
const Pool = pg.Pool ?? pg.default?.Pool;
|
|
170
|
+
if (!Pool)
|
|
171
|
+
throw new Error('Could not find a Pool export in the "pg" package.');
|
|
172
|
+
const pool = new Pool({ connectionString });
|
|
173
|
+
/* pg removes a failed idle client itself; an unhandled pool error would crash Node, as the engine's pool
|
|
174
|
+
(adapters/postgresPool.ts) is told. This pool sits outside the engine's admission — its own connections,
|
|
175
|
+
not the connection's capped writer pool — so a search is neither queued nor counted there. */
|
|
176
|
+
pool.on('error', () => { });
|
|
177
|
+
return pool;
|
|
178
|
+
}
|
|
179
|
+
/** One collection's table, in one database. */
|
|
180
|
+
export class PostgresTsvectorIndex {
|
|
181
|
+
connectionString;
|
|
182
|
+
collectionPrefix;
|
|
183
|
+
pool;
|
|
184
|
+
/** The searchable fields each table held when last read; see `readFields` for when it is read again. */
|
|
185
|
+
fields = new Map();
|
|
186
|
+
constructor(connectionString, collectionPrefix) {
|
|
187
|
+
this.connectionString = connectionString;
|
|
188
|
+
this.collectionPrefix = collectionPrefix;
|
|
189
|
+
}
|
|
190
|
+
/** The pool, opened on first use, never at plug-in, so a deployment that declares the connection but serves no searched App never connects. */
|
|
191
|
+
async db() {
|
|
192
|
+
if (!this.pool)
|
|
193
|
+
this.pool = await openPool(this.connectionString);
|
|
194
|
+
return this.pool;
|
|
195
|
+
}
|
|
196
|
+
/** Ends the pool; the next call reopens it. For tests and shutdown — the index itself is tables in Postgres and survives. */
|
|
197
|
+
async close() {
|
|
198
|
+
const pool = this.pool;
|
|
199
|
+
this.pool = undefined;
|
|
200
|
+
this.fields.clear();
|
|
201
|
+
if (pool)
|
|
202
|
+
await pool.end();
|
|
203
|
+
}
|
|
204
|
+
/** The collection exists and holds every field named; a field added later rebuilds the table to hold it. */
|
|
205
|
+
async ensureCollection(name, fields) {
|
|
206
|
+
const table = collectionTable(name, this.collectionPrefix);
|
|
207
|
+
const wanted = searchableFields(fields);
|
|
208
|
+
const pool = await this.db();
|
|
209
|
+
let held = await this.readFields(table);
|
|
210
|
+
if (!held) {
|
|
211
|
+
await pool.query(createTableSql(table, wanted, true));
|
|
212
|
+
await pool.query(keyIndexSql(table));
|
|
213
|
+
for (const field of wanted) {
|
|
214
|
+
await pool.query(`CREATE INDEX IF NOT EXISTS "${indexName(table, field)}" ON "${table}" USING gin ("${vectorColumn(field)}")`);
|
|
215
|
+
}
|
|
216
|
+
held = await this.readFields(table, true);
|
|
217
|
+
if (!held)
|
|
218
|
+
throw new Error(`A search collection "${table}" could not be created.`);
|
|
219
|
+
}
|
|
220
|
+
if (wanted.every((field) => held.includes(field)))
|
|
221
|
+
return;
|
|
222
|
+
const temp = `${table}__next`;
|
|
223
|
+
/* The whole rebuild on one client: BEGIN, the DDL and COMMIT through the pool would land on different
|
|
224
|
+
connections. The advisory lock, keyed by the table, makes a second process wait here and then find the
|
|
225
|
+
table already wide enough, so two processes never rebuild it at once. */
|
|
226
|
+
const client = await pool.connect();
|
|
227
|
+
let failed = false;
|
|
228
|
+
try {
|
|
229
|
+
await client.query('BEGIN');
|
|
230
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [table]);
|
|
231
|
+
const current = (await this.catalogFields(client, table)) ?? held;
|
|
232
|
+
const missing = wanted.filter((field) => !current.includes(field));
|
|
233
|
+
const next = [...current, ...missing];
|
|
234
|
+
if (missing.length) {
|
|
235
|
+
await client.query(`DROP TABLE IF EXISTS "${temp}"`);
|
|
236
|
+
await client.query(createTableSql(temp, next, false));
|
|
237
|
+
const columns = ['id', ...current, TENANT_FIELD];
|
|
238
|
+
await client.query(`INSERT INTO "${temp}"(${quoted(columns)}) SELECT ${quoted(columns)} FROM "${table}"`);
|
|
239
|
+
await client.query(`DROP TABLE "${table}"`);
|
|
240
|
+
await client.query(`ALTER TABLE "${temp}" RENAME TO "${table}"`);
|
|
241
|
+
await client.query(keyIndexSql(table));
|
|
242
|
+
for (const field of next) {
|
|
243
|
+
await client.query(`CREATE INDEX IF NOT EXISTS "${indexName(table, field)}" ON "${table}" USING gin ("${vectorColumn(field)}")`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
await client.query('COMMIT');
|
|
247
|
+
this.fields.set(table, next);
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
failed = true;
|
|
251
|
+
try {
|
|
252
|
+
await client.query('ROLLBACK');
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
/* The rollback itself failed; the error below is the one that matters. */
|
|
256
|
+
}
|
|
257
|
+
throw error;
|
|
258
|
+
}
|
|
259
|
+
finally {
|
|
260
|
+
// A client that failed mid-transaction is destroyed, not returned to the pool in an unknown state.
|
|
261
|
+
client.release(failed);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** 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. */
|
|
265
|
+
async upsert(collection, document) {
|
|
266
|
+
const table = collectionTable(collection, this.collectionPrefix);
|
|
267
|
+
const fields = Object.keys(document).filter((key) => key !== 'id' && key !== TENANT_FIELD);
|
|
268
|
+
await this.ensureCollection(table, fields);
|
|
269
|
+
const pool = await this.db();
|
|
270
|
+
await this.afresh(async (fresh) => {
|
|
271
|
+
const held = (await this.readFields(table, fresh)) ?? [];
|
|
272
|
+
const columns = ['id', ...held, TENANT_FIELD];
|
|
273
|
+
const values = columns.map((column) => (column === 'id' ? document.id : (document[column] ?? null)));
|
|
274
|
+
const placeholders = values.map((_, at) => `$${at + 1}`);
|
|
275
|
+
const sets = columns
|
|
276
|
+
.filter((column) => column !== 'id')
|
|
277
|
+
.map((column) => `"${column}" = EXCLUDED."${column}"`)
|
|
278
|
+
.join(', ');
|
|
279
|
+
await pool.query(`INSERT INTO "${table}"(${quoted(columns)}) VALUES (${placeholders.join(', ')}) ON CONFLICT ("id", (coalesce("${TENANT_FIELD}", ''))) DO UPDATE SET ${sets}`, values);
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Gone from the index; a document that was never there is gone already, and a collection never ensured holds
|
|
284
|
+
* nothing — as does a name the index cannot hold. With a tenant scope only that tenant's document goes; without
|
|
285
|
+
* one, every tenant's document under that key does; core names the tenant of a tenant-owned row's removal (appSearchRuntime.ts).
|
|
286
|
+
*/
|
|
287
|
+
async remove(collection, id, scope) {
|
|
288
|
+
if (!isIdentifier(collection) || Buffer.byteLength(collection) > MAX_COLLECTION_BYTES)
|
|
289
|
+
return;
|
|
290
|
+
if (!(await this.readFields(collection)))
|
|
291
|
+
return;
|
|
292
|
+
const pool = await this.db();
|
|
293
|
+
if (scope?.field === TENANT_FIELD)
|
|
294
|
+
await pool.query(`DELETE FROM "${collection}" WHERE "id" = $1 AND "${TENANT_FIELD}" = $2`, [id, scope.value]);
|
|
295
|
+
else
|
|
296
|
+
await pool.query(`DELETE FROM "${collection}" WHERE "id" = $1`, [id]);
|
|
297
|
+
}
|
|
298
|
+
/** 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. */
|
|
299
|
+
async search(collection, phrase, fields, limit, scope) {
|
|
300
|
+
if (limit <= 0 || !isIdentifier(collection))
|
|
301
|
+
return [];
|
|
302
|
+
try {
|
|
303
|
+
const table = collectionTable(collection, this.collectionPrefix);
|
|
304
|
+
return await this.afresh((fresh) => this.ask(table, phrase, fields, limit, scope, fresh));
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
throw new SearchUnavailable(`search "${collection}" could not be asked: ${error.message}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
async ask(table, phrase, fields, limit, scope, fresh) {
|
|
311
|
+
let held = await this.readFields(table, fresh);
|
|
312
|
+
if (!held)
|
|
313
|
+
return [];
|
|
314
|
+
/* Another process may have widened the table since this one read it: a field asked and not held is
|
|
315
|
+
looked for in the catalog once before it is left out. */
|
|
316
|
+
if (!fresh && fields.some((field) => isIdentifier(field) && !held.includes(field)))
|
|
317
|
+
held = (await this.readFields(table, true)) ?? held;
|
|
318
|
+
const asked = fields.filter((field) => isIdentifier(field) && held.includes(field));
|
|
319
|
+
if (!asked.length)
|
|
320
|
+
return [];
|
|
321
|
+
const query = tsqueryOf(phrase);
|
|
322
|
+
if (!query)
|
|
323
|
+
return [];
|
|
324
|
+
const params = [query];
|
|
325
|
+
let where = `(${asked.map((field) => `"${vectorColumn(field)}" @@ to_tsquery('${TEXT_CONFIG}', $1)`).join(' OR ')})`;
|
|
326
|
+
if (scope) {
|
|
327
|
+
if (!isIdentifier(scope.field))
|
|
328
|
+
return [];
|
|
329
|
+
if (scope.field !== TENANT_FIELD && !held.includes(scope.field))
|
|
330
|
+
return [];
|
|
331
|
+
params.push(scope.value);
|
|
332
|
+
where += ` AND "${scope.field}" = $${params.length}`;
|
|
333
|
+
}
|
|
334
|
+
/* Asked-order weights, as the SQLite pack's are: an earlier asked
|
|
335
|
+
field weighs more, and a field the search did not ask weighs
|
|
336
|
+
nothing, so it cannot lift a match. */
|
|
337
|
+
const rank = asked
|
|
338
|
+
.map((field, at) => `${asked.length - at} * ts_rank("${vectorColumn(field)}", to_tsquery('${TEXT_CONFIG}', $1))`)
|
|
339
|
+
.join(' + ');
|
|
340
|
+
params.push(Math.floor(limit));
|
|
341
|
+
const pool = await this.db();
|
|
342
|
+
const { rows } = await pool.query(`SELECT "id" FROM "${table}" WHERE ${where} ORDER BY (${rank}) DESC, "id" ASC LIMIT $${params.length}`, params);
|
|
343
|
+
return rows.map((row) => String(row.id));
|
|
344
|
+
}
|
|
345
|
+
/** Runs `run`; a statement that meets an undefined column ran against a stale field list, so it runs once more on a fresh one. */
|
|
346
|
+
async afresh(run) {
|
|
347
|
+
try {
|
|
348
|
+
return await run(false);
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
if (error.code !== '42703')
|
|
352
|
+
throw error;
|
|
353
|
+
return run(true);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/** The searchable fields a table holds: the process's cache, or the catalog when `fresh` or not yet read; undefined when the table is not there (never cached, so a table another process creates is seen). */
|
|
357
|
+
async readFields(table, fresh = false) {
|
|
358
|
+
const cached = this.fields.get(table);
|
|
359
|
+
if (cached && !fresh)
|
|
360
|
+
return cached;
|
|
361
|
+
const found = await this.catalogFields(await this.db(), table);
|
|
362
|
+
if (found)
|
|
363
|
+
this.fields.set(table, found);
|
|
364
|
+
else
|
|
365
|
+
this.fields.delete(table);
|
|
366
|
+
return found;
|
|
367
|
+
}
|
|
368
|
+
/** The searchable fields a table holds, from the catalog. Text columns only, so a vector column never reads as a field. */
|
|
369
|
+
async catalogFields(db, table) {
|
|
370
|
+
const { rows } = await db.query(`SELECT a.attname AS name, format_type(a.atttypid, NULL) AS type FROM pg_attribute a ` +
|
|
371
|
+
`JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace ` +
|
|
372
|
+
`WHERE c.relname = $1 AND n.nspname = current_schema() AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum`, [table]);
|
|
373
|
+
if (!rows.length)
|
|
374
|
+
return undefined;
|
|
375
|
+
return rows.filter((row) => row.type === 'text' && row.name !== 'id' && row.name !== TENANT_FIELD).map((row) => String(row.name));
|
|
376
|
+
}
|
|
377
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mistriwork/search-postgres",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "PostgreSQL tsvector + GIN search provider pack for mistri Apps, living beside your deployment's PostgreSQL database.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mistri",
|
|
7
|
+
"search",
|
|
8
|
+
"postgres",
|
|
9
|
+
"postgresql",
|
|
10
|
+
"tsvector",
|
|
11
|
+
"full-text-search"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://mistriwork.dev",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/rbaljinder/mistri/issues"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"author": "Baljinder Randhawa",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/rbaljinder/mistri.git",
|
|
22
|
+
"directory": "packages/search-postgres"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"type": "module",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"@mistriwork/mistri": "1.2.0",
|
|
38
|
+
"pg": "^8.0.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependenciesMeta": {
|
|
41
|
+
"pg": {
|
|
42
|
+
"optional": true
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=24"
|
|
47
|
+
}
|
|
48
|
+
}
|