Skip to main content

renox_core/db/
search.rs

1//! Full-text search over a model's text columns, with one API on both
2//! databases: an FTS5 table on SQLite, a `tsvector` column on PostgreSQL.
3//!
4//! 1. Name the columns on the model: `#[model(search = "title, body")]`
5//!    (columns listed first weigh more in the ranking).
6//! 2. Create the index with a migration made by [`migration`].
7//! 3. Search: `Post::search(&words)` gives a [`Query`](super::Query) of
8//!    the matching rows, best first, that takes more filters, the default
9//!    scope, soft deletes and pagination like any other.
10//!
11//! ```
12//! # use renox::prelude::*;
13//! #[derive(Model, serde::Serialize, Default)]
14//! #[model(table = "posts", search = "title, body")]
15//! struct Post { id: i64, title: String, body: String, published: bool }
16//!
17//! # fn app() -> App {
18//! App::new().migrations(&[
19//!     // After the migration that creates `posts`.
20//!     renox::db::search::migration::<Post>("20260101000100_search_posts"),
21//! ])
22//! # }
23//! # async fn demo(db: Db) -> Result {
24//! let found = Post::search("coffee roast")
25//!     .where_eq("published", true)
26//!     .paginate(&db, 1, 20)
27//!     .await?;
28//! # let _ = found; Ok(()) }
29//! ```
30//!
31//! **What a search matches:** every word of the text, as a word or the
32//! start of one (`cof` finds "coffee"), ignoring case. Punctuation separates
33//! words and is otherwise ignored, so user input is always safe to pass:
34//! no search syntax reaches the database, only words, bound as a value.
35//! A text without any word matches every row (no filter).
36//!
37//! **Language:** `english` by default, which matches word forms ("roasts"
38//! finds "roasting"). `#[model(search_language = "simple")]` matches words
39//! as typed, for other languages. On PostgreSQL the name is a text search
40//! configuration (`spanish`, `german`, …: `\dF` in psql lists them);
41//! SQLite stems only English, so any other name there matches as typed.
42//! PostgreSQL's `english` also skips stop words ("the", "a").
43//!
44//! **Arabic and other scripts:** `#[model(search = "name", normalize = "arabic")]`
45//! makes the search ignore Arabic marks (harakat, tatweel) and spelling
46//! variants (alef forms, ya and alef maqsura, ta marbuta, Persian kaf and ya)
47//! and read Arabic-Indic digits as ASCII digits; see [`Normalize`]. The
48//! index is built over a normalised copy of the text and the words searched
49//! for are normalised the same way. [`crate::text`] has the same
50//! normalisation in Rust.
51//!
52//! **Keeping the index current:** the database does it, so every way of
53//! writing rows is covered: `save`, `delete`, but also bulk
54//! `Query::update`/`delete`, `insert_many` and raw SQL, which skip model
55//! hooks. On SQLite the migration adds triggers on the table; on
56//! PostgreSQL the column is `GENERATED ALWAYS … STORED`. Soft-deleted rows
57//! stay in the index; queries leave them out as usual.
58//!
59//! **What the migration creates**, for `#[model(table = "posts", search = "title, body")]`:
60//! - SQLite: an FTS5 table `posts_search` reading its text from `posts`
61//!   ("external content"), triggers `posts_search_insert`,
62//!   `posts_search_update` and `posts_search_delete`, and fills it from the
63//!   rows already there.
64//! - PostgreSQL: a column `search_vector` (`tsvector`, generated from the
65//!   columns) and a GIN index `posts_search_index` on it.
66//!
67//! With `normalize`, the SQLite FTS5 table keeps its own copy of the
68//! normalised text instead of reading `posts`, and the triggers delete by
69//! rowid; on PostgreSQL the generated column wraps each column in the
70//! normalising `translate(…)`.
71//!
72//! Changed the searchable columns? Add another migration made by
73//! [`migration`] under a new name: it replaces the index (rolling it back
74//! removes the index).
75
76use super::{Dialect, Executor, Migration, Model, quote, sql};
77use crate::Result;
78use crate::text::{self, Rule};
79use anyhow::anyhow;
80
81/// How a model's text is normalised before it is indexed and searched, set
82/// with `#[model(search = "…", normalize = "arabic")]`. Without it, text is
83/// indexed as written.
84///
85/// ```
86/// # use renox::prelude::*;
87/// #[derive(Model, serde::Serialize, Default)]
88/// #[model(table = "parties", search = "name, notes", normalize = "arabic")]
89/// struct Party { id: i64, name: String, notes: String }
90/// ```
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[non_exhaustive]
93pub enum Normalize {
94    /// [`normalize_arabic`](crate::text::normalize_arabic): marks removed,
95    /// alef, ya and ta marbuta forms united, Persian kaf and ya folded,
96    /// Arabic-Indic and Persian digits turned into ASCII digits.
97    Arabic,
98}
99
100/// The SQL expression that normalises the text `expr` the way
101/// [`normalize_arabic`](crate::text::normalize_arabic) does, on `dialect`:
102/// nested `replace(…)` calls on SQLite, one `translate(…)` on PostgreSQL.
103/// Built from the same rule table as the Rust function. This is what a search
104/// index with `normalize = "arabic"` uses; it is public for expressions of
105/// your own (a generated column, a raw query).
106///
107/// `expr` is SQL, written by you, never user input.
108///
109/// ```
110/// use renox::db::{Dialect, search::arabic_sql};
111///
112/// let sql = arabic_sql(Dialect::Postgres, "name");
113/// assert!(sql.starts_with("translate(name, "));
114/// ```
115pub fn arabic_sql(dialect: Dialect, expr: &str) -> String {
116    match dialect {
117        Dialect::Sqlite => {
118            let mut sql = expr.to_owned();
119            for rule in text::RULES {
120                let (from, to) = match *rule {
121                    Rule::Map(from, to) => (from, to.to_string()),
122                    Rule::Delete(from) => (from, String::new()),
123                };
124                sql = format!(
125                    "replace({sql}, {}, {})",
126                    literal(&from.to_string()),
127                    literal(&to)
128                );
129            }
130            sql
131        }
132        Dialect::Postgres => {
133            // translate() drops the characters of `from` that have no
134            // counterpart in `to`, so the mappings come first.
135            let (mut from, mut to) = (String::new(), String::new());
136            for rule in text::RULES {
137                if let Rule::Map(f, t) = *rule {
138                    from.push(f);
139                    to.push(t);
140                }
141            }
142            for rule in text::RULES {
143                if let Rule::Delete(f) = *rule {
144                    from.push(f);
145                }
146            }
147            format!("translate({expr}, {}, {})", literal(&from), literal(&to))
148        }
149    }
150}
151
152/// `expr` normalised as `M` asks (unchanged without `normalize`).
153fn indexed_expr<M: Model>(dialect: Dialect, expr: &str) -> String {
154    match M::SEARCH_NORMALIZE {
155        Some(Normalize::Arabic) => arabic_sql(dialect, expr),
156        None => expr.to_owned(),
157    }
158}
159
160/// The text of a search, normalised as `M`'s index is.
161fn normalized<M: Model>(text: &str) -> std::borrow::Cow<'_, str> {
162    match M::SEARCH_NORMALIZE {
163        Some(Normalize::Arabic) => text::normalize_arabic(text).into(),
164        None => text.into(),
165    }
166}
167
168/// At most this many words of a search are used.
169const MAX_TERMS: usize = 16;
170/// Longer words are cut to this many characters.
171const MAX_TERM_CHARS: usize = 64;
172
173/// The words of `text` (letters and digits; anything else separates
174/// them), joined by single spaces: the one value a search binds. `None`
175/// when there is no word. Keeping only letters and digits is what makes
176/// user input safe in FTS5's and `to_tsquery`'s syntax.
177pub(crate) fn terms(text: &str) -> Option<String> {
178    let words: Vec<String> = text
179        .split(|c: char| !c.is_alphanumeric())
180        .filter(|w| !w.is_empty())
181        .take(MAX_TERMS)
182        .map(|w| w.chars().take(MAX_TERM_CHARS).collect())
183        .collect();
184    (!words.is_empty()).then(|| words.join(" "))
185}
186
187/// Why `M` can't be searched, if it can't.
188pub(crate) fn unsearchable<M: Model>() -> Option<String> {
189    if M::SEARCHABLE.is_empty() {
190        return Some(format!(
191            "`{}` has no full-text search: add #[model(search = \"…\")]",
192            M::TABLE
193        ));
194    }
195    if !valid_language(M::SEARCH_LANGUAGE) {
196        return Some(format!(
197            "search language `{}` isn't a plain name (letters and `_`)",
198            M::SEARCH_LANGUAGE
199        ));
200    }
201    None
202}
203
204fn valid_language(language: &str) -> bool {
205    !language.is_empty() && language.chars().all(|c| c.is_ascii_lowercase() || c == '_')
206}
207
208/// The FTS5 table's name on SQLite.
209fn fts_table<M: Model>() -> String {
210    format!("{}_search", M::TABLE)
211}
212
213/// The value `Query::search` binds: the words (`terms`), then, after a
214/// unit separator, the text as typed (control characters left out, at most
215/// 200 characters). One value for both databases; each takes what it needs.
216pub(crate) fn bound<M: Model>(text: &str) -> Option<String> {
217    let text = &*normalized::<M>(text);
218    let words = terms(text)?;
219    let typed: String = text.chars().filter(|c| !c.is_control()).take(200).collect();
220    Some(format!("{words}{SEPARATOR}{}", typed.trim()))
221}
222
223/// Between the words and the typed text in `bound`'s value.
224const SEPARATOR: char = '\u{1f}';
225
226/// The match expression for the one bound value (`bound`).
227///
228/// SQLite: each word as a prefix, all of them required. PostgreSQL: the
229/// same, or the text as typed read by PostgreSQL's own parser, which splits
230/// it the way it split the row: it reads `-1` in `GIR-JER-0001-1` and
231/// `-12.5` in `SKU-12.5` as signed numbers, so a code typed whole matches
232/// only that way (#304). Built in SQL from the bound value, read once in a
233/// subquery so the statement has a single `?`.
234fn match_expression(dialect: Dialect) -> &'static str {
235    match dialect {
236        // "cof"* "tea"*
237        Dialect::Sqlite => {
238            "(SELECT '\"' || replace(substr(v, 1, instr(v, char(31)) - 1), ' ', '\"* \"') || '\"*' \
239             FROM (SELECT ? AS v))"
240        }
241        // cof:* & tea:*, or what PostgreSQL makes of the typed text
242        Dialect::Postgres => {
243            "(SELECT to_tsquery(c, replace(split_part(v, chr(31), 1), ' ', ':* & ') || ':*') \
244             || plainto_tsquery(c, split_part(v, chr(31), 2)) FROM (SELECT ?::text AS v, %CONFIG% AS c) AS s)"
245        }
246    }
247}
248
249/// The language as a SQL literal; `unsearchable` has checked it is only
250/// lowercase letters and `_` (it comes from the model, never from input).
251fn config_literal<M: Model>() -> String {
252    format!("'{}'::regconfig", M::SEARCH_LANGUAGE)
253}
254
255/// `WHERE` condition: the row matches the search (one `?`).
256pub(crate) fn filter_sql<M: Model>(dialect: Dialect) -> String {
257    match dialect {
258        Dialect::Sqlite => format!(
259            "{}.rowid IN (SELECT rowid FROM {fts} WHERE {fts} MATCH {})",
260            quote(M::TABLE),
261            match_expression(dialect),
262            fts = quote(&fts_table::<M>()),
263        ),
264        Dialect::Postgres => format!(
265            "{}.\"search_vector\" @@ {}",
266            quote(M::TABLE),
267            match_expression(dialect).replace("%CONFIG%", &config_literal::<M>())
268        ),
269    }
270}
271
272/// The weight of the column at `index` (A, B, C, D on PostgreSQL).
273fn weight(index: usize) -> (char, &'static str) {
274    match index {
275        0 => ('A', "1.0"),
276        1 => ('B', "0.4"),
277        2 => ('C', "0.2"),
278        _ => ('D', "0.1"),
279    }
280}
281
282/// `ORDER BY` term: best matches first (one `?`). Rows that don't match
283/// come last.
284pub(crate) fn rank_sql<M: Model>(dialect: Dialect) -> String {
285    match dialect {
286        Dialect::Sqlite => {
287            // bm25 is negative, lower is better; non-matches get 0.
288            let weights: Vec<&str> = (0..M::SEARCHABLE.len()).map(|i| weight(i).1).collect();
289            format!(
290                "COALESCE((SELECT bm25({fts}, {}) FROM {fts} WHERE {fts} MATCH {} AND {fts}.rowid = {}.rowid), 0) ASC",
291                weights.join(", "),
292                match_expression(dialect),
293                quote(M::TABLE),
294                fts = quote(&fts_table::<M>()),
295            )
296        }
297        Dialect::Postgres => format!(
298            "ts_rank({}.\"search_vector\", {}) DESC",
299            quote(M::TABLE),
300            match_expression(dialect).replace("%CONFIG%", &config_literal::<M>())
301        ),
302    }
303}
304
305/// A string literal in SQL.
306fn literal(text: &str) -> String {
307    format!("'{}'", text.replace('\'', "''"))
308}
309
310fn sqlite_up<M: Model>() -> String {
311    let table = quote(M::TABLE);
312    let fts = quote(&fts_table::<M>());
313    let columns: Vec<String> = M::SEARCHABLE.iter().map(|c| quote(c)).collect();
314    let columns = columns.join(", ");
315    let tokenize = if M::SEARCH_LANGUAGE == "english" {
316        "porter unicode61 remove_diacritics 2"
317    } else {
318        "unicode61 remove_diacritics 2"
319    };
320    let trigger = |suffix: &str| quote(&format!("{}_search_{suffix}", M::TABLE));
321    if M::SEARCH_NORMALIZE.is_some() {
322        // The index holds a normalised copy of the text, so it can't read
323        // the table as external content (a rebuild would index the text as
324        // written): it keeps its own, and the triggers delete by rowid.
325        let values = |row: &str| -> String {
326            M::SEARCHABLE
327                .iter()
328                .map(|c| indexed_expr::<M>(Dialect::Sqlite, &format!("{row}.{}", quote(c))))
329                .collect::<Vec<_>>()
330                .join(", ")
331        };
332        return format!(
333            "{drop}\n\
334             CREATE VIRTUAL TABLE {fts} USING fts5({columns}, tokenize={tokenize});\n\
335             CREATE TRIGGER {insert} AFTER INSERT ON {table} BEGIN\n\
336             \x20   INSERT INTO {fts}(rowid, {columns}) VALUES (new.rowid, {new});\n\
337             END;\n\
338             CREATE TRIGGER {delete} AFTER DELETE ON {table} BEGIN\n\
339             \x20   DELETE FROM {fts} WHERE rowid = old.rowid;\n\
340             END;\n\
341             CREATE TRIGGER {update} AFTER UPDATE OF \"id\", {columns} ON {table} BEGIN\n\
342             \x20   DELETE FROM {fts} WHERE rowid = old.rowid;\n\
343             \x20   INSERT INTO {fts}(rowid, {columns}) VALUES (new.rowid, {new});\n\
344             END;\n\
345             {fill};",
346            drop = sqlite_down::<M>(),
347            new = values("new"),
348            fill = sqlite_fill::<M>(),
349            tokenize = literal(tokenize),
350            insert = trigger("insert"),
351            delete = trigger("delete"),
352            update = trigger("update"),
353        );
354    }
355    let new: Vec<String> = M::SEARCHABLE
356        .iter()
357        .map(|c| format!("new.{}", quote(c)))
358        .collect();
359    let old: Vec<String> = M::SEARCHABLE
360        .iter()
361        .map(|c| format!("old.{}", quote(c)))
362        .collect();
363    let (new, old) = (new.join(", "), old.join(", "));
364    format!(
365        "{drop}\n\
366         CREATE VIRTUAL TABLE {fts} USING fts5({columns}, content={content}, tokenize={tokenize});\n\
367         CREATE TRIGGER {insert} AFTER INSERT ON {table} BEGIN\n\
368         \x20   INSERT INTO {fts}(rowid, {columns}) VALUES (new.rowid, {new});\n\
369         END;\n\
370         CREATE TRIGGER {delete} AFTER DELETE ON {table} BEGIN\n\
371         \x20   INSERT INTO {fts}({fts}, rowid, {columns}) VALUES ('delete', old.rowid, {old});\n\
372         END;\n\
373         CREATE TRIGGER {update} AFTER UPDATE OF \"id\", {columns} ON {table} BEGIN\n\
374         \x20   INSERT INTO {fts}({fts}, rowid, {columns}) VALUES ('delete', old.rowid, {old});\n\
375         \x20   INSERT INTO {fts}(rowid, {columns}) VALUES (new.rowid, {new});\n\
376         END;\n\
377         INSERT INTO {fts}({fts}) VALUES ('rebuild');",
378        drop = sqlite_down::<M>(),
379        content = literal(M::TABLE),
380        tokenize = literal(tokenize),
381        insert = trigger("insert"),
382        delete = trigger("delete"),
383        update = trigger("update"),
384    )
385}
386
387/// Fills a normalising model's own FTS5 table from the rows (it is empty).
388fn sqlite_fill<M: Model>() -> String {
389    let columns: Vec<String> = M::SEARCHABLE.iter().map(|c| quote(c)).collect();
390    let values: Vec<String> = M::SEARCHABLE
391        .iter()
392        .map(|c| indexed_expr::<M>(Dialect::Sqlite, &quote(c)))
393        .collect();
394    format!(
395        "INSERT INTO {fts}(rowid, {}) SELECT rowid, {} FROM {}",
396        columns.join(", "),
397        values.join(", "),
398        quote(M::TABLE),
399        fts = quote(&fts_table::<M>()),
400    )
401}
402
403fn sqlite_down<M: Model>() -> String {
404    let trigger = |suffix: &str| quote(&format!("{}_search_{suffix}", M::TABLE));
405    format!(
406        "DROP TRIGGER IF EXISTS {};\nDROP TRIGGER IF EXISTS {};\nDROP TRIGGER IF EXISTS {};\nDROP TABLE IF EXISTS {};",
407        trigger("insert"),
408        trigger("update"),
409        trigger("delete"),
410        quote(&fts_table::<M>())
411    )
412}
413
414fn postgres_up<M: Model>() -> String {
415    let vector: Vec<String> = M::SEARCHABLE
416        .iter()
417        .enumerate()
418        .map(|(i, c)| {
419            format!(
420                "setweight(to_tsvector({}, coalesce({}, '')), '{}')",
421                config_literal::<M>(),
422                indexed_expr::<M>(Dialect::Postgres, &format!("{}::text", quote(c))),
423                weight(i).0
424            )
425        })
426        .collect();
427    format!(
428        "{drop}\n\
429         ALTER TABLE {table} ADD COLUMN \"search_vector\" tsvector GENERATED ALWAYS AS ({vector}) STORED;\n\
430         CREATE INDEX {index} ON {table} USING GIN (\"search_vector\");",
431        drop = postgres_down::<M>(),
432        table = quote(M::TABLE),
433        vector = vector.join(" || "),
434        index = quote(&format!("{}_search_index", M::TABLE)),
435    )
436}
437
438fn postgres_down<M: Model>() -> String {
439    format!(
440        "DROP INDEX IF EXISTS {};\nALTER TABLE {} DROP COLUMN IF EXISTS \"search_vector\";",
441        quote(&format!("{}_search_index", M::TABLE)),
442        quote(M::TABLE)
443    )
444}
445
446/// A migration that creates `M`'s full-text index (and removes it when
447/// rolled back), from the model's `#[model(search = …)]` columns and
448/// language. Name it so it sorts after the migration creating the table,
449/// and register it with [`App::migrations`](crate::App::migrations).
450/// Running it again under a new name replaces the index, e.g. after the
451/// searchable columns changed. The module docs list what it creates.
452///
453/// Call it once, while building the app: the SQL it makes lives as long
454/// as the program.
455///
456/// # Panics
457///
458/// When `M` has no searchable columns.
459pub fn migration<M: Model>(name: &'static str) -> Migration {
460    if let Some(problem) = unsearchable::<M>() {
461        panic!("renox::db::search::migration: {problem}");
462    }
463    let leak = |sql: String| -> &'static str { Box::leak(sql.into_boxed_str()) };
464    Migration::new(name, "", None)
465        .sqlite(leak(sqlite_up::<M>()), Some(leak(sqlite_down::<M>())))
466        .postgres(leak(postgres_up::<M>()), Some(leak(postgres_down::<M>())))
467}
468
469/// Fills `M`'s full-text index again from the table's rows. The index
470/// keeps itself current, so this is for repairs: rows written while its
471/// triggers were dropped, or a restored backup of the table alone. On
472/// PostgreSQL the generated column is always current, so it does nothing.
473///
474/// ```
475/// # use renox::prelude::*;
476/// # #[derive(Model, serde::Serialize, Default)]
477/// # #[model(table = "posts", search = "title, body")]
478/// # struct Post { id: i64, title: String, body: String }
479/// # async fn demo(db: Db) -> Result {
480/// renox::db::search::rebuild::<Post>(&db).await?;
481/// # Ok(()) }
482/// ```
483pub async fn rebuild<'c, M: Model>(db: impl Executor<'c>) -> Result {
484    if let Some(problem) = unsearchable::<M>() {
485        return Err(anyhow!("{problem}").into());
486    }
487    let db = db.into_conn();
488    if db.dialect() == Dialect::Sqlite {
489        let fts = quote(&fts_table::<M>());
490        if M::SEARCH_NORMALIZE.is_some() {
491            super::script(db, &format!("DELETE FROM {fts};\n{}", sqlite_fill::<M>())).await?;
492        } else {
493            sql(format!("INSERT INTO {fts}({fts}) VALUES ('rebuild')"))
494                .execute(db)
495                .await?;
496        }
497    }
498    Ok(())
499}
500
501#[cfg(test)]
502mod tests {
503    use super::terms;
504
505    #[test]
506    fn terms_keep_only_words() {
507        assert_eq!(terms("  Coffee, roast!  "), Some("Coffee roast".into()));
508        assert_eq!(
509            terms("\"a\" OR b* NEAR(c) -d"),
510            Some("a OR b NEAR c d".into())
511        );
512        assert_eq!(
513            terms("it's x'; DROP TABLE posts; --"),
514            Some("it s x DROP TABLE posts".into())
515        );
516        assert_eq!(terms("café 東京"), Some("café 東京".into()));
517        assert_eq!(terms("!!! ... ---"), None);
518        assert_eq!(terms(""), None);
519        let many = "w ".repeat(40);
520        assert_eq!(terms(&many).unwrap().split(' ').count(), 16);
521        assert_eq!(terms(&"x".repeat(100)).unwrap().len(), 64);
522    }
523}