//! `packages/store/__tests__/search.test.ts`, ported. //! //! Search has to survive being fed whatever someone types, which includes the //! characters FTS5 treats as query syntax. use super::*; use crate::fold::fold_ops; use crate::protocol::hlc::next_hlc; use crate::mint::Change; use crate::protocol::types::CottonOp; use crate::test_support::{seeded_file, WORKSPACE as WS}; use serde_json::{json, Value as JsonValue}; const NOW: &str = "2026-08-22T10:30:00.000Z"; const DEVICE: &str = "device:a"; /// Receipts as `mint` would make them, stamped in order on one clock. struct Ops { n: i64, scratch: Driver, } impl Ops { fn new() -> Ops { Ops { n: 0, scratch: seeded_file(DEVICE) } } fn at(&mut self, change: Change, ms: i64) -> CottonOp { self.n += 1; crate::wire::op_of_change( &self.scratch, &change, &next_hlc(DEVICE, None, ms).expect("a stamp in range"), DEVICE, &crate::fixtures::fixture_actor(), format!("op-{}", self.n), ) .expect("a receipt") } /// The row's create. fn upsert(&mut self, table: &str, row_id: &str, patch: JsonValue) -> CottonOp { let mut full = json!({ "id": row_id }); let object = full.as_object_mut().expect("an object"); for (key, value) in patch.as_object().expect("a patch object") { object.insert(key.clone(), value.clone()); } let ms = 1_700_000_000_000 + self.n + 1; self.at(Change::create(table, row_id, full.as_object().cloned().expect("an object")), ms) } fn note(&mut self, id: &str, title: &str, body: &str) -> CottonOp { self.upsert( "cotton_notes", id, json!({ "workspace_id": WS, "title": title, "body": body, "kind": "note", "created_at": NOW, "updated_at": NOW, }), ) } } fn seeded() -> Driver { seeded_file(DEVICE) } fn hits(db: &Driver, query: &str) -> Vec { search_all(db, query, None, None).expect("searches") } fn row_ids(hits: &[SearchHit]) -> Vec { hits.iter().map(|hit| hit.row_id.clone()).collect() } #[test] fn finds_a_row_written_through_the_fold() { let db = seeded(); let mut ops = Ops::new(); fold_ops( &db, &[ops.note("n1", "Cotton architecture", "one file per life")], ) .expect("folds"); let found = hits(&db, "architecture"); assert_eq!(found.len(), 1); assert_eq!(found[0].table, "cotton_notes"); assert_eq!(found[0].row_id, "n1"); } #[test] fn matches_on_body_as_well_as_title() { let db = seeded(); let mut ops = Ops::new(); fold_ops( &db, &[ops.note("n1", "Unrelated", "the sqlite file is the architecture")], ) .expect("folds"); assert_eq!(row_ids(&hits(&db, "sqlite")), ["n1"]); } #[test] fn re_indexes_when_a_row_is_updated() { let db = seeded(); let mut ops = Ops::new(); fold_ops(&db, &[ops.note("n1", "First title", "first body")]).expect("folds"); assert_eq!(hits(&db, "first").len(), 1); let edit = ops.at( Change::update( "cotton_notes", "n1", json!({"title": "Second title", "body": "second body"}).as_object().cloned().expect("an object"), ), 1_700_000_900_000, ); fold_ops(&db, &[edit]).expect("folds"); assert_eq!(hits(&db, "first").len(), 0); assert_eq!(hits(&db, "second").len(), 1); } #[test] fn drops_a_row_from_the_index_when_it_is_deleted() { let db = seeded(); let mut ops = Ops::new(); fold_ops(&db, &[ops.note("n1", "Ephemeral", "here today")]).expect("folds"); assert_eq!(hits(&db, "ephemeral").len(), 1); fold_ops( &db, &[ops.at(Change::retract("cotton_notes", "n1"), 1_700_000_900_000)], ) .expect("folds"); assert_eq!(hits(&db, "ephemeral").len(), 0); } #[test] fn ranks_a_title_hit_above_a_body_only_hit() { let db = seeded(); let mut ops = Ops::new(); fold_ops( &db, &[ ops.note( "n1", "Something else", "a passing mention of cotton in the body", ), ops.note("n2", "Cotton", "unrelated body text"), ], ) .expect("folds"); assert_eq!(row_ids(&hits(&db, "cotton")), ["n2", "n1"]); } #[test] fn searches_across_every_indexed_table_at_once() { let db = seeded(); let mut ops = Ops::new(); fold_ops( &db, &[ ops.note("n1", "Falkenstein notes", "the archive"), ops.upsert( "cotton_todos", "t1", json!({ "workspace_id": WS, "title": "Move Falkenstein backups", "created_at": NOW, "updated_at": NOW, }), ), ops.upsert( "cotton_people", "p1", json!({ "workspace_id": WS, "full_name": "Someone", "org": "Falkenstein GmbH", "created_at": NOW, "updated_at": NOW, }), ), ], ) .expect("folds"); let mut tables: Vec = hits(&db, "falkenstein") .into_iter() .map(|hit| hit.table) .collect(); tables.sort(); tables.dedup(); assert_eq!(tables, ["cotton_notes", "cotton_people", "cotton_todos"]); } #[test] fn honours_a_table_filter() { let db = seeded(); let mut ops = Ops::new(); fold_ops( &db, &[ ops.note("n1", "shared word", "x"), ops.upsert( "cotton_todos", "t1", json!({ "workspace_id": WS, "title": "shared word", "created_at": NOW, "updated_at": NOW, }), ), ], ) .expect("folds"); let filtered = search_all(&db, "shared", Some(&["cotton_todos".to_string()]), None).expect("searches"); assert_eq!( filtered .iter() .map(|hit| hit.table.as_str()) .collect::>(), ["cotton_todos"] ); } #[test] fn honours_a_limit() { let db = seeded(); let mut ops = Ops::new(); let batch: Vec = (0..12) .map(|n| ops.note(&format!("n{n}"), &format!("Note {n}"), "common term")) .collect(); fold_ops(&db, &batch).expect("folds"); assert_eq!( search_all(&db, "common", None, Some(5)) .expect("searches") .len(), 5 ); } #[test] fn returns_a_snippet_around_the_match() { let db = seeded(); let mut ops = Ops::new(); fold_ops( &db, &[ops.note( "n1", "Title", "a long body that mentions litestream in the middle of it", )], ) .expect("folds"); let found = hits(&db, "litestream"); assert!( found[0].snippet.to_lowercase().contains("litestream"), "got {}", found[0].snippet ); } #[test] fn survives_fts5_syntax_typed_by_a_human() { // These are all things a person might paste into a search box. None may // fail, and none may be interpreted as query operators. let db = seeded(); let mut ops = Ops::new(); fold_ops( &db, &[ops.note("n1", "Quarterly report", "she said \"hello\" and left")], ) .expect("folds"); for query in [ "\"", "\"unterminated", "NEAR(", "a OR b", "*", "^caret", "-minus", "col:value", "trailing*", "(unbalanced", "'apostrophe", "", " ", ] { search_all(&db, query, None, None) .unwrap_or_else(|error| panic!("{query:?} raised {error}")); } } #[test] fn treats_a_quoted_phrase_as_literal_text_not_an_operator() { let db = seeded(); let mut ops = Ops::new(); fold_ops(&db, &[ops.note("n1", "Report", "she said hello and left")]).expect("folds"); search_all(&db, "\"hello", None, None).expect("a stray quote is not an operator"); assert_eq!(hits(&db, "hello").len(), 1); } /// RULE: A search box finds a word written with a hyphen or an apostrophe as it was typed — "Stand-up", "O'Brien" — because the index breaks the word there, so the query breaks it the same way. #[test] fn finds_a_hyphenated_word_as_it_was_typed() { let db = seeded(); let mut ops = Ops::new(); fold_ops(&db, &[ops.note("n1", "Stand-up", "with O'Brien")]).expect("folds"); assert_eq!(row_ids(&hits(&db, "Stand-up")), vec!["n1".to_string()]); assert_eq!(row_ids(&hits(&db, "stand-up")), vec!["n1".to_string()]); assert_eq!(row_ids(&hits(&db, "O'Brien")), vec!["n1".to_string()]); } #[test] fn finds_nothing_for_a_term_that_is_not_there_without_erroring() { let db = seeded(); let mut ops = Ops::new(); fold_ops(&db, &[ops.note("n1", "Title", "body")]).expect("folds"); assert_eq!(hits(&db, "nonexistentterm"), vec![]); } #[test] fn indexes_documents_and_meetings_too() { let db = seeded(); let mut ops = Ops::new(); fold_ops( &db, &[ ops.upsert( "cotton_documents", "d1", json!({ "workspace_id": WS, "title": "Quillby invoice", "original_name": "inv.pdf", "mime": "application/pdf", "byte_size": 10, "sha256": "b".repeat(64), "storage_path": format!("{WS}/d1.pdf"), "status": "ready", "status_changed_at": NOW, "issuer": "Quillby Transport", "created_at": NOW, "updated_at": NOW, }), ), ops.upsert( "cotton_meetings", "m1", json!({ "workspace_id": WS, "title": "Standup with Subash", "status": "ready", "source": "recorded", "status_changed_at": NOW, "started_at": NOW, "created_at": NOW, "updated_at": NOW, }), ), ], ) .expect("folds"); assert!(hits(&db, "quillby") .iter() .any(|hit| hit.table == "cotton_documents")); assert!(hits(&db, "subash") .iter() .any(|hit| hit.table == "cotton_meetings")); } // ───────────────────────────────────────────────────────────────────────────── // to_match_query // ───────────────────────────────────────────────────────────────────────────── #[test] fn a_typed_search_reads_its_last_word_as_a_prefix() { assert_eq!(to_typed_match_query("dent"), Some("\"dent\"*".to_string())); assert_eq!(to_typed_match_query("dinner at o"), Some("\"dinner\" \"at\" \"o\"*".to_string())); assert_eq!(to_typed_match_query("dent*"), Some("\"dent\"*".to_string())); assert_eq!(to_typed_match_query(" "), None); } #[test] fn every_token_becomes_a_quoted_literal_and_the_operator_between_them_is_and() { assert_eq!(to_match_query("hello"), Some("\"hello\"".to_string())); assert_eq!( to_match_query("two words"), Some("\"two\" \"words\"".to_string()) ); } #[test] fn the_operator_characters_break_the_word_rather_than_being_escaped() { assert_eq!(to_match_query("^caret"), Some("\"caret\"".to_string())); assert_eq!( to_match_query("col:value"), Some("\"col\" \"value\"".to_string()) ); assert_eq!( to_match_query("trailing*"), Some("\"trailing\"".to_string()) ); assert_eq!(to_match_query("-minus"), Some("\"minus\"".to_string())); assert_eq!( to_match_query("(unbalanced"), Some("\"unbalanced\"".to_string()) ); assert_eq!( to_match_query("'apostrophe"), Some("\"apostrophe\"".to_string()) ); } #[test] fn nothing_left_after_stripping_is_nothing_to_search_for() { assert_eq!(to_match_query(""), None); assert_eq!(to_match_query(" "), None); assert_eq!(to_match_query("\""), None); assert_eq!(to_match_query("*"), None); assert_eq!(to_match_query("()"), None); // Tabs and newlines are whitespace to the splitter, exactly as `\s+` is. assert_eq!(to_match_query("\t\n "), None); } #[test] fn leading_and_trailing_whitespace_produce_no_empty_tokens() { assert_eq!(to_match_query(" hello "), Some("\"hello\"".to_string())); assert_eq!( to_match_query("\thello\nworld "), Some("\"hello\" \"world\"".to_string()) ); }