Skip to main content

datumesh_store/
catalogue.rs

1//! The catalogue (0.5.0): entries that describe functions and classes, dictionaries of key
2//! values, embeddings of their text (PostgreSQL with the `vector` extension) and the log of
3//! find misses. This module is what both backends share: the types, the bounds, the text
4//! search's matching and scores, and the canonical JSON of the stored columns. The SQL is in
5//! `pg.rs` and `sqlite.rs`.
6//!
7//! Text search ([`Store::text_find`](crate::Store::text_find)): the query is split on white
8//! space, each word (lower-cased) must be found in the entry or value, in any of its fields;
9//! a word is found in a field as the whole field (score 1.0), as one of the field's words
10//! (0.8) or inside it (0.5). An entry's score is the mean over the words of the best field's
11//! score, so it lies in (0, 1]. Words match literally (`%`, `_` and `\` are characters).
12//! The backends prefilter rows in SQL with LIKE and rank them here, so both give the same
13//! answers (see [`Words::pattern`] for the words the SQL cannot match exactly).
14
15use std::collections::BTreeMap;
16
17use datumesh_core::json;
18use datumesh_core::lexical::{check_function_name, check_hex, check_name};
19use datumesh_core::{Error as CoreError, ErrorCode};
20
21use crate::error::{Error, Result};
22
23/// The most rows `find_misses` keeps; the oldest are pruned.
24pub const FIND_MISSES_CAP: usize = 100_000;
25
26/// Bytes of a find miss's query text kept (cut on a character boundary).
27pub(crate) const MISS_BYTES: usize = 512;
28
29/// The dimension of the embeddings (`intfloat/multilingual-e5-small`).
30pub(crate) const EMBED_DIM: usize = 384;
31
32/// The most values of a dictionary a summary shows.
33pub(crate) const SUMMARY_VALUES: usize = 50;
34
35/// The kind of a catalogue entry.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum CatalogKind {
38    /// A class.
39    Class,
40    /// A method of a class (a function named `<class name>/<method>`).
41    Method,
42    /// A function.
43    Function,
44}
45
46impl CatalogKind {
47    /// The name the store keeps: `class`, `method` or `function`.
48    pub fn as_str(self) -> &'static str {
49        match self {
50            CatalogKind::Class => "class",
51            CatalogKind::Method => "method",
52            CatalogKind::Function => "function",
53        }
54    }
55
56    pub(crate) fn parse(s: &str) -> Option<CatalogKind> {
57        Some(match s {
58            "class" => CatalogKind::Class,
59            "method" => CatalogKind::Method,
60            "function" => CatalogKind::Function,
61            _ => return None,
62        })
63    }
64}
65
66/// Who published an entry: the publisher (its signed document) or the operator (a local
67/// file). An operator's entry never replaces a publisher's.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69pub enum CatalogSource {
70    /// The publisher's own text.
71    Publisher,
72    /// The operator's text.
73    Operator,
74    /// The text of a listed function (a name of another mesh, described here and not served here;
75    /// `signed_by` is that mesh's host). Written by [`Store::put_listing`](crate::Store::put_listing)
76    /// only. Since 0.7.0.
77    Listed,
78}
79
80impl CatalogSource {
81    /// `publisher`, `operator` or `listed`.
82    pub fn as_str(self) -> &'static str {
83        match self {
84            CatalogSource::Publisher => "publisher",
85            CatalogSource::Operator => "operator",
86            CatalogSource::Listed => "listed",
87        }
88    }
89
90    pub(crate) fn parse(s: &str) -> Option<CatalogSource> {
91        Some(match s {
92            "publisher" => CatalogSource::Publisher,
93            "operator" => CatalogSource::Operator,
94            "listed" => CatalogSource::Listed,
95            _ => return None,
96        })
97    }
98}
99
100/// A catalogue entry, keyed by (kind, name).
101///
102/// `label` is at most 120 bytes (it may be empty), `description` 1 to 1024 bytes; `args` maps
103/// each argument's name to its text; `examples` is a JSON array (kept in canonical form).
104#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct CatalogEntry {
106    /// Class, method or function.
107    pub kind: CatalogKind,
108    /// The full name (SPEC 2.3).
109    pub name: String,
110    /// The function hash (a function) or the class hash (a class), when it has one.
111    pub hash: Option<String>,
112    /// A short human label.
113    pub label: String,
114    /// What it does, in words.
115    pub description: String,
116    /// The text of each argument, by name.
117    pub args: BTreeMap<String, String>,
118    /// A JSON array of `{call, expected}` examples.
119    pub examples: String,
120    /// Who published it.
121    pub source: CatalogSource,
122    /// The key reference of the signer, when signed.
123    pub signed_by: Option<String>,
124}
125
126/// The facets of a catalogue entry: a facet key (`domain`, `thing`, `measure`, `region` or
127/// `frequency`) to its names, ascending and unique, at most 8 of them (CONTRACT-classes-round C2).
128pub type Facets = BTreeMap<String, Vec<String>>;
129
130/// A catalogue entry with its facets and its `extends` (CONTRACT-classes-round C2 and K9).
131///
132/// `extends` is the full name of the class a function extends (16.8): only a function extends a
133/// class, and the store does not check that the class is stored. [`CatalogEntry`] itself is
134/// unchanged; an entry with no facets and no `extends` is `CatalogEntryExt::new`.
135#[non_exhaustive]
136#[derive(Clone, Debug, PartialEq, Eq)]
137pub struct CatalogEntryExt {
138    /// The entry.
139    pub entry: CatalogEntry,
140    /// Its facets; empty when it has none.
141    pub facets: Facets,
142    /// The class this function extends, when it extends one.
143    pub extends: Option<String>,
144    /// The name of the entry's source as the publisher gives it, when it gives one. Since 0.6.0.
145    pub source_name: Option<String>,
146}
147
148impl CatalogEntryExt {
149    /// The entry with no facets and no `extends`.
150    pub fn new(entry: CatalogEntry) -> CatalogEntryExt {
151        CatalogEntryExt { entry, facets: Facets::new(), extends: None, source_name: None }
152    }
153}
154
155/// A catalogue entry that has facets, as [`Store::catalog_entries_with_facets`](crate::Store::catalog_entries_with_facets)
156/// lists it.
157#[non_exhaustive]
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub struct FacetedEntry {
160    /// Class, method or function.
161    pub kind: CatalogKind,
162    /// The full name.
163    pub name: String,
164    /// The catalogue's hash of the entry (a function's or a class's), when it has one.
165    pub hash: Option<String>,
166    /// Its facets; at least one key.
167    pub facets: Facets,
168    /// The instant of the earliest binding of the name (of a class for a class, of a function
169    /// or method otherwise); `None` when the name was never bound.
170    pub first_bound: Option<String>,
171    /// The entry's `source_name`, when it has one. Since 0.6.0.
172    pub source_name: Option<String>,
173}
174
175/// The facet keys an entry may carry.
176pub(crate) const FACET_KEYS: &[&str] = &["domain", "frequency", "measure", "region", "thing"];
177
178/// The most names a facet lists.
179pub(crate) const FACET_MAX: usize = 8;
180
181/// One row to write: an entry, its facets as canonical JSON, and its `extends`.
182pub(crate) struct CatalogRow<'a> {
183    pub(crate) entry: &'a CatalogEntry,
184    pub(crate) facets: String,
185    pub(crate) extends: Option<&'a str>,
186    pub(crate) source_name: Option<&'a str>,
187}
188
189impl<'a> CatalogRow<'a> {
190    /// A row of the 0.5.2 call: no facets, no `extends` (the store keeps those of an existing row).
191    pub(crate) fn plain(entry: &'a CatalogEntry) -> Self {
192        CatalogRow { entry, facets: "{}".to_string(), extends: None, source_name: None }
193    }
194
195    /// A row of the facets call, with its facets and `extends` as given.
196    pub(crate) fn ext(e: &'a CatalogEntryExt) -> Self {
197        CatalogRow {
198            entry: &e.entry,
199            facets: facets_json(&e.facets),
200            extends: e.extends.as_deref(),
201            source_name: e.source_name.as_deref(),
202        }
203    }
204}
205
206/// One value of a dictionary: its label and aliases (the publisher's dictionary only).
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct KeyValue {
209    /// The canonical lexical form of the value (as a cell argument has it).
210    pub value: String,
211    /// Its human text, for example `2 Chronicles` for `2Chr`; may be empty.
212    pub label: String,
213    /// Other words for it (`1Mo` for `Gen`).
214    pub aliases: Vec<String>,
215}
216
217/// What an embedding is of: a catalogue entry or a dictionary value.
218#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
219pub enum EmbedRef {
220    /// A catalogue entry (its id is the entry's id).
221    Entry,
222    /// A dictionary value (its id is the value's id).
223    Value,
224}
225
226impl EmbedRef {
227    /// `entry` or `value`.
228    pub fn as_str(self) -> &'static str {
229        match self {
230            EmbedRef::Entry => "entry",
231            EmbedRef::Value => "value",
232        }
233    }
234}
235
236/// An embedding of an entry or a value, for one model.
237#[derive(Clone, Debug, PartialEq)]
238pub struct Embedding {
239    /// What it is of.
240    pub ref_kind: EmbedRef,
241    /// The id of the entry or value.
242    pub ref_id: i64,
243    /// 384 finite values, not all zero (normalised by the caller, when cosine is the measure).
244    pub vec: Vec<f32>,
245}
246
247/// An entry or value with no embedding for a model, and the text to embed.
248#[non_exhaustive]
249#[derive(Clone, Debug, PartialEq, Eq)]
250pub struct PendingEmbedding {
251    /// Entry or value.
252    pub ref_kind: EmbedRef,
253    /// Its id.
254    pub ref_id: i64,
255    /// The text: `<label>. <description>` for an entry (the description alone when the label
256    /// is empty), the label for a value (the value when the label is empty).
257    pub text: String,
258}
259
260/// A text-search hit: an entry, or a dictionary value.
261#[non_exhaustive]
262#[derive(Clone, Debug, PartialEq)]
263pub enum Hit {
264    /// A catalogue entry.
265    Entry {
266        /// Its id.
267        id: i64,
268        /// The entry.
269        entry: CatalogEntry,
270        /// How well it matches, in (0, 1] for text and [-1, 1] for vectors (cosine).
271        score: f64,
272    },
273    /// A dictionary value.
274    Value {
275        /// Its id.
276        id: i64,
277        /// The owner (a function or class name).
278        owner: String,
279        /// The key.
280        key: String,
281        /// The canonical lexical form of the value.
282        value: String,
283        /// Its label (may be empty).
284        label: String,
285        /// Its aliases.
286        aliases: Vec<String>,
287        /// How well it matches (as for entries).
288        score: f64,
289    },
290}
291
292/// The catalogue as an operator sees it ([`Store::catalog_summary`](crate::Store::catalog_summary)).
293#[non_exhaustive]
294#[derive(Clone, Debug, PartialEq, Eq)]
295pub struct Summary {
296    /// Every entry, by kind then name.
297    pub entries: Vec<SummaryEntry>,
298    /// Every dictionary, by owner then key.
299    pub dictionaries: Vec<Dictionary>,
300}
301
302/// An entry of a [`Summary`].
303#[non_exhaustive]
304#[derive(Clone, Debug, PartialEq, Eq)]
305pub struct SummaryEntry {
306    /// Class, method or function.
307    pub kind: CatalogKind,
308    /// The full name.
309    pub name: String,
310    /// Its label.
311    pub label: String,
312    /// The cells of the function that are stored (0 for a class or a method).
313    pub n_cells: i64,
314}
315
316/// A dictionary of a [`Summary`]: the values of one key of one owner.
317#[non_exhaustive]
318#[derive(Clone, Debug, PartialEq, Eq)]
319pub struct Dictionary {
320    /// The owner: a function or class name.
321    pub owner: String,
322    /// The key.
323    pub key: String,
324    /// How many values the dictionary has.
325    pub n_values: i64,
326    /// Its first values by value, at most 50.
327    pub values: Vec<DictionaryValue>,
328}
329
330/// A value of a [`Dictionary`].
331#[non_exhaustive]
332#[derive(Clone, Debug, PartialEq, Eq)]
333pub struct DictionaryValue {
334    /// The canonical lexical form.
335    pub value: String,
336    /// Its label.
337    pub label: String,
338    /// The cells of the owner's function that have this value for the key (refreshed by
339    /// `refresh_value_counts`).
340    pub n_cells: i64,
341}
342
343// ---- Validation -------------------------------------------------------------------------
344
345pub(crate) fn invalid(path: &str, detail: impl Into<String>) -> Error {
346    Error::Invalid(CoreError::new(ErrorCode::Schema, path, detail))
347}
348
349/// A catalogue entry's bounds and forms (the store refuses an entry that breaks them).
350pub(crate) fn check_catalog_entry(e: &CatalogEntry) -> Result<()> {
351    check_function_name(&e.name, "name")?;
352    if let Some(h) = &e.hash {
353        check_hex(h, 64, "hash")?;
354    }
355    if e.label.len() > 120 {
356        return Err(invalid("label", "a label has at most 120 bytes"));
357    }
358    if e.description.is_empty() || e.description.len() > 1024 {
359        return Err(invalid("description", "a description has 1 to 1024 bytes"));
360    }
361    for (k, v) in &e.args {
362        check_name(k, "args")?;
363        if v.len() > 1024 {
364            return Err(invalid("args", "an argument's text has at most 1024 bytes"));
365        }
366    }
367    if args_json(&e.args).len() > 65536 {
368        return Err(invalid("args", "the arguments have at most 65536 bytes of JSON"));
369    }
370    let examples = canonical_examples(&e.examples)?;
371    if examples.len() > 65536 {
372        return Err(invalid("examples", "the examples have at most 65536 bytes of JSON"));
373    }
374    if let Some(s) = &e.signed_by {
375        if s.is_empty() || s.len() > 256 {
376            return Err(invalid("signed_by", "a key reference has 1 to 256 bytes"));
377        }
378    }
379    Ok(())
380}
381
382/// A catalogue entry with its facets and `extends`: the entry's bounds, then the facets' and
383/// `extends`' (CONTRACT-classes-round C2 and K9). Nothing is written before all of them pass.
384pub(crate) fn check_catalog_ext(e: &CatalogEntryExt) -> Result<()> {
385    check_catalog_entry(&e.entry)?;
386    check_facets(&e.facets)?;
387    check_extends(e.entry.kind, e.extends.as_deref())
388}
389
390/// Facets: a key of [`FACET_KEYS`], 1 to 8 names each, every name a name (2.2) of at most 32
391/// bytes, ascending and unique.
392pub(crate) fn check_facets(f: &Facets) -> Result<()> {
393    for (k, names) in f {
394        if !FACET_KEYS.contains(&k.as_str()) {
395            return Err(invalid("facets", format!("{k:?} is not a facet key")));
396        }
397        if names.is_empty() || names.len() > FACET_MAX {
398            return Err(invalid("facets", "a facet has 1 to 8 names"));
399        }
400        for n in names {
401            check_name(n, "facets")?;
402            if n.len() > 32 {
403                return Err(invalid("facets", "a facet name has at most 32 bytes"));
404            }
405        }
406        if names.windows(2).any(|w| w[0] >= w[1]) {
407            return Err(invalid("facets", "the names of a facet are ascending and unique"));
408        }
409    }
410    Ok(())
411}
412
413/// `extends`: a full function name (2.3), and only on a function.
414pub(crate) fn check_extends(kind: CatalogKind, extends: Option<&str>) -> Result<()> {
415    let Some(class) = extends else { return Ok(()) };
416    check_function_name(class, "extends")?;
417    if kind != CatalogKind::Function {
418        return Err(invalid("extends", "only a function extends a class"));
419    }
420    Ok(())
421}
422
423/// A dictionary's bounds (owner, key, values, labels, aliases).
424pub(crate) fn check_key_values(owner: &str, key: &str, values: &[KeyValue]) -> Result<()> {
425    check_function_name(owner, "owner")?;
426    check_name(key, "key")?;
427    for v in values {
428        if v.value.is_empty() || v.value.len() > 1024 {
429            return Err(invalid("value", "a value has 1 to 1024 bytes"));
430        }
431        if v.label.len() > 120 {
432            return Err(invalid("label", "a label has at most 120 bytes"));
433        }
434        for a in &v.aliases {
435            if a.is_empty() || a.len() > 120 {
436                return Err(invalid("aliases", "an alias has 1 to 120 bytes"));
437            }
438        }
439    }
440    Ok(())
441}
442
443pub(crate) fn check_model(model: &str) -> Result<()> {
444    if model.is_empty() || model.len() > 200 {
445        return Err(invalid("model", "a model name has 1 to 200 bytes"));
446    }
447    Ok(())
448}
449
450/// A vector's form for `vector`: 384 finite values, not all zero. Its text literal.
451pub(crate) fn vector_literal(v: &[f32]) -> Result<String> {
452    if v.len() != EMBED_DIM {
453        return Err(invalid("vec", format!("a vector has {EMBED_DIM} values, not {}", v.len())));
454    }
455    if v.iter().any(|x| !x.is_finite()) {
456        return Err(invalid("vec", "a vector's values are finite"));
457    }
458    if v.iter().all(|x| *x == 0.0) {
459        return Err(invalid("vec", "a vector is not all zero"));
460    }
461    let parts: Vec<String> = v.iter().map(|x| x.to_string()).collect();
462    Ok(format!("[{}]", parts.join(",")))
463}
464
465/// The text of a find miss as stored: trimmed, cut to 512 bytes on a character boundary;
466/// `None` when nothing is left.
467pub(crate) fn miss_text(query: &str) -> Option<&str> {
468    let q = query.trim();
469    if q.is_empty() {
470        return None;
471    }
472    let mut end = 0;
473    for (i, c) in q.char_indices() {
474        if i + c.len_utf8() > MISS_BYTES {
475            break;
476        }
477        end = i + c.len_utf8();
478    }
479    Some(&q[..end])
480}
481
482// ---- Canonical JSON of the stored columns -----------------------------------------------
483
484/// The arguments as canonical JSON (an object of strings).
485pub(crate) fn args_json(args: &BTreeMap<String, String>) -> String {
486    let members: Vec<(String, json::Value)> =
487        args.iter().map(|(k, v)| (k.clone(), json::Value::String(v.clone()))).collect();
488    String::from_utf8(json::Value::Object(members).to_jcs()).unwrap_or_default()
489}
490
491/// The arguments from their stored JSON.
492pub(crate) fn parse_args(text: &str) -> Result<BTreeMap<String, String>> {
493    let v = json::parse(text.as_bytes())?;
494    let members = v.as_object().ok_or_else(|| invalid("args", "stored arguments are not an object"))?;
495    let mut out = BTreeMap::new();
496    for (k, v) in members {
497        let s = v.as_str().ok_or_else(|| invalid("args", "stored argument text is not a string"))?;
498        out.insert(k.clone(), s.to_string());
499    }
500    Ok(out)
501}
502
503/// The facets as canonical JSON (an object of arrays of strings, keys ascending).
504pub(crate) fn facets_json(f: &Facets) -> String {
505    let members: Vec<(String, json::Value)> = f
506        .iter()
507        .map(|(k, names)| {
508            let items = names.iter().map(|n| json::Value::String(n.clone())).collect();
509            (k.clone(), json::Value::Array(items))
510        })
511        .collect();
512    String::from_utf8(json::Value::Object(members).to_jcs()).unwrap_or_default()
513}
514
515/// The facets from their stored JSON.
516pub(crate) fn parse_facets(text: &str) -> Result<Facets> {
517    let corrupt = || invalid("facets", "a stored entry has bad facets");
518    let v = json::parse(text.as_bytes())?;
519    let members = v.as_object().ok_or_else(corrupt)?;
520    let mut out = Facets::new();
521    for (k, v) in members {
522        let items = match v {
523            json::Value::Array(items) => items,
524            _ => return Err(corrupt()),
525        };
526        let names =
527            items.iter().map(|i| i.as_str().map(str::to_string).ok_or_else(corrupt)).collect::<Result<Vec<_>>>()?;
528        out.insert(k.clone(), names);
529    }
530    Ok(out)
531}
532
533/// A catalogue entry with its stored facets and `extends`.
534pub(crate) fn entry_ext(
535    entry: CatalogEntry,
536    facets: &str,
537    extends: Option<String>,
538    source_name: Option<String>,
539) -> Result<CatalogEntryExt> {
540    Ok(CatalogEntryExt { entry, facets: parse_facets(facets)?, extends, source_name })
541}
542
543/// The examples in canonical form; they must be a JSON array.
544pub(crate) fn canonical_examples(text: &str) -> Result<String> {
545    let v = json::parse(text.as_bytes())?;
546    if !matches!(v, json::Value::Array(_)) {
547        return Err(invalid("examples", "examples are a JSON array"));
548    }
549    Ok(String::from_utf8(v.to_jcs()).unwrap_or_default())
550}
551
552/// The aliases as canonical JSON (an array of strings), for SQLite.
553#[cfg(feature = "sqlite")]
554pub(crate) fn aliases_json(aliases: &[String]) -> String {
555    let items: Vec<json::Value> = aliases.iter().map(|a| json::Value::String(a.clone())).collect();
556    String::from_utf8(json::Value::Array(items).to_jcs()).unwrap_or_default()
557}
558
559/// The aliases from their stored JSON, for SQLite.
560#[cfg(feature = "sqlite")]
561pub(crate) fn parse_aliases(text: &str) -> Result<Vec<String>> {
562    let v = json::parse(text.as_bytes())?;
563    let items = match &v {
564        json::Value::Array(items) => items,
565        _ => return Err(invalid("aliases", "stored aliases are not an array")),
566    };
567    items
568        .iter()
569        .map(|i| i.as_str().map(str::to_string).ok_or_else(|| invalid("aliases", "a stored alias is not a string")))
570        .collect()
571}
572
573/// An entry from its stored columns.
574#[allow(clippy::too_many_arguments)]
575pub(crate) fn entry_from_columns(
576    kind: &str,
577    name: String,
578    hash: Option<String>,
579    label: String,
580    description: String,
581    args: &str,
582    examples: &str,
583    source: &str,
584    signed_by: Option<String>,
585) -> Result<CatalogEntry> {
586    let corrupt = |what: &str| invalid("catalog", format!("a stored entry has a bad {what}"));
587    Ok(CatalogEntry {
588        kind: CatalogKind::parse(kind).ok_or_else(|| corrupt("kind"))?,
589        name,
590        hash,
591        label,
592        description,
593        args: parse_args(args)?,
594        examples: examples.to_string(),
595        source: CatalogSource::parse(source).ok_or_else(|| corrupt("source"))?,
596        signed_by,
597    })
598}
599
600// ---- The text of embeddings -------------------------------------------------------------
601
602/// The text of an entry to embed.
603pub(crate) fn entry_text(label: &str, description: &str) -> String {
604    if label.is_empty() {
605        description.to_string()
606    } else {
607        format!("{label}. {description}")
608    }
609}
610
611/// The text of a value to embed.
612pub(crate) fn value_text(label: &str, value: &str) -> String {
613    if label.is_empty() {
614        value.to_string()
615    } else {
616        label.to_string()
617    }
618}
619
620// ---- Text search -----------------------------------------------------------------------
621
622/// The words of a text query, lower-cased; `None` when there are none (a blank query finds
623/// nothing).
624pub(crate) struct Words {
625    words: Vec<String>,
626}
627
628impl Words {
629    pub(crate) fn new(query: &str) -> Option<Words> {
630        let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
631        if words.is_empty() {
632            None
633        } else {
634            Some(Words { words })
635        }
636    }
637
638    /// The LIKE pattern of word `i` for an SQL prefilter, or `None` when the SQL cannot
639    /// match it exactly, and the rows are read and matched here instead. `sql_exact` says
640    /// whether a word is safe for the backend's LIKE: no `"` or `\` (JSON text escapes them),
641    /// no control characters, and (SQLite, whose LIKE folds ASCII only) ASCII letters only.
642    pub(crate) fn pattern(&self, i: usize, sql_exact: impl Fn(&str) -> bool) -> Option<String> {
643        let w = &self.words[i];
644        if !sql_exact(w) {
645            return None;
646        }
647        let mut escaped = String::with_capacity(w.len() + 2);
648        escaped.push('%');
649        for c in w.chars() {
650            if matches!(c, '!' | '%' | '_') {
651                escaped.push('!');
652            }
653            escaped.push(c);
654        }
655        escaped.push('%');
656        Some(escaped)
657    }
658
659    pub(crate) fn len(&self) -> usize {
660        self.words.len()
661    }
662
663    /// The words, lower-cased, as the text search matches them.
664    pub(crate) fn words(&self) -> &[String] {
665        &self.words
666    }
667
668    /// The total of a row with these fields, in tens (see [`field_score`]), or `None` when a
669    /// word is in none of them: the sum of each word's best field. An integer, so the order
670    /// of the search is exact and the same as the SQL's.
671    #[cfg(feature = "sqlite")]
672    pub(crate) fn total(&self, fields: &[&str]) -> Option<u32> {
673        let fields: Vec<String> = fields.iter().map(|f| f.to_lowercase()).collect();
674        let mut total = 0;
675        for w in &self.words {
676            let best = fields.iter().map(|f| field_score(f, w)).max().unwrap_or(0);
677            if best == 0 {
678                return None;
679            }
680            total += best;
681        }
682        Some(total)
683    }
684
685    /// The score of a total ([`Words::total`]): the mean of the words' best scores.
686    pub(crate) fn score_of(&self, total: u32) -> f64 {
687        f64::from(total) / (10.0 * self.words.len() as f64)
688    }
689}
690
691#[cfg(feature = "sqlite")]
692/// How well a lower-cased field matches a lower-cased word, in tens: the whole field (10), one
693/// of its words (split on anything but letters and digits: 8), inside it (5), or not at all
694/// (0). The SQL of migration 12 computes the same.
695pub(crate) fn field_score(field: &str, word: &str) -> u32 {
696    if field == word {
697        10
698    } else if field.split(|c: char| !c.is_alphanumeric()).any(|p| p == word) {
699        8
700    } else if field.contains(word) {
701        5
702    } else {
703        0
704    }
705}
706
707/// Hits in rank order: by score (highest first), then by name (entries) or owner, key and
708/// value (values), so equal scores always come in the same order; at most `limit`.
709pub(crate) fn rank(mut hits: Vec<Hit>, limit: usize) -> Vec<Hit> {
710    fn key(h: &Hit) -> String {
711        match h {
712            Hit::Entry { entry, .. } => entry.name.clone(),
713            Hit::Value { owner, key, value, .. } => format!("{owner}\u{1}{key}\u{1}{value}"),
714        }
715    }
716    fn score(h: &Hit) -> f64 {
717        match h {
718            Hit::Entry { score, .. } | Hit::Value { score, .. } => *score,
719        }
720    }
721    hits.sort_by(|a, b| {
722        score(b).partial_cmp(&score(a)).unwrap_or(std::cmp::Ordering::Equal).then_with(|| key(a).cmp(&key(b)))
723    });
724    hits.truncate(limit);
725    hits
726}
727
728/// A count or limit as the database's integer.
729pub(crate) fn as_i64(n: usize) -> i64 {
730    i64::try_from(n).unwrap_or(i64::MAX)
731}