@cslug/search 0.0.0-stage → 0.6.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/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @cslug/search
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Full-text search over any table, on PostgreSQL (no search server): `searchable()` declares a weighted, multilingual,
4
+ accent-insensitive search column that PostgreSQL keeps up to date, and `search()` runs ranked queries with highlights
5
+ and typo tolerance that compose with the query builder. List `SearchProvider` in `bootstrap/providers.ts`
6
+ (`cslug add search`), then `cslug migrate`.
7
+
8
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
9
+ [guide 22](../../guides/22-search.md).
package/docs/README.md ADDED
@@ -0,0 +1,123 @@
1
+ # @cslug/search
2
+
3
+ `cslug add search` installs the package and lists `SearchProvider`; `cslug migrate` then runs its migration before
4
+ the app's: the `unaccent` and `pg_trgm` extensions (both trusted: the database owner can create them) and a copy of
5
+ every built-in text search configuration that ignores accents, `cslug_<name>` (`cslug_french`, `cslug_english`,
6
+ `cslug_simple`…: `unaccent`, then the language's dictionary).
7
+
8
+ ## A search column
9
+
10
+ ```ts
11
+ export const circuits = table('circuits', {
12
+ id: id(),
13
+ title: text(),
14
+ summary: text().nullable(),
15
+ body: text(),
16
+ search: searchable({ title: 'A', summary: 'B', body: 'C' }, { language: 'french' }),
17
+ }, { indexes: (t) => [t.using('gin', 'search'), t.using('gin', ['title', 'gin_trgm_ops'])] })
18
+ ```
19
+
20
+ `searchable(weights, { language, unaccent })` is a hidden generated `tsvector` column (`@cslug/database`'s
21
+ `generatedAs` + `hidden`): PostgreSQL computes it on every insert and update, rows never carry it, and
22
+ `cslug make:migration --from-tables` creates it (and follows weight or language changes). Weights are `A` (most) to
23
+ `D`. Index it with `t.using('gin', 'search')`.
24
+
25
+ - `language: 'french'`: a fixed text search configuration (default `simple`: no stemming).
26
+ - `language: { column: 'locale', configs: { fr: 'french', en: 'english', it: 'italian' }, fallback: 'simple' }`: each
27
+ row is stemmed in its own language (a `case` on the column; values without a configuration use the fallback).
28
+ - `unaccent: false`: use the configurations as they are (accents matter).
29
+
30
+ ## Searching
31
+
32
+ ```ts
33
+ const page = await search(this.circuits, 'isalo 4x4', { highlight: ['summary'], typos: ['title'] })
34
+ .where({ published: true })
35
+ .paginate(1, 20)
36
+ // page.data: (Row & { rank: number; highlight: { summary: string } })[]
37
+ ```
38
+
39
+ `search(repoOrQuery, term, options)` returns the query with the rows that match, best first:
40
+
41
+ - **Syntax** (`websearch_to_tsquery`): words (all must match), `"an exact phrase"`, `-without`, `or`. A term without
42
+ any word filters nothing (every row, `rank` 0).
43
+ - **Rank**: `ts_rank_cd(vector, query, 32)`, between 0 and 1, so title (A) matches come before body (C) ones. The
44
+ rank is the first sort term: `orderBy` added after `search()` breaks ties.
45
+ - **Languages**: the query is built for every language of the column at once (a row matches in its own);
46
+ `language: 'fr'` (a value) or `'french'` (a configuration) searches one.
47
+ - **Highlights**: `highlight: ['summary']` (or `{ columns, words = 30, fragments = 2 }`) adds `highlight.<column>`:
48
+ the text HTML-escaped, then the matching words in `<mark>…</mark>` (safe to render as HTML). Fragments start and end
49
+ at words that are not stop words; `fragments: 0` gives one window from the start of the text instead.
50
+ - **Typos**: `typos: ['title']` also matches rows whose column is similar to the term (`pg_trgm` word similarity, so
51
+ `isallo` finds `Isalo`); they rank lower (`+ 0.3 × similarity`). Each column needs `t.using('gin', [column,
52
+ 'gin_trgm_ops'])`.
53
+ - `column` picks the search column when a table has several.
54
+
55
+ Everything is a `whereSql`, `selectSql` and `orderBySql` on the query, so it composes with the rest of the query builder
56
+ (`where`, `paginate`, `first`, `cursor` on another key is not meaningful with a rank).
57
+
58
+ ## Indexes for documents that are not rows
59
+
60
+ ```ts
61
+ // app/search/help-search-index.ts
62
+ export const helpIndex = searchIndex<{ url: string; kind: 'faq' | 'guide' }>('help', {
63
+ languages: ['french', 'english'], // the first is the default
64
+ documents: async function* () { // what `cslug search:reindex help` refills it with
65
+ for (const page of await resolve(HelpPageRepository).all())
66
+ yield { key: page.slug, title: page.title, body: page.text, language: page.locale === 'en' ? 'english' : 'french',
67
+ metadata: { url: `/help/${page.slug}`, kind: page.kind } }
68
+ },
69
+ })
70
+
71
+ await helpIndex.upsert({ key: 'visa', title: 'Visa à l’arrivée', body, metadata: { url: '/help/visa', kind: 'faq' } })
72
+ const { data, meta } = await helpIndex.search('visa', { filter: { kind: 'faq' }, highlight: true, page: 1 })
73
+ // data: { key, title, metadata, rank, highlight?: { title, body } }[]
74
+ ```
75
+
76
+ Documents live in `cslug_search_documents` (one row per index and key: title, body, metadata, its text search
77
+ configuration, and a vector generated from the title (A) and the body (B) in that language). A document's
78
+ `language` must be one of the index's `languages`; the query covers them all unless `language` narrows it.
79
+
80
+ - `upsert(doc)` / `upsertMany(docs)` add or replace by key (one statement); `remove(...keys)`,
81
+ `removeWhere(metadataFilter)`, `clear()`, `count()`.
82
+ - `search(term, { page = 1, perPage = 20, filter, language, highlight, typos })` → `{ data, meta }` like
83
+ `paginate()`: ranked as `search()` ranks rows, `filter` matches metadata (`metadata @> filter`), `highlight`
84
+ (`true` or `{ words, fragments }`) marks the title and body (HTML-escaped first), `typos` also matches similar
85
+ titles.
86
+ - `reindex()` (and `cslug search:reindex [name]`, which imports `app/search/`): upserts everything `documents()`
87
+ yields, in batches of 500, then removes the documents it did not yield. Without a name, every index that has a
88
+ source. Indexes are defined once per name (`searchIndex()` throws on a second definition).
89
+
90
+ Table search never needs a reindex: PostgreSQL computes `searchable()` columns on every write.
91
+
92
+ ## Semantic and hybrid search
93
+
94
+ ```ts
95
+ // config/search.ts
96
+ export default defineConfig({ vectors: true }) // registers the embeddings migration: pgvector, then cslug migrate
97
+
98
+ export const helpIndex = searchIndex('help', { languages: ['french', 'english'], semantic: true })
99
+ await helpIndex.search('louer une voiture') // hybrid (the default for a semantic index)
100
+ await helpIndex.search('louer une voiture', { mode: 'semantic', minSimilarity: 0.3 })
101
+ ```
102
+
103
+ - **Embeddings.** A `semantic` index embeds each document's title and body (the first `maxChars`, default 8000:
104
+ `semantic: { maxChars }`) on `upsert`, with the app's `Embedder`, into `cslug_search_embeddings` (one vector per
105
+ document, deleted with it). A document is embedded again only when its text or the embedder's `model` changed (a
106
+ hash is kept), so `search:reindex` costs nothing for unchanged documents. Vectors of another model are ignored
107
+ until the document is embedded again.
108
+ - **Modes.** `text` (full text, as before), `semantic` (nearest vectors by cosine distance; `rank` is the cosine
109
+ similarity, `minSimilarity` leaves out the rest; the query is embedded with `purpose: 'query'`), `hybrid`
110
+ (the best 100 of each, fused by reciprocal rank: `Σ 1 / (60 + position)`; a document found both ways comes first).
111
+ `filter`, `highlight` (on the words of the term) and pagination work in every mode.
112
+ - **The `Embedder`** is a contract: `model` and `embed(texts, purpose)`. `@cslug/ai` binds one from `config/ai.ts` →
113
+ `embeddings` (Voyage, OpenAI-compatible); tests and development can bind `FakeEmbedder` (`app.instance(Embedder, new
114
+ FakeEmbedder())`): words hashed into buckets, plus optional `concepts` to show matches by meaning.
115
+ - The search is exact (no approximate index): fine for thousands of documents. pgvector's `vector` extension may
116
+ need a superuser to install on some hosts.
117
+ - Table rows are searched by meaning through an index: upsert the rows' text into a semantic `searchIndex()` where
118
+ they change (or from its `documents()` source).
119
+
120
+ ## From agents
121
+
122
+ `@cslug/ai` has `searchTool(index)` (an agent searches an index) and `recallTool()` (a user's earlier
123
+ conversations, kept in an index with `ai.recall`).
package/docs/api.md ADDED
@@ -0,0 +1,18 @@
1
+ # @cslug/search: API
2
+
3
+ | | |
4
+ |---|---|
5
+ | `searchable(weights, options?)` | A hidden, generated `tsvector` column: `weights` `{ column: 'A' \| 'B' \| 'C' \| 'D' }`; `options.language` a configuration name or `{ column, configs, fallback? }`; `options.unaccent` (default true: `cslug_<config>`) |
6
+ | `search(source, term, options?)` | `source` a repository or a `Query`; → `Query<T, R & { rank: number } & { highlight?: Record<K, string> }>`. Options: `column`, `language`, `highlight` (`K[]` or `{ columns, words?, fragments? }`), `typos` (`K[]`) |
7
+ | `searchColumnOf(table, key?)` | `{ key, config }` of the table's `searchable()` column; an error names what is missing or ambiguous |
8
+ | `searchIndex<M>(name, options?)` → `SearchIndex<M>` | A document index (defined once per name): `options.languages` (first = default), `unaccent`, `documents()` (a sync or async iterable of `SearchDocument<M>`), `semantic` (`true` or `{ maxChars }`) |
9
+ | `SearchIndex` | `upsert(doc)`, `upsertMany(docs)`, `remove(...keys)` → count, `removeWhere(filter)` → count, `clear()` → count, `count()`, `search(term, { page, perPage, filter, language, highlight, typos, mode, minSimilarity })` → `Page<SearchHit<M>>` (`mode`: `text` \| `semantic` \| `hybrid`), `reindex(batch?)` → `{ indexed, removed }` |
10
+ | `SearchDocument<M>` / `SearchHit<M>` | `{ key, title?, body?, metadata?, language? }` / `{ key, title, metadata, rank, highlight? }` |
11
+ | `searchIndexes()`, `discoverSearchIndexes(app)` | The indexes defined so far; import `app/search/` |
12
+ | `SearchReindexCommand` | `cslug search:reindex [index]` |
13
+ | `SearchProvider` | Registers the `cslug_search` migrations (and the embeddings one with `search.vectors: true`); contributes `search:reindex` |
14
+ | `Embedder` | Abstract: `model`, `embed(texts, 'document' \| 'query')` → `number[][]`; bind one for semantic indexes |
15
+ | `FakeEmbedder({ dimensions?, concepts? })` | Deterministic, for tests: hashed words (accents, plurals folded), `concepts` share a bucket; records `calls` |
16
+ | `VECTOR_MIGRATIONS` | `vector` extension + `cslug_search_embeddings` (index, key, model, hash, embedding) |
17
+ | `SEARCH_MIGRATIONS` | Its folder: `unaccent`, `pg_trgm`, `cslug_<config>` text search configurations (down drops the configurations, not the extensions); `cslug_search_documents` |
18
+ | `Weights`, `Language`, `SearchableOptions`, `SearchOptions`, `SearchConfig` | Types |
@@ -0,0 +1,35 @@
1
+ -- up
2
+ -- Accent-insensitive copies of the built-in text search configurations: cslug_french, cslug_english, cslug_simple…
3
+ -- (unaccent first, then the language's own dictionary), so to_tsvector and ts_headline ignore accents alike.
4
+ create extension if not exists unaccent;
5
+ create extension if not exists pg_trgm;
6
+ do $$
7
+ declare
8
+ c record;
9
+ dicts text;
10
+ begin
11
+ for c in select cfgname from pg_ts_config where cfgnamespace = 'pg_catalog'::regnamespace loop
12
+ if exists (select 1 from pg_ts_config where cfgname = 'cslug_' || c.cfgname) then
13
+ continue;
14
+ end if;
15
+ select string_agg(quote_ident(d.dictname), ', ' order by m.mapseqno) into dicts
16
+ from pg_ts_config_map m join pg_ts_dict d on d.oid = m.mapdict
17
+ where m.mapcfg = ('pg_catalog.' || quote_ident(c.cfgname))::regconfig
18
+ and m.maptokentype = (select tokid from ts_token_type('default') where alias = 'word');
19
+ execute format('create text search configuration %I (copy = pg_catalog.%I)', 'cslug_' || c.cfgname, c.cfgname);
20
+ execute format('alter text search configuration %I alter mapping for hword, hword_part, word with unaccent, %s',
21
+ 'cslug_' || c.cfgname, dicts);
22
+ end loop;
23
+ end
24
+ $$;
25
+
26
+ -- down
27
+ do $$
28
+ declare
29
+ c record;
30
+ begin
31
+ for c in select cfgname from pg_ts_config where cfgname like 'cslug\_%' loop
32
+ execute format('drop text search configuration %I', c.cfgname);
33
+ end loop;
34
+ end
35
+ $$;
@@ -0,0 +1,21 @@
1
+ -- up
2
+ -- Documents that are not table rows (pages, files, messages), one row per (index, key). `config` is the document's
3
+ -- text search configuration (a regconfig, so the generated vector stays immutable).
4
+ create table cslug_search_documents (
5
+ index text not null,
6
+ key text not null,
7
+ title text not null default '',
8
+ body text not null default '',
9
+ config regconfig not null default 'cslug_simple',
10
+ metadata jsonb not null default '{}',
11
+ vector tsvector generated always as (
12
+ setweight(to_tsvector(config, title), 'A') || setweight(to_tsvector(config, body), 'B')
13
+ ) stored,
14
+ updated_at timestamptz not null,
15
+ primary key (index, key)
16
+ );
17
+ create index cslug_search_documents_vector_idx on cslug_search_documents using gin (vector);
18
+ create index cslug_search_documents_title_trgm_idx on cslug_search_documents using gin (title gin_trgm_ops);
19
+
20
+ -- down
21
+ drop table cslug_search_documents;
@@ -0,0 +1,17 @@
1
+ -- up
2
+ -- Registered only with `search.vectors: true` (config/search.ts): needs the pgvector extension on the server.
3
+ create extension if not exists vector;
4
+ create table cslug_search_embeddings (
5
+ index text not null,
6
+ key text not null,
7
+ -- the embedder's model: vectors of another model are ignored, and re-embedded on the next upsert
8
+ model text not null,
9
+ -- a hash of the embedded text, so unchanged documents are not embedded again
10
+ hash text not null,
11
+ embedding vector not null,
12
+ primary key (index, key),
13
+ foreign key (index, key) references cslug_search_documents (index, key) on delete cascade
14
+ );
15
+
16
+ -- down
17
+ drop table cslug_search_embeddings;
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@cslug/search",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.0",
4
+ "description": "Full-text search over any table on PostgreSQL: weighted, multilingual, accent-insensitive, ranked.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cslugts/cslug.git",
10
+ "directory": "packages/search"
11
+ },
12
+ "homepage": "https://github.com/cslugts/cslug/tree/main/packages/search",
13
+ "keywords": [
14
+ "cslug",
15
+ "bun",
16
+ "framework",
17
+ "search",
18
+ "postgres"
19
+ ],
20
+ "exports": {
21
+ ".": "./src/index.ts"
22
+ },
23
+ "files": [
24
+ "src",
25
+ "migrations",
26
+ "migrations-vectors",
27
+ "docs",
28
+ "README.md"
29
+ ],
30
+ "engines": {
31
+ "bun": ">=1.3.14"
32
+ },
33
+ "peerDependencies": {
34
+ "@cslug/core": "0.6.0",
35
+ "@cslug/database": "0.6.0"
36
+ },
37
+ "devDependencies": {
38
+ "@cslug/testing": "workspace:*"
39
+ }
40
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Turns text into vectors for semantic search. `@cslug/ai` binds one from `config/ai.ts` → `embeddings`; tests can
3
+ * bind a `FakeEmbedder`. `model` identifies the vectors: when it changes, documents are embedded again.
4
+ */
5
+ export abstract class Embedder {
6
+ abstract readonly model: string
7
+ /** One vector per text, in order. `purpose` lets models that tell queries from documents (Voyage) do so. */
8
+ abstract embed(texts: string[], purpose: 'document' | 'query'): Promise<number[][]>
9
+ }
10
+
11
+ const fold = (word: string) =>
12
+ word
13
+ .normalize('NFD')
14
+ .replace(/\p{Diacritic}/gu, '')
15
+ .toLowerCase()
16
+ .replace(/(ing|es|s)$/, '')
17
+
18
+ /**
19
+ * A deterministic embedder for tests and development: words (lowercased, accents and a plural or -ing removed) are
20
+ * hashed into `dimensions` buckets, so texts that share words are close. `concepts` maps words to a shared concept,
21
+ * so a test can show matches by meaning (`{ car: 'vehicle', '4x4': 'vehicle' }`).
22
+ */
23
+ export class FakeEmbedder extends Embedder {
24
+ readonly model: string
25
+ readonly calls: { texts: string[]; purpose: 'document' | 'query' }[] = []
26
+
27
+ constructor(private readonly options: { dimensions?: number; concepts?: Record<string, string> } = {}) {
28
+ super()
29
+ this.model = `fake-${options.dimensions ?? 64}`
30
+ }
31
+
32
+ async embed(texts: string[], purpose: 'document' | 'query'): Promise<number[][]> {
33
+ this.calls.push({ texts, purpose })
34
+ const size = this.options.dimensions ?? 64
35
+ return texts.map((text) => {
36
+ const vector = new Array<number>(size).fill(0)
37
+ for (const raw of text.split(/[^\p{L}\p{N}]+/u).filter(Boolean)) {
38
+ const word = fold(raw)
39
+ const token = this.options.concepts?.[word] ?? word
40
+ const bucket = Number(BigInt(Bun.hash(token)) % BigInt(size))
41
+ vector[bucket] = (vector[bucket] ?? 0) + 1
42
+ }
43
+ const norm = Math.hypot(...vector) || 1
44
+ return vector.map((x) => x / norm)
45
+ })
46
+ }
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @cslug/search: full-text search over any table on PostgreSQL. `searchable()` declares a weighted, multilingual,
3
+ * accent-insensitive search column (generated by PostgreSQL); `search()` runs ranked queries with highlights and typo
4
+ * tolerance, composable with the query builder.
5
+ */
6
+ export { Embedder, FakeEmbedder } from './embedder'
7
+ export { SearchProvider, SearchReindexCommand } from './provider'
8
+ export { type SearchOptions, search } from './search'
9
+ export {
10
+ discoverSearchIndexes,
11
+ type IndexSearchOptions,
12
+ type SearchDocument,
13
+ type SearchHit,
14
+ SearchIndex,
15
+ type SearchIndexOptions,
16
+ searchIndex,
17
+ searchIndexes,
18
+ } from './search-index'
19
+ export {
20
+ type Language,
21
+ SEARCH_MIGRATIONS,
22
+ type SearchableOptions,
23
+ type SearchConfig,
24
+ searchable,
25
+ searchColumnOf,
26
+ VECTOR_MIGRATIONS,
27
+ type Weights,
28
+ } from './searchable'
@@ -0,0 +1,47 @@
1
+ import { arg, Command, ServiceProvider } from '@cslug/core'
2
+ import { addMigrations } from '@cslug/database'
3
+ import { discoverSearchIndexes, searchIndexes } from './search-index'
4
+ import { SEARCH_MIGRATIONS, VECTOR_MIGRATIONS } from './searchable'
5
+
6
+ /**
7
+ * `cslug search:reindex [index]`: refill the indexes defined in `app/search/` from their `documents()` source (all of
8
+ * them, or one). Table search needs no reindex: PostgreSQL keeps `searchable()` columns up to date.
9
+ */
10
+ export class SearchReindexCommand extends Command {
11
+ static signature = 'search:reindex'
12
+ static description = 'Refill search indexes (app/search/) from their documents() source'
13
+ static args = { index: arg.string().optional().describe('One index by name; default: every index with a source') }
14
+
15
+ async handle({ index }: Command.Args<typeof SearchReindexCommand>) {
16
+ await discoverSearchIndexes(this.app)
17
+ const all = searchIndexes()
18
+ const chosen = index ? all.filter((i) => i.name === index) : all.filter((i) => i.options.documents)
19
+ if (index && !chosen.length) {
20
+ this.error(`No index "${index}" in app/search/ (indexes: ${all.map((i) => i.name).join(', ') || 'none'})`)
21
+ return 1
22
+ }
23
+ if (!chosen.length) {
24
+ this.info('No index with a documents() source in app/search/')
25
+ return 0
26
+ }
27
+ for (const i of chosen) {
28
+ const { indexed, removed } = await i.reindex()
29
+ this.success(`${i.name}: ${indexed} indexed, ${removed} removed`)
30
+ }
31
+ return 0
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Registers the `cslug_search` migrations (`cslug migrate` runs them before the app's own): the `unaccent` and
37
+ * `pg_trgm` extensions, the accent-insensitive `cslug_<config>` text search configurations, and
38
+ * `cslug_search_documents` for `searchIndex()`; with `search.vectors: true` (config/search.ts), pgvector and
39
+ * `cslug_search_embeddings` for semantic indexes. Contributes `search:reindex`.
40
+ */
41
+ export class SearchProvider extends ServiceProvider {
42
+ register() {
43
+ addMigrations(SEARCH_MIGRATIONS)
44
+ if (this.app.config<boolean | undefined>('search.vectors')) addMigrations(VECTOR_MIGRATIONS)
45
+ this.commands([SearchReindexCommand])
46
+ }
47
+ }
@@ -0,0 +1,338 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { type Application, Clock, CslugError, currentApp, resolve } from '@cslug/core'
4
+ import { Database, type Page, sql } from '@cslug/database'
5
+ import { Embedder } from './embedder'
6
+
7
+ /** A document of an index: its `key` is unique in the index. */
8
+ export type SearchDocument<M extends Record<string, unknown> = Record<string, unknown>> = {
9
+ key: string
10
+ title?: string
11
+ body?: string
12
+ metadata?: M
13
+ /** One of the index's languages (default: its first). */
14
+ language?: string
15
+ }
16
+
17
+ /** A search result: the document without its body, its rank and, when asked, highlights. */
18
+ export type SearchHit<M extends Record<string, unknown> = Record<string, unknown>> = {
19
+ key: string
20
+ title: string
21
+ metadata: M
22
+ rank: number
23
+ highlight?: { title: string; body: string }
24
+ }
25
+
26
+ export type SearchIndexOptions<M extends Record<string, unknown>> = {
27
+ /** Text search configurations documents may use (`french`, `english`…); the first is the default. Default `simple`. */
28
+ languages?: string[]
29
+ /** Ignore accents (`cslug_<config>`), default true. */
30
+ unaccent?: boolean
31
+ /** Every document of the index, for `cslug search:reindex`: the index then holds exactly these. */
32
+ documents?: () => AsyncIterable<SearchDocument<M>> | Iterable<SearchDocument<M>>
33
+ /**
34
+ * Also search by meaning: each document's title and body (the first `maxChars`, default 8000) are embedded on
35
+ * upsert with the bound `Embedder` (needs `search.vectors: true` and pgvector). Unchanged texts are not embedded
36
+ * again. Searches are then hybrid by default.
37
+ */
38
+ semantic?: boolean | { maxChars?: number }
39
+ }
40
+
41
+ export type IndexSearchOptions<M extends Record<string, unknown>> = {
42
+ page?: number
43
+ perPage?: number
44
+ /** Only documents whose metadata contains these values (`metadata @> filter`). */
45
+ filter?: Partial<M>
46
+ /** One language of the index instead of all of them. */
47
+ language?: string
48
+ /** `<mark>` highlights of the title and body (HTML-escaped first). */
49
+ highlight?: boolean | { words?: number; fragments?: number }
50
+ /** Also match titles similar to the term (pg_trgm), ranked lower (text and hybrid modes). */
51
+ typos?: boolean
52
+ /**
53
+ * `text`: words (full text). `semantic`: meaning (nearest embeddings; rank = cosine similarity). `hybrid`: both,
54
+ * merged by reciprocal rank fusion. Default: `hybrid` for a `semantic` index, else `text`.
55
+ */
56
+ mode?: 'text' | 'semantic' | 'hybrid'
57
+ /** Semantic and hybrid: leave out documents less similar than this (0–1, default 0). */
58
+ minSimilarity?: number
59
+ }
60
+
61
+ const TABLE = sql`cslug_search_documents`
62
+ const EMBEDDINGS = sql`cslug_search_embeddings`
63
+ /** How many results of each ranking a hybrid search fuses, and the reciprocal-rank-fusion constant. */
64
+ const FUSE = { depth: 100, k: 60 }
65
+ const vectorLiteral = (v: number[]) => `[${v.join(',')}]`
66
+ const NAME = /^[a-z_]+$/
67
+ const quoted = (s: string) => sql.raw(`'${s.replace(/'/g, "''")}'`)
68
+ const escapeHtml = (text: unknown) =>
69
+ sql`replace(replace(replace(replace(${text}, '&', '&amp;'), '<', '&lt;'), '>', '&gt;'), '"', '&quot;')`
70
+
71
+ const registry = new Map<string, SearchIndex<Record<string, unknown>>>()
72
+
73
+ /**
74
+ * Documents that are not table rows (help pages, files, transcripts), searched like `search()` searches tables. Rows
75
+ * live in `cslug_search_documents`; the vector is generated from the title (weight A) and the body (B) in the
76
+ * document's language.
77
+ */
78
+ export class SearchIndex<M extends Record<string, unknown> = Record<string, unknown>> {
79
+ readonly configs: string[]
80
+
81
+ constructor(
82
+ readonly name: string,
83
+ readonly options: SearchIndexOptions<M> = {},
84
+ ) {
85
+ const languages = options.languages ?? ['simple']
86
+ if (!languages.length) throw new Error(`searchIndex('${name}'): languages is empty`)
87
+ this.configs = languages.map((l) => {
88
+ if (!NAME.test(l)) throw new Error(`Not a text search configuration name: "${l}"`)
89
+ return options.unaccent === false ? l : `cslug_${l}`
90
+ })
91
+ }
92
+
93
+ private get db(): Database {
94
+ return resolve(Database)
95
+ }
96
+
97
+ private config(language: string | undefined): string {
98
+ if (language === undefined) return this.configs[0] as string
99
+ const found = this.configs.find((c) => c === language || c === `cslug_${language}`)
100
+ if (!found)
101
+ throw new CslugError(
102
+ 'search.unknown_language',
103
+ `"${language}" is not a language of index ${this.name} (${(this.options.languages ?? ['simple']).join(', ')})`,
104
+ )
105
+ return found
106
+ }
107
+
108
+ /** Add or replace documents (by key), in one statement. */
109
+ async upsertMany(documents: SearchDocument<M>[]): Promise<void> {
110
+ if (!documents.length) return
111
+ const now = resolve(Clock).now()
112
+ const rows = documents.map(
113
+ (d) =>
114
+ sql`(${this.name}, ${d.key}, ${d.title ?? ''}, ${d.body ?? ''}, ${quoted(this.config(d.language))}::regconfig,
115
+ ${sql.json(d.metadata ?? {})}, ${now})`,
116
+ )
117
+ await this.db.exec(sql`insert into ${TABLE} (index, key, title, body, config, metadata, updated_at)
118
+ values ${sql.join(rows)}
119
+ on conflict (index, key) do update set title = excluded.title, body = excluded.body, config = excluded.config,
120
+ metadata = excluded.metadata, updated_at = excluded.updated_at`)
121
+ if (this.options.semantic) await this.embed(documents)
122
+ }
123
+
124
+ private embedder(): Embedder {
125
+ if (!currentApp().has(Embedder))
126
+ throw new CslugError(
127
+ 'search.no_embedder',
128
+ `Index ${this.name} is semantic but no Embedder is bound: configure ai.embeddings (@cslug/ai) or bind one`,
129
+ )
130
+ return resolve(Embedder)
131
+ }
132
+
133
+ /** Queries on `cslug_search_embeddings`, with a hint when its migration is missing. */
134
+ private async vectors<T>(run: () => Promise<T>): Promise<T> {
135
+ try {
136
+ return await run()
137
+ } catch (error) {
138
+ if (String((error as Error)?.message).includes('cslug_search_embeddings'))
139
+ throw new CslugError(
140
+ 'search.no_vectors',
141
+ 'Semantic search needs the embeddings table: set `vectors: true` in config/search.ts and run cslug migrate (needs pgvector)',
142
+ )
143
+ throw error
144
+ }
145
+ }
146
+
147
+ /** Embed the documents whose text (or the embedder's model) changed since their last embedding. */
148
+ private async embed(documents: SearchDocument<M>[]): Promise<void> {
149
+ const embedder = this.embedder()
150
+ const max = (typeof this.options.semantic === 'object' && this.options.semantic.maxChars) || 8000
151
+ const texts = new Map(
152
+ documents.map((d) => [d.key, `${d.title ?? ''}\n\n${d.body ?? ''}`.slice(0, max).trim()] as const),
153
+ )
154
+ const hashOf = (text: string) => new Bun.CryptoHasher('sha1').update(text).digest('hex')
155
+ await this.vectors(async () => {
156
+ const known = await this.db.many<{ key: string; hash: string }>(
157
+ sql`select key, hash from ${EMBEDDINGS} where index = ${this.name} and model = ${embedder.model}
158
+ and key in (${sql.join([...texts.keys()])})`,
159
+ )
160
+ const done = new Map(known.map((k) => [k.key, k.hash]))
161
+ const changed = [...texts].filter(([key, text]) => done.get(key) !== hashOf(text))
162
+ for (let i = 0; i < changed.length; i += 64) {
163
+ const chunk = changed.slice(i, i + 64)
164
+ const vectors = await embedder.embed(
165
+ chunk.map(([, text]) => text),
166
+ 'document',
167
+ )
168
+ const rows = chunk.map(
169
+ ([key, text], n) =>
170
+ sql`(${this.name}, ${key}, ${embedder.model}, ${hashOf(text)}, ${vectorLiteral(vectors[n] as number[])}::vector)`,
171
+ )
172
+ await this.db.exec(sql`insert into ${EMBEDDINGS} (index, key, model, hash, embedding) values ${sql.join(rows)}
173
+ on conflict (index, key) do update set model = excluded.model, hash = excluded.hash,
174
+ embedding = excluded.embedding`)
175
+ }
176
+ })
177
+ }
178
+
179
+ upsert(document: SearchDocument<M>): Promise<void> {
180
+ return this.upsertMany([document])
181
+ }
182
+
183
+ /** Remove documents by key; returns how many were there. */
184
+ remove(...keys: string[]): Promise<number> {
185
+ if (!keys.length) return Promise.resolve(0)
186
+ return this.db.exec(sql`delete from ${TABLE} where index = ${this.name} and key in (${sql.join(keys)})`)
187
+ }
188
+
189
+ /** Remove the documents whose metadata contains `filter` (`metadata @> filter`); returns how many. */
190
+ removeWhere(filter: Partial<M>): Promise<number> {
191
+ return this.db.exec(sql`delete from ${TABLE} where index = ${this.name} and metadata @> ${sql.json(filter)}`)
192
+ }
193
+
194
+ /** Remove every document of the index. */
195
+ clear(): Promise<number> {
196
+ return this.db.exec(sql`delete from ${TABLE} where index = ${this.name}`)
197
+ }
198
+
199
+ async count(): Promise<number> {
200
+ return Number(await this.db.value(sql`select count(*)::int from ${TABLE} where index = ${this.name}`))
201
+ }
202
+
203
+ /** The best matches for `term` (web-search syntax in text mode), as a page. */
204
+ async search(term: string, options: IndexSearchOptions<M> = {}): Promise<Page<SearchHit<M>>> {
205
+ const { page = 1, perPage = 20, minSimilarity = 0 } = options
206
+ const blank = !/\w/.test(term)
207
+ const mode = blank ? 'text' : (options.mode ?? (this.options.semantic ? 'hybrid' : 'text'))
208
+ if (mode !== 'text' && !this.options.semantic)
209
+ throw new CslugError(
210
+ 'search.not_semantic',
211
+ `Index ${this.name} is not semantic: define it with { semantic: true }`,
212
+ )
213
+ const configs = options.language === undefined ? this.configs : [this.config(options.language)]
214
+ const tsquery = sql`(${sql.join(
215
+ configs.map((c) => sql`websearch_to_tsquery(${quoted(c)}::regconfig, ${term})`),
216
+ sql` || `,
217
+ )})`
218
+ const match = blank
219
+ ? sql`true`
220
+ : options.typos
221
+ ? sql`(d.vector @@ ${tsquery} or ${term} <% d.title)`
222
+ : sql`d.vector @@ ${tsquery}`
223
+ const textRank = options.typos
224
+ ? sql`(ts_rank_cd(d.vector, ${tsquery}, 32) + 0.3 * word_similarity(${term}, d.title))::float8`
225
+ : sql`ts_rank_cd(d.vector, ${tsquery}, 32)::float8`
226
+ const filter = options.filter ? sql` and d.metadata @> ${sql.json(options.filter)}` : sql.empty
227
+ const h = options.highlight
228
+ const { words = 30, fragments = 2 } = typeof h === 'object' ? h : {}
229
+ const settings = quoted(
230
+ `StartSel=<mark>, StopSel=</mark>, MaxWords=${words}, MinWords=${Math.max(1, Math.min(10, words - 1))}, ` +
231
+ `MaxFragments=${fragments}, FragmentDelimiter=" … "`,
232
+ )
233
+ const highlight = h
234
+ ? sql`, json_build_object('title', ts_headline(d.config, ${escapeHtml(sql`d.title`)}, ${tsquery}, ${settings}),
235
+ 'body', ts_headline(d.config, ${escapeHtml(sql`d.body`)}, ${tsquery}, ${settings})) as highlight`
236
+ : sql.empty
237
+ const p = Math.max(1, Math.floor(page))
238
+ const window = sql`limit ${perPage} offset ${(p - 1) * perPage}`
239
+ const pageOf = (data: SearchHit<M>[], total: number) => ({
240
+ data,
241
+ meta: { page: p, perPage, total, lastPage: Math.max(1, Math.ceil(total / perPage)) },
242
+ })
243
+
244
+ if (mode === 'text') {
245
+ const where = sql`where d.index = ${this.name} and ${match}${filter}`
246
+ const total = Number(await this.db.value(sql`select count(*)::int from ${TABLE} d ${where}`))
247
+ const data = await this.db.many<SearchHit<M>>(
248
+ sql`select d.key, d.title, d.metadata, ${textRank} as rank${highlight} from ${TABLE} d ${where}
249
+ order by rank desc, d.key ${window}`,
250
+ )
251
+ return pageOf(data, total)
252
+ }
253
+
254
+ const embedder = this.embedder()
255
+ const [vector] = await embedder.embed([term], 'query')
256
+ const v = sql`${vectorLiteral(vector as number[])}::vector`
257
+ const nearest = sql`${TABLE} d join ${EMBEDDINGS} e on e.index = d.index and e.key = d.key and e.model = ${embedder.model}
258
+ where d.index = ${this.name} and 1 - (e.embedding <=> ${v}) >= ${minSimilarity}${filter}`
259
+ return this.vectors(async () => {
260
+ if (mode === 'semantic') {
261
+ const total = Number(await this.db.value(sql`select count(*)::int from ${nearest}`))
262
+ const data = await this.db.many<SearchHit<M>>(
263
+ sql`select d.key, d.title, d.metadata, (1 - (e.embedding <=> ${v}))::float8 as rank${highlight}
264
+ from ${nearest} order by e.embedding <=> ${v}, d.key ${window}`,
265
+ )
266
+ return pageOf(data, total)
267
+ }
268
+ // hybrid: the best `depth` of each ranking, fused by reciprocal rank (Σ 1 / (k + position))
269
+ const fused = sql`with words as (
270
+ select d.key, row_number() over (order by ${textRank} desc, d.key) as position from ${TABLE} d
271
+ where d.index = ${this.name} and ${match}${filter} order by position limit ${FUSE.depth}
272
+ ), meaning as (
273
+ select d.key, row_number() over (order by e.embedding <=> ${v}, d.key) as position from ${nearest}
274
+ order by position limit ${FUSE.depth}
275
+ ), fused as (
276
+ select key, sum(1.0 / (${FUSE.k} + position))::float8 as score
277
+ from (select * from words union all select * from meaning) x group by key
278
+ )`
279
+ const total = Number(await this.db.value(sql`${fused} select count(*)::int from fused`))
280
+ const data = await this.db.many<SearchHit<M>>(
281
+ sql`${fused} select d.key, d.title, d.metadata, fused.score as rank${highlight}
282
+ from fused join ${TABLE} d on d.index = ${this.name} and d.key = fused.key
283
+ order by fused.score desc, d.key ${window}`,
284
+ )
285
+ return pageOf(data, total)
286
+ })
287
+ }
288
+
289
+ /**
290
+ * Replace the index's content with what `documents()` yields (in batches): documents it no longer yields are
291
+ * removed. Returns the counts.
292
+ */
293
+ async reindex(batch = 500): Promise<{ indexed: number; removed: number }> {
294
+ const source = this.options.documents
295
+ if (!source)
296
+ throw new CslugError('search.no_source', `Index ${this.name} has no documents() source to reindex from`)
297
+ const started = resolve(Clock).now()
298
+ let indexed = 0
299
+ let pending: SearchDocument<M>[] = []
300
+ for await (const document of source()) {
301
+ pending.push(document)
302
+ if (pending.length >= batch) {
303
+ await this.upsertMany(pending)
304
+ indexed += pending.length
305
+ pending = []
306
+ }
307
+ }
308
+ await this.upsertMany(pending)
309
+ indexed += pending.length
310
+ const removed = await this.db.exec(sql`delete from ${TABLE} where index = ${this.name} and updated_at < ${started}`)
311
+ return { indexed, removed }
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Define an index (usually in `app/search/`, where `cslug search:reindex` finds it): `searchIndex('help',
317
+ * { languages: ['french', 'english'], documents: async function* () { … } })`. One definition per name.
318
+ */
319
+ export function searchIndex<M extends Record<string, unknown> = Record<string, unknown>>(
320
+ name: string,
321
+ options: SearchIndexOptions<M> = {},
322
+ ): SearchIndex<M> {
323
+ if (registry.has(name)) throw new Error(`searchIndex('${name}') is defined twice`)
324
+ const index = new SearchIndex<M>(name, options)
325
+ registry.set(name, index as unknown as SearchIndex<Record<string, unknown>>)
326
+ return index
327
+ }
328
+
329
+ /** The indexes defined so far (after `discoverSearchIndexes` imported `app/search/`). */
330
+ export const searchIndexes = (): SearchIndex[] => [...registry.values()]
331
+
332
+ /** Import every module under `app/search/`, so their `searchIndex()` definitions run. */
333
+ export async function discoverSearchIndexes(app: Application): Promise<void> {
334
+ const dir = join(app.rootDir, 'app/search')
335
+ if (!existsSync(dir)) return
336
+ for (const file of (readdirSync(dir, { recursive: true }) as string[]).filter((f) => /(?<!\.test)\.ts$/.test(f)))
337
+ await import(join(dir, file))
338
+ }
package/src/search.ts ADDED
@@ -0,0 +1,104 @@
1
+ import type { Query, Row, Table } from '@cslug/database'
2
+ import { type SqlFragment, sql } from '@cslug/database'
3
+ import { type SearchConfig, searchColumnOf } from './searchable'
4
+
5
+ export type SearchOptions<K extends string> = {
6
+ /** The `searchable()` column, when the table has several. */
7
+ column?: string
8
+ /**
9
+ * Search in one language only: a value of the language column (`fr`) or a configuration of the column (`french`).
10
+ * Default: every language of the column at once.
11
+ */
12
+ language?: string
13
+ /**
14
+ * Columns to return with the matching words in `<mark>…</mark>`, as `highlight.<column>`. The text is HTML-escaped
15
+ * first, so the result is safe to render as HTML. `words` per fragment (30), `fragments` (2; 0 for the whole text).
16
+ */
17
+ highlight?: K[] | { columns: K[]; words?: number; fragments?: number }
18
+ /**
19
+ * Columns matched by word similarity too (pg_trgm), so `isallo` finds `Isalo`. Each needs a trigram index:
20
+ * `t.using('gin', ['title', 'gin_trgm_ops'])`.
21
+ */
22
+ typos?: K[]
23
+ }
24
+
25
+ type Source<T extends Table, R> = Query<T, R> | { query(): Query<T, R> }
26
+ type Highlighted<K extends string> = [K] extends [never] ? unknown : { highlight: Record<K, string> }
27
+
28
+ const quoted = (s: string) => sql.raw(`'${s.replace(/'/g, "''")}'`)
29
+ const escapeHtml = (text: unknown) =>
30
+ sql`replace(replace(replace(replace(coalesce(${text}, ''), '&', '&amp;'), '<', '&lt;'), '>', '&gt;'), '"', '&quot;')`
31
+
32
+ function languages(config: SearchConfig, language: string | undefined): string[] {
33
+ if (language === undefined) return config.configs
34
+ const byValue = config.byColumn?.configs[language]
35
+ if (byValue) return [byValue]
36
+ const named = config.configs.find((c) => c === language || c === `cslug_${language}`)
37
+ if (named) return [named]
38
+ throw new Error(`search(): "${language}" is not a language of this search column (${config.configs.join(', ')})`)
39
+ }
40
+
41
+ /**
42
+ * A full-text search on a repository or a query, ranked: the rows that match `term` (web-search syntax: `"exact
43
+ * phrase"`, `-without`, `or`), best first, each with its `rank` (and `highlight` when asked). The result is a query:
44
+ * keep chaining `where`, `orderBy` (after the rank), `paginate`.
45
+ *
46
+ * ```ts
47
+ * const page = await search(this.circuits, 'isalo 4x4', { highlight: ['summary'] }).where({ published: true }).paginate()
48
+ * ```
49
+ */
50
+ export function search<T extends Table, R, K extends keyof Row<T> & string = never>(
51
+ source: Source<T, R>,
52
+ term: string,
53
+ options: SearchOptions<K> = {},
54
+ ): Query<T, R & { rank: number } & Highlighted<K>> {
55
+ const query = 'query' in source && typeof source.query === 'function' ? source.query() : (source as Query<T, R>)
56
+ const table = query.table
57
+ const { key, config } = searchColumnOf(table, options.column)
58
+ const col = (k: string): unknown => (table.c as Record<string, unknown>)[k]
59
+ const vector = col(key)
60
+ const used = languages(config, options.language)
61
+ const tsquery = sql`(${sql.join(
62
+ used.map((cfg) => sql`websearch_to_tsquery(${quoted(cfg)}::regconfig, ${term})`),
63
+ sql` || `,
64
+ )})`
65
+ const typos = options.typos ?? []
66
+ const similar = typos.map((f) => sql`word_similarity(${term}, ${col(f)})`)
67
+ const rank = similar.length
68
+ ? sql<number>`(ts_rank_cd(${vector}, ${tsquery}, 32) + 0.3 * greatest(${sql.join(similar)}))::float8`
69
+ : sql<number>`ts_rank_cd(${vector}, ${tsquery}, 32)::float8`
70
+
71
+ let q = query.selectSql('rank', rank) as Query<T, R & { rank: number }>
72
+ if (/\w/.test(term)) {
73
+ const match = sql`${vector} @@ ${tsquery}`
74
+ const condition = typos.length
75
+ ? sql`(${match} or ${sql.join(
76
+ typos.map((f) => sql`${term} <% ${col(f)}`),
77
+ sql` or `,
78
+ )})`
79
+ : match
80
+ q = q.whereSql(condition).orderBySql(sql`${sql.ident('rank')} desc`)
81
+ }
82
+
83
+ const highlight = options.highlight
84
+ if (!highlight) return q as Query<T, R & { rank: number } & Highlighted<K>>
85
+ const { columns, words = 30, fragments = 2 } = Array.isArray(highlight) ? { columns: highlight } : highlight
86
+ const settings = quoted(
87
+ `StartSel=<mark>, StopSel=</mark>, MaxWords=${words}, MinWords=${Math.max(1, Math.min(10, words - 1))}, ` +
88
+ `MaxFragments=${fragments}, FragmentDelimiter=" … "`,
89
+ )
90
+ const headline = (column: K, cfg: string) =>
91
+ sql`ts_headline(${quoted(cfg)}::regconfig, ${escapeHtml(col(column))}, ${tsquery}, ${settings})`
92
+ const perRow = (column: K) => {
93
+ const b = config.byColumn
94
+ if (!b || used.length === 1) return headline(column, used[0] as string)
95
+ const cases = Object.entries(b.configs).map(
96
+ ([value, cfg]) => sql`when ${quoted(value)} then ${headline(column, cfg)}`,
97
+ )
98
+ return sql`case ${col(b.column)} ${sql.join(cases, sql` `)} else ${headline(column, b.fallback)} end`
99
+ }
100
+ return q.selectSql(
101
+ 'highlight',
102
+ sql<Record<K, string>>`json_build_object(${sql.join(columns.flatMap((c) => [quoted(c), perRow(c)]))})`,
103
+ ) as Query<T, R & { rank: number } & Highlighted<K>>
104
+ }
@@ -0,0 +1,102 @@
1
+ import { join } from 'node:path'
2
+ import { type Column, custom, type Generated, type Hidden, type Table } from '@cslug/database'
3
+
4
+ /** The `cslug_search` migration: unaccent, pg_trgm, and the accent-insensitive `cslug_<config>` configurations. */
5
+ export const SEARCH_MIGRATIONS = join(import.meta.dir, '../migrations')
6
+ /** The embeddings migration (pgvector), registered with `search.vectors: true`. */
7
+ export const VECTOR_MIGRATIONS = join(import.meta.dir, '../migrations-vectors')
8
+
9
+ /** A weight per searchable column: `A` counts most, then `B`, `C`, `D`. */
10
+ export type Weights = Record<string, 'A' | 'B' | 'C' | 'D'>
11
+
12
+ /**
13
+ * The language of the text: a PostgreSQL text search configuration (`english`, `french`, `italian`, `simple`…), or a
14
+ * column naming each row's language with the configuration for each value.
15
+ */
16
+ export type Language = string | { column: string; configs: Record<string, string>; fallback?: string }
17
+
18
+ export type SearchableOptions = {
19
+ /** Default `simple` (no stemming). */
20
+ language?: Language
21
+ /** Ignore accents (`éléphant` = `elephant`), through the `cslug_<config>` copies; default true. */
22
+ unaccent?: boolean
23
+ }
24
+
25
+ /** What `search()` needs to know about a search column. */
26
+ export type SearchConfig = {
27
+ weights: Weights
28
+ /** The configurations in use (fixed: one; per row: each value's, then the fallback). */
29
+ configs: string[]
30
+ /** Per-row language: the column (TS key) and value → configuration. */
31
+ byColumn?: { column: string; configs: Record<string, string>; fallback: string }
32
+ }
33
+
34
+ const configs = new WeakMap<object, SearchConfig>()
35
+
36
+ const LANGUAGE = /^[a-z_]+$/
37
+ const config = (name: string, unaccent: boolean) => {
38
+ if (!LANGUAGE.test(name)) throw new Error(`Not a text search configuration name: "${name}"`)
39
+ return unaccent ? `cslug_${name}` : name
40
+ }
41
+ const literal = (s: string) => `'${s.replace(/'/g, "''")}'`
42
+
43
+ /**
44
+ * A search column: a hidden `tsvector` PostgreSQL computes from weighted columns, kept up to date on every write.
45
+ * Index it with `t.using('gin', 'search')`.
46
+ *
47
+ * ```ts
48
+ * search: searchable({ title: 'A', summary: 'B', body: 'C' }, { language: 'french' })
49
+ * search: searchable({ title: 'A', body: 'B' }, { language: { column: 'locale', configs: { fr: 'french', en: 'english' } } })
50
+ * ```
51
+ */
52
+ export function searchable(
53
+ weights: Weights,
54
+ options: SearchableOptions = {},
55
+ ): Column<string, false, true> & Generated & Hidden {
56
+ const unaccent = options.unaccent !== false
57
+ const language = options.language ?? 'simple'
58
+ const byColumn =
59
+ typeof language === 'string'
60
+ ? undefined
61
+ : {
62
+ column: language.column,
63
+ configs: Object.fromEntries(Object.entries(language.configs).map(([v, c]) => [v, config(c, unaccent)])),
64
+ fallback: config(language.fallback ?? 'simple', unaccent),
65
+ }
66
+ const fixed = typeof language === 'string' ? config(language, unaccent) : undefined
67
+ for (const w of Object.values(weights))
68
+ if (!['A', 'B', 'C', 'D'].includes(w)) throw new Error(`Search weights are A, B, C or D (got "${w}")`)
69
+
70
+ const column = custom('tsvector')
71
+ .generatedAs((c) => {
72
+ const vector = (cfg: string) =>
73
+ Object.entries(weights)
74
+ .map(([key, w]) => `setweight(to_tsvector(${literal(cfg)}, coalesce(${c(key)}, '')), '${w}')`)
75
+ .join(' || ')
76
+ if (fixed) return vector(fixed)
77
+ const b = byColumn as NonNullable<typeof byColumn>
78
+ const cases = Object.entries(b.configs).map(([value, cfg]) => `when ${literal(value)} then ${vector(cfg)}`)
79
+ return `case ${c(b.column)} ${cases.join(' ')} else ${vector(b.fallback)} end`
80
+ })
81
+ .hidden()
82
+ configs.set(column.def, {
83
+ weights,
84
+ configs: fixed ? [fixed] : [...new Set([...Object.values(byColumn?.configs ?? {}), byColumn?.fallback as string])],
85
+ ...(byColumn ? { byColumn } : {}),
86
+ })
87
+ return column
88
+ }
89
+
90
+ /** The search column of a table (the one named `key`, or the only `searchable()` one) and its configuration. */
91
+ export function searchColumnOf(table: Table, key?: string): { key: string; config: SearchConfig } {
92
+ const found = Object.entries(table.columns).filter(([k, c]) => configs.has(c.def) && (key === undefined || k === key))
93
+ if (found.length === 1) {
94
+ const [k, c] = found[0] as [string, { def: object }]
95
+ return { key: k, config: configs.get(c.def) as SearchConfig }
96
+ }
97
+ throw new Error(
98
+ found.length
99
+ ? `${table.name} has several searchable() columns (${found.map(([k]) => k).join(', ')}): pass { column }`
100
+ : `${table.name} has no searchable() column${key ? ` named "${key}"` : ''}`,
101
+ )
102
+ }