Cotton code
195 lines · 7.3 KB · RustRaw
//! One search across every tool in the file.use rusqlite::types::Value as SqlValue;use crate::driver::Driver;use crate::error::Result;use crate::schema::fts::FTS_SOURCES;use crate::protocol::js::is_js_whitespace;#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]pub struct SearchHit {    pub table: String,    #[serde(rename = "rowId")]    pub row_id: String,    pub title: String,    pub snippet: String,    pub rank: f64,}/// The default page a search box asks for.pub const SEARCH_LIMIT: i64 = 50;/// The characters FTS5 treats as syntax, which a search box must not.const STRIPPED: &[char] = &['"', '\'', '^', '*', ':', '(', ')', '-'];/// Turn whatever a human typed into a safe FTS5 MATCH expression.////// FTS5's query language treats `"`, `*`, `^`, `-`, `:`, `(`, `)`, `NEAR`, `OR`/// and `AND` as syntax, so passing raw input through means a stray quote raises/// a SQL error in front of the user. We do not want the operators — a search/// box is not a query language — so each syntax character breaks the word it/// sits in and every piece is re-quoted as a literal phrase. `None` after stripping means/// there was nothing to search for.pub fn to_match_query(input: &str) -> Option<String> {    // A syntax character BREAKS a word, as the index's tokenizer breaks it:    // "Stand-up" was indexed as `stand` + `up`, and joining the halves into    // "Standup" matched nothing.    let spaced: String = input        .chars()        .map(|ch| if STRIPPED.contains(&ch) { ' ' } else { ch })        .collect();    let tokens: Vec<String> = spaced        // JS `.split(/\s+/)` — the same whitespace set; the empty tokens a        // run of spaces produces are dropped by the filter below.        .split(is_js_whitespace)        .map(|token| token.trim_matches(is_js_whitespace).to_string())        .filter(|token| !token.is_empty())        .collect();    if tokens.is_empty() {        return None;    }    // Each token becomes a quoted literal; the implicit operator between them    // is AND, which is what someone typing two words expects.    Some(        tokens            .iter()            .map(|token| format!("\"{token}\""))            .collect::<Vec<_>>()            .join(" "),    )}/// [`to_match_query`] with its LAST word read as the start of a word, as a/// search box being typed into means it: "dent" finds the Dentist before the/// word is finished. The words before it are whole, as typed.pub fn to_typed_match_query(input: &str) -> Option<String> {    to_match_query(input).map(|matcher| format!("{matcher}*"))}/// Search every indexed table, or the named subset, and merge the hits.pub fn search_all(    db: &Driver,    query: &str,    tables: Option<&[String]>,    limit: Option<i64>,) -> Result<Vec<SearchHit>> {    match to_match_query(query) {        Some(matcher) => search_matching(db, &matcher, tables, limit),        None => Ok(Vec::new()),    }}/// [`search_all`] for a list's search box: the last word is a prefix/// ([`to_typed_match_query`]).pub fn search_all_typed(    db: &Driver,    query: &str,    tables: Option<&[String]>,    limit: Option<i64>,) -> Result<Vec<SearchHit>> {    match to_typed_match_query(query) {        Some(matcher) => search_matching(db, &matcher, tables, limit),        None => Ok(Vec::new()),    }}fn search_matching(    db: &Driver,    matcher: &str,    tables: Option<&[String]>,    limit: Option<i64>,) -> Result<Vec<SearchHit>> {    let limit = limit.unwrap_or(SEARCH_LIMIT);    let mut hits: Vec<SearchHit> = Vec::new();    // ONE index per table. A table may be mirrored twice while a wider index    // is filled beside the one that answers (v122: fts_mail beside    // fts_emails): a filling index is never read, and of two whole ones the    // later-declared — the wider — answers, so no hit comes back twice.    let filling: Vec<String> = crate::fts_fill::all_filling(db)        .map(|rows| rows.into_iter().map(|p| p.fts).collect())        .unwrap_or_default();    let answering = |source: &crate::schema::decl::FtsSource| {        !filling.iter().any(|fts| fts == source.fts)            && !FTS_SOURCES.iter().skip_while(|s| s.fts != source.fts).skip(1).any(|later| {                later.source == source.source && !filling.iter().any(|fts| fts == later.fts)            })    };    for source in FTS_SOURCES {        if let Some(wanted) = tables {            if !wanted.iter().any(|table| table == source.source) {                continue;            }        }        if !answering(source) {            continue;        }        let title_column = source.columns[0];        // The index is external-content: it stores no copy of the row's TEXT        // id, because its rowid IS the source row's rowid. So the id comes from        // the join, and the title is read off the source table for the same        // reason — reading it through the index would send FTS5 to fetch the        // very row this join already has.        let sql = format!(            "SELECT s.id AS row_id,\n                    s.{title_column} AS title,\n                    snippet({fts}, -1, '', '', '…', 12) AS snippet,\n                    rank AS rank\n               FROM {fts}\n               JOIN {table} s ON s.rowid = {fts}.rowid\n              WHERE {fts} MATCH ?\n              ORDER BY rank\n              LIMIT ?",            fts = source.fts,            table = source.source        );        // A malformed match should never take the whole search down; skipping        // the tool is better than a red screen.        let Ok(rows) = db.all(            &sql,            &[SqlValue::Text(matcher.to_string()), SqlValue::Integer(limit)],        ) else {            continue;        };        for row in rows {            let title = row.text("title").map(str::to_string);            let rank = row.real("rank").unwrap_or(0.0);            hits.push(SearchHit {                table: source.source.to_string(),                row_id: row.text("row_id").unwrap_or_default().to_string(),                title: title.clone().unwrap_or_default(),                snippet: row.text("snippet").unwrap_or_default().to_string(),                // FTS5 rank is negative, better matches more negative. Boost a                // hit whose title matched, so "Cotton" the note outranks a note                // that merely mentions cotton in passing.                rank: rank                    * if matches_title(title.as_deref(), matcher) {                        2.0                    } else {                        1.0                    },            });        }    }    // Stable, like `Array.prototype.sort`: two hits with the same rank stay in    // the order their indexes were walked, which is `FTS_SOURCES` order.    hits.sort_by(|a, b| {        a.rank            .partial_cmp(&b.rank)            .unwrap_or(std::cmp::Ordering::Equal)    });    hits.truncate(limit.max(0) as usize);    Ok(hits)}fn matches_title(title: Option<&str>, matcher: &str) -> bool {    let Some(title) = title.filter(|title| !title.is_empty()) else {        return false;    };    let haystack = title.to_lowercase();    matcher        .split(' ')        .map(|token| token.replace(['"', '*'], "").to_lowercase())        .filter(|token| !token.is_empty())        .any(|token| haystack.contains(&token))}#[cfg(test)]#[path = "search_tests.rs"]mod tests;