use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::Duration;
use serde::Deserialize;
use serde::de::IgnoredAny;
use serde_json::{Value, json};
use super::TableIndex;
use crate::search::{self, Status, eq};
use crate::sql::Database;
use crate::{Error, ErrorKind, Options, Store, sql};
const ARTICLES: &str = "create table articles (
id integer primary key,
title text not null,
body text not null default '',
category text,
done integer not null default 0,
views integer not null default 0,
embedding blob
)";
#[derive(Clone, Debug, PartialEq, Deserialize)]
struct Article {
id: i64,
title: String,
body: String,
category: Option<String>,
done: bool,
}
struct Fixture {
store: Store,
db: Database,
dir: tempfile::TempDir,
}
fn fixture() -> Fixture {
let dir = tempfile::tempdir().unwrap();
let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
let db = store.database("app").migrations([("0001_articles.sql", ARTICLES)]).open().unwrap();
Fixture { dir, store, db }
}
impl Fixture {
fn articles(&self) -> TableIndex<Article> {
let opened = self.db.search_index::<Article>("articles_search").table("articles");
let opened = opened.field("title", 2.0).field("body", 1.0).filters(["category", "done"]).open().unwrap();
self.ready(&opened);
opened
}
fn ready<T: serde::de::DeserializeOwned>(&self, index: &TableIndex<T>) {
search::maintain(&self.store).unwrap();
index.ready().unwrap();
}
fn insert(&self, id: i64, title: &str, body: &str) {
self.db.exec(sql!("insert into articles (id, title, body) values (?, ?, ?)", id, title, body)).unwrap();
}
fn beside(&self) -> rusqlite::Connection {
let beside = rusqlite::Connection::open(self.dir.path().join("sql").join("app.db")).unwrap();
beside.busy_timeout(Duration::from_secs(5)).unwrap();
beside
}
}
fn ids<T>(found: &search::Found<T>) -> Vec<&str> {
found.hits.iter().map(|hit| hit.id.as_str()).collect()
}
fn floats(values: &[f32]) -> Vec<u8> {
values.iter().flat_map(|value| value.to_le_bytes()).collect()
}
#[test]
fn every_way_a_row_changes_reaches_its_index_and_a_hit_is_the_row() {
let f = fixture();
f.insert(1, "Sourdough bread", "flour, water and salt");
let articles = f.articles();
let found = articles.search("bread").run().unwrap();
assert_eq!(ids(&found), ["1"], "a row the table held before the index read in the background");
assert_eq!(found.hits[0].value.title, "Sourdough bread", "a hit's value is its row");
f.insert(2, "Rye", "bread from rye flour");
assert_eq!(ids(&articles.search("bread").run().unwrap()), ["1", "2"], "the next search sees an insert");
f.db.exec(sql!("update articles set title = 'Butter' where id = 1")).unwrap();
assert!(articles.search("sourdough").run().unwrap().hits.is_empty(), "an update takes the old words out");
assert_eq!(ids(&articles.search("butter").run().unwrap()), ["1"]);
f.db.batch([
sql!("insert into articles (id, title) values (3, 'Milk')"),
sql!("delete from articles where id = 2"),
])
.unwrap();
f.db.tx(|tx| -> crate::Result<()> {
tx.exec(sql!("insert into articles (id, title, category) values (4, 'Cream', 'dairy')"))?;
tx.exec(sql!("update articles set done = 1, category = 'dairy' where id = 3"))?;
Ok(())
})
.unwrap();
assert!(articles.search("rye").run().unwrap().hits.is_empty(), "a delete in a batch");
assert_eq!(ids(&articles.search("milk cream").run().unwrap()).len(), 2, "rows of a transaction");
let done = articles.search("milk cream").filter(eq("done", &true)).run().unwrap();
assert_eq!(ids(&done), ["3"], "a boolean passes the integer SQLite keeps it as");
let dairy = articles.search("milk cream").filter(eq("category", "dairy")).run().unwrap();
assert_eq!(dairy.hits.len(), 2);
assert!(dairy.hits.iter().all(|hit| hit.value.category.as_deref() == Some("dairy")));
}
#[test]
fn a_tables_index_reads_a_word_typed_with_the_other_layout_on_in_its_layouts() {
let f = fixture();
f.insert(1, "Хлеб на закваске", "мука, вода и соль");
let opened = f.db.search_index::<Article>("articles_search").table("articles").field("title", 2.0);
let articles = opened.field("body", 1.0).layouts(["ru", "en"]).open().unwrap();
f.ready(&articles);
let found = articles.search("[kt,").run().unwrap();
assert_eq!((ids(&found), found.corrected.as_deref()), (vec!["1"], Some("хлеб")));
}
#[test]
fn a_search_in_the_transaction_that_wrote_sees_its_writes() {
let f = fixture();
let articles = f.articles();
let found =
f.db.tx(|tx| -> crate::Result<Vec<String>> {
tx.exec(sql!("insert into articles (id, title) values (1, 'inside')"))?;
let found = tx.with(&articles).search("inside").run()?;
Ok(found.hits.into_iter().map(|hit| hit.id).collect())
})
.unwrap();
assert_eq!(found, ["1"]);
let around = f.db.tx(|_| articles.search("inside").run().map(drop)).unwrap_err();
assert_eq!(around.kind(), ErrorKind::Invalid, "a search beside the transaction would not see its writes");
}
#[test]
fn a_hit_says_where_its_columns_matched_as_its_row_holds_them_inside_a_transaction_too() {
let f = fixture();
let articles = f.articles();
f.insert(1, "Ёлки и ЁЛКА", "a forest of firs");
let shown = |found: search::Found<Article>| -> Vec<(String, String)> {
let hit = &found.hits[0];
let text = |column: &str| if column == "title" { &hit.value.title } else { &hit.value.body };
hit.matches.iter().map(|found| (found.field.clone(), text(&found.field)[found.at.clone()].to_owned())).collect()
};
let pair = |column: &str, text: &str| (column.to_owned(), text.to_owned());
let found = articles.search("елка forest").matches().run().unwrap();
assert_eq!(shown(found), [pair("title", "Ёлки"), pair("title", "ЁЛКА"), pair("body", "forest")]);
let inside = f.db.tx(|tx| {
tx.exec(sql!("update articles set title = 'Ёлочка и ёлка' where id = 1"))?;
tx.with(&articles).search("елка").matches().run()
});
assert_eq!(shown(inside.unwrap()), [pair("title", "ёлка")], "the row as the transaction wrote it");
}
#[test]
fn a_search_in_a_transaction_goes_on_while_a_switch_of_its_index_waits_for_that_transaction() {
let f = fixture();
let titles = f.db.search_index::<Article>("articles_search").table("articles").field("title", 1.0).open().unwrap();
f.ready(&titles);
f.insert(1, "bread", "salt");
let both = f.db.search_index::<Article>("articles_search").table("articles");
let both = both.field("title", 1.0).field("body", 1.0).open().unwrap();
assert!(matches!(both.status().unwrap(), Status::Rebuilding { .. }));
let (answer, answered) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let f = f;
let searched = f.db.tx(|tx| -> crate::Result<_> {
tx.exec(sql!("insert into articles (id, title) values (2, 'fresh bread')"))?;
let (search, open) = (Arc::clone(&both.inner().search), Arc::clone(&both.inner().open));
let switch = std::thread::spawn(move || search.rebuild(&open));
while !both.inner().open.changing() {
assert!(!switch.is_finished(), "the switch ended before it held the index");
std::thread::yield_now();
}
let found = tx.with(&both).search("fresh").run()?;
Ok((ids(&found).join(" "), switch))
});
let searched = searched.and_then(|(found, switch)| switch.join().unwrap().map(|()| found));
let switched = both.search("salt").run().map(|found| ids(&found).join(" "));
answer.send((searched, switched)).unwrap();
});
let waited = "the search waited for the switch, which waited for the search's transaction";
let (searched, switched) = answered.recv_timeout(Duration::from_secs(30)).expect(waited);
assert_eq!(searched.unwrap(), "2", "the search saw its transaction's write");
assert_eq!(switched.unwrap(), "1", "the switch went on once the transaction committed");
}
#[test]
fn a_status_asked_inside_a_transaction_is_refused_while_a_switch_waits_for_that_transaction() {
let f = fixture();
let titles = f.db.search_index::<Article>("articles_search").table("articles").field("title", 1.0).open().unwrap();
f.ready(&titles);
f.insert(1, "bread", "salt");
let both = f.db.search_index::<Article>("articles_search").table("articles");
let both = both.field("title", 1.0).field("body", 1.0).open().unwrap();
let (answer, answered) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let f = f;
let asked = f.db.tx(|_| -> crate::Result<_> {
let (search, open) = (Arc::clone(&both.inner().search), Arc::clone(&both.inner().open));
let switch = std::thread::spawn(move || search.rebuild(&open));
while !both.inner().open.changing() {
assert!(!switch.is_finished(), "the switch ended before it held the index");
std::thread::yield_now();
}
Ok((both.status().map(drop), switch))
});
let asked = asked.and_then(|(status, switch)| switch.join().unwrap().map(|()| status));
answer.send(asked).unwrap();
});
let waited = "the status waited for the switch, which waited for the status's transaction";
let status = answered.recv_timeout(Duration::from_secs(30)).expect(waited).unwrap();
assert_eq!(status.unwrap_err().kind(), ErrorKind::Invalid, "a read inside a transaction of its file");
}
#[test]
fn a_search_in_a_transaction_that_rolls_back_leaves_later_searches_what_committed() {
let f = fixture();
let articles = f.articles();
f.insert(1, "bread", "");
f.insert(2, "bread", "");
search::maintain(&f.store).unwrap();
let rolled: crate::Result<()> = f.db.tx(|tx| {
tx.exec(sql!("update articles set title = 'bread zebrafish' where id = 1"))?;
let found = tx.with(&articles).search("bread zebrafisj").run()?;
assert_eq!(found.corrected.as_deref(), Some("bread zebrafish"), "the transaction's own word");
Err(Error::invalid("changed its mind"))
});
assert!(rolled.is_err());
f.db.exec(sql!("delete from articles where id = 2")).unwrap();
f.insert(3, "quokkas", "");
let corrected = articles.search("quokkaz").run().unwrap();
assert_eq!(corrected.corrected.as_deref(), Some("quokkas"), "a word committed after the rollback");
assert_eq!(ids(&articles.search("bread").run().unwrap()), ["1"], "the row the rollback kept, not the one deleted");
}
#[test]
fn a_drop_refused_inside_a_transaction_leaves_the_index_as_it_was() {
let f = fixture();
let articles = f.articles();
f.insert(1, "bread", "");
let refused = f.db.tx(|_| f.db.drop_search_index("articles_search")).unwrap_err();
assert_eq!(refused.kind(), ErrorKind::Invalid, "{refused}");
assert_eq!(ids(&articles.search("bread").run().unwrap()), ["1"], "a handle searches as before");
f.insert(2, "rye", "");
assert_eq!(ids(&articles.search("rye").run().unwrap()), ["2"], "the triggers follow the table as before");
assert!(f.db.drop_search_index("articles_search").unwrap());
}
#[test]
fn a_write_that_rolls_back_changes_neither_the_table_nor_its_index() {
let f = fixture();
let articles = f.articles();
f.insert(1, "kept", "");
let rolled: crate::Result<()> = f.db.tx(|tx| {
tx.exec(sql!("insert into articles (id, title) values (2, 'ghost words')"))?;
tx.exec(sql!("update articles set title = 'gone' where id = 1"))?;
Err(Error::invalid("changed its mind"))
});
assert!(rolled.is_err());
assert!(articles.search("ghost gone").run().unwrap().hits.is_empty());
assert_eq!(ids(&articles.search("kept").run().unwrap()), ["1"]);
let refused = f.db.exec(sql!("insert into articles (id, title) values (1, 'twice')")).unwrap_err();
assert_eq!(refused.kind(), ErrorKind::Conflict);
assert!(articles.search("twice").run().unwrap().hits.is_empty(), "a write that failed in its savepoint");
}
#[test]
fn a_row_whose_vector_does_not_read_fails_its_write_and_one_beside_the_store_is_left_out() {
let f = fixture();
let opened = f.db.search_index::<Article>("by_meaning").table("articles").field("title", 1.0);
let index = opened.vectors("embedding", 3).open().unwrap();
f.ready(&index);
let insert = |id: i64, title: &str, embedding: Option<Vec<u8>>| {
f.db.exec(sql!("insert into articles (id, title, embedding) values (?, ?, ?)", id, title, embedding))
};
insert(1, "red shoes", Some(floats(&[1.0, 0.0, 0.0]))).unwrap();
insert(2, "blue shoes", None).unwrap();
let ragged = insert(3, "ragged", Some(vec![0; 5])).unwrap_err();
assert_eq!(ragged.kind(), ErrorKind::Invalid);
assert!(ragged.to_string().contains("embedding") && ragged.to_string().contains("row 3"), "{ragged}");
assert_eq!(insert(4, "not a number", Some(floats(&[f32::NAN, 0.0, 0.0]))).unwrap_err().kind(), ErrorKind::Invalid);
let held: i64 = f.db.scalar(sql!("select count(*) from articles where id in (3, 4)")).unwrap();
assert_eq!(held, 0, "the rows failed with their vectors");
assert_eq!(ids(&index.search_vector(&[1.0, 0.1, 0.0]).run().unwrap()), ["1"], "a row of none is not found by one");
assert_eq!(ids(&index.search("shoes").run().unwrap()), ["1", "2"]);
f.beside().execute("insert into articles (id, title, embedding) values (5, 'beside', x'00')", []).unwrap();
insert(6, "after", None).unwrap();
assert!(index.search("beside").run().unwrap().hits.is_empty(), "left out, and the store's write went on");
assert_eq!(ids(&index.search("after").run().unwrap()), ["6"]);
}
#[test]
fn a_write_from_beside_the_store_reaches_the_index_at_the_store_s_next_write() {
let f = fixture();
let articles = f.articles();
f.insert(1, "first", "");
let beside = f.beside();
beside.execute("insert into articles (id, title) values (2, 'outside words')", []).unwrap();
beside.execute("update articles set title = 'changed outside' where id = 1", []).unwrap();
assert!(articles.search("outside").run().unwrap().hits.is_empty(), "waiting among the pending keys");
f.db.exec(sql!("update articles set views = views + 1 where id = 2")).unwrap();
let found = articles.search("outside").run().unwrap();
assert_eq!(ids(&found), ["2", "1"], "equal scores, in the order the keys were left");
assert!(articles.search("first").run().unwrap().hits.is_empty());
}
#[test]
fn keys_left_from_beside_the_store_for_a_table_it_then_renamed_hold_up_no_write_and_no_drop() {
let f = fixture();
let articles = f.articles();
f.insert(1, "bread", "");
f.beside().execute_batch("delete from articles where id = 1; alter table articles rename to posts;").unwrap();
f.db.exec(sql!("create table notes (id integer primary key, body text)")).unwrap();
f.db.exec(sql!("insert into notes (body) values ('after')")).unwrap();
let renamed = f.db.exec(sql!("insert into posts (id, title) values (2, 'rye')")).unwrap_err();
assert_eq!(renamed.kind(), ErrorKind::Invalid, "{renamed}");
assert!(renamed.to_string().contains("index articles_search"), "{renamed}");
assert!(f.db.drop_search_index("articles_search").unwrap());
let pending: i64 = f.db.scalar(sql!("select count(*) from _tinystore_search_pending")).unwrap();
assert_eq!(pending, 0, "the drop took its keys with it");
f.db.exec(sql!("insert into posts (id, title) values (2, 'rye')")).unwrap();
assert_eq!(articles.search("bread").run().unwrap_err().kind(), ErrorKind::Invalid);
}
#[test]
fn a_row_written_while_no_process_had_its_index_open_reaches_it_at_its_next_open() {
let f = fixture();
drop(f.articles());
f.store.close().unwrap();
let store = Store::open(f.dir.path(), Options { background: false, ..Options::default() }).unwrap();
let db = store.database("app").open().unwrap();
db.exec(sql!("insert into articles (id, title) values (1, 'while closed')")).unwrap();
let articles = db.search_index::<Article>("articles_search").table("articles");
let articles = articles.field("title", 2.0).field("body", 1.0).filters(["category", "done"]).open().unwrap();
assert_eq!(ids(&articles.search("closed").run().unwrap()), ["1"]);
}
#[test]
fn a_table_s_index_follows_one_table_by_a_key_of_unique_values() {
let f = fixture();
f.db.exec(sql!("create table notes (slug text, body text)")).unwrap();
let opened = |builder: crate::search::TableIndexBuilder<Value>| builder.open().map(drop).unwrap_err().to_string();
let index = |name: &str| f.db.search_index::<Value>(name);
assert!(opened(index("n").field("body", 1.0)).contains("names its table"));
assert!(opened(index("n").table("nothing").field("body", 1.0)).contains("no table nothing"));
assert!(opened(index("n").table("articles").field("nope", 1.0)).contains("no column nope"));
assert!(opened(index("n").table("notes").field("body", 1.0)).contains("no primary key"));
assert!(opened(index("n").table("notes").key("slug").field("body", 1.0)).contains("no key"));
assert!(opened(index("n").table("articles").field("title.x", 1.0)).contains("reads columns"));
f.db.exec(sql!("create unique index notes_by_slug on notes (slug)")).unwrap();
let notes = index("n").table("notes").key("slug").field("body", 1.0).open().unwrap();
f.db.exec(sql!("insert into notes values ('a-note', 'hello')")).unwrap();
assert_eq!(ids(¬es.search("hello").run().unwrap()), ["a-note"], "a hit's id is its key as text");
let moved = index("n").table("articles").field("title", 1.0).open().unwrap();
assert!(matches!(moved.status().unwrap(), Status::Rebuilding { .. }), "another table is read beside");
}
const PAGES: &str = "create table pages (id integer primary key, slug text not null unique, body text not null)";
#[test]
fn a_row_a_replace_removed_leaves_its_index_once_a_search_meets_it_and_the_page_fills_past_it() {
let f = fixture();
f.db.exec(PAGES).unwrap();
let pages = f.db.search_index::<Value>("pages_search").table("pages").field("body", 1.0).open().unwrap();
f.ready(&pages);
let held = || -> i64 {
f.db.scalar(sql!("select documents from _tinystore_search_indexes where name = 'pages_search'")).unwrap()
};
let found = |text: &str, limit: usize| ids(&pages.search(text).limit(limit).run().unwrap()).join(" ");
f.db.exec(sql!("insert into pages (slug, body) values ('home', 'old words')")).unwrap();
f.db.exec(sql!("insert into pages (slug, body) values ('about', 'old words kept')")).unwrap();
f.db.exec(sql!("insert or replace into pages (slug, body) values ('home', 'new words')")).unwrap();
assert_eq!(held(), 3, "the removed row's document is still in the index");
assert_eq!(found("old", 1), "2", "the page filled past the row gone, the shorter and first");
search::maintain(&f.store).unwrap();
assert_eq!(held(), 2, "the document of the row gone left the index");
assert_eq!((found("old", 10), found("new", 10)), ("2".to_owned(), "3".to_owned()));
f.db.exec(sql!("update or replace pages set slug = 'about' where id = 3")).unwrap();
assert_eq!(found("kept", 10), "", "row 2, which update or replace removed, answers nothing");
f.db.exec(sql!("insert into pages (id, slug, body) values (2, 'kept', 'kept again')")).unwrap();
search::maintain(&f.store).unwrap();
assert_eq!((found("again", 10), held()), ("2".to_owned(), 2), "a row back since a search met it gone stays");
f.db.exec(sql!("replace into pages (slug, body) values ('kept', 'replaced words')")).unwrap();
assert_eq!(found("again", 10), "", "row 2, which replace into removed, answers nothing");
search::maintain(&f.store).unwrap();
assert_eq!((found("replaced", 10), found("again", 10), held()), ("4".to_owned(), String::new(), 2));
}
#[test]
fn a_column_added_reads_the_table_again_beside_the_index_and_a_drop_takes_the_triggers_off() {
let f = fixture();
let titles = f.db.search_index::<Article>("articles_search").table("articles").field("title", 1.0).open().unwrap();
f.ready(&titles);
f.insert(1, "bread", "flour and salt");
let both = f.db.search_index::<Article>("articles_search").table("articles");
let both = both.field("title", 1.0).field("body", 1.0).open().unwrap();
assert!(matches!(both.status().unwrap(), Status::Rebuilding { .. }));
assert!(both.search("salt").run().unwrap().hits.is_empty(), "the old settings answer until the switch");
f.insert(2, "rye", "salt again");
f.ready(&both);
assert_eq!(ids(&both.search("salt").run().unwrap()), ["2", "1"], "the shorter body first");
assert!(f.db.drop_search_index("articles_search").unwrap());
let triggers: i64 = f.db.scalar(sql!("select count(*) from sqlite_schema where type = 'trigger'")).unwrap();
assert_eq!(triggers, 0);
f.insert(3, "after the drop", "");
assert_eq!(both.search("salt").run().unwrap_err().kind(), ErrorKind::Invalid);
let pending: i64 = f.db.scalar(sql!("select count(*) from _tinystore_search_pending")).unwrap();
assert_eq!(pending, 0);
}
#[test]
fn a_row_changed_while_its_index_is_read_again_reaches_the_new_rows_by_what_only_they_read() {
let f = fixture();
let titles = f.db.search_index::<Article>("articles_search").table("articles").field("title", 1.0).open().unwrap();
f.ready(&titles);
for id in 1..=3 {
f.insert(id, &format!("shoes {id}"), "");
}
let opened = f.db.search_index::<Article>("articles_search").table("articles").field("title", 1.0);
let both = opened.filters(["category"]).vectors("embedding", 3).open().unwrap();
assert!(matches!(both.status().unwrap(), Status::Rebuilding { .. }));
let search = Arc::clone(&both.inner().search);
assert!(!search.copy_step(&both.inner().open).unwrap(), "every row copied in one step");
let embedding = floats(&[1.0, 0.0, 0.0]);
f.db.exec(sql!("update articles set embedding = ?, category = 'red' where id = 2", embedding)).unwrap();
f.ready(&both);
assert_eq!(ids(&both.search_vector(&[1.0, 0.1, 0.0]).run().unwrap()), ["2"], "a vector only the new rows read");
let red = both.search("shoes").filter(eq("category", "red")).run().unwrap();
assert_eq!(ids(&red), ["2"], "a filter only the new rows read");
}
const DOCUMENTS: &str = "create table documents (id integer primary key, title text not null, attachment blob)";
#[test]
fn the_rows_of_a_table_index_s_hits_hold_the_store_s_memory_together() {
let dir = tempfile::tempdir().unwrap();
let options = Options { memory: Some(1 << 20), background: false, ..Options::default() };
let store = Store::open(dir.path(), options).unwrap();
let db = store.database("app").migrations([("0001_documents.sql", DOCUMENTS)]).open().unwrap();
let documents = db.search_index::<IgnoredAny>("documents_search").table("documents").field("title", 1.0);
let documents = documents.open().unwrap();
search::maintain(&store).unwrap();
for _ in 0..12 {
db.exec(sql!("insert into documents (title, attachment) values ('report', zeroblob(100000))")).unwrap();
}
assert_eq!(documents.search("report").limit(8).run().unwrap().hits.len(), 8);
assert_eq!(store.memory().used(), 0, "the rows' memory is given back with the search");
let past = documents.search("report").limit(12).run().unwrap_err();
assert_eq!((past.kind(), past.fact("limit")), (ErrorKind::Limit, Some("store memory")), "{past}");
}
#[test]
fn the_rows_of_a_table_index_s_hits_are_one_call_s_rows_within_its_bound() {
let f = fixture();
f.db.exec(DOCUMENTS).unwrap();
let documents = f.db.search_index::<IgnoredAny>("documents_search").table("documents").field("title", 1.0);
let documents = documents.open().unwrap();
f.ready(&documents);
let mebibytes = "with recursive n(at) as (select 1 union all select at + 1 from n where at < 65)
insert into documents (title, attachment) select 'report', zeroblob(1048576) from n";
f.db.exec(mebibytes).unwrap();
let past = documents.search("report").limit(65).run().unwrap_err();
let limit = (past.kind(), past.fact("limit"), past.fact("bound"));
assert_eq!(limit, (ErrorKind::Limit, Some("bytes of a call's rows"), Some("67108864")), "{past}");
}
const WORDS: [&str; 12] =
["bread", "salt", "flour", "rye", "milk", "cream", "butter", "honey", "tea", "jam", "oat", "corn"];
struct Steps(u64);
impl Steps {
fn next(&mut self, below: u64) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0 % below
}
fn words(&mut self, count: u64) -> String {
(0..1 + self.next(count)).map(|_| WORDS[self.next(WORDS.len() as u64) as usize]).collect::<Vec<_>>().join(" ")
}
}
#[test]
fn through_a_long_mix_of_writes_a_search_answers_what_an_index_made_afresh_of_the_rows_would() {
let f = fixture();
for id in 0..300 {
f.insert(id, &format!("{} {id}", WORDS[(id % 12) as usize]), "");
}
let opened = f.db.search_index::<Article>("articles_search").table("articles").field("title", 2.0);
let articles = opened.field("body", 1.0).filters(["category", "done"]).open().unwrap();
let search = std::sync::Arc::clone(&articles.inner().search);
assert!(!search.file_write(|tx| search.fill_step(tx, "articles_search")).unwrap(), "a first step of 256");
f.db.exec(sql!("update articles set body = 'honey jam' where id = 10")).unwrap();
f.db.exec(sql!("update articles set body = 'honey tea' where id = 290")).unwrap();
f.db.exec(sql!("delete from articles where id = 280")).unwrap();
f.ready(&articles);
same_as_afresh(&f, &articles, 0);
let mut steps = Steps(0x9e37_79b9_7f4a_7c15);
for round in 1..=6 {
for _ in 0..60 {
write_one(&f, &mut steps);
}
if round % 2 == 0 {
search::maintain(&f.store).unwrap();
}
same_as_afresh(&f, &articles, round);
}
}
fn write_one(f: &Fixture, steps: &mut Steps) {
let id = steps.next(400) as i64;
let (title, body) = (steps.words(3), steps.words(5));
let category = ["dairy", "bakery"][steps.next(2) as usize];
let upsert = sql!(
"insert into articles (id, title, body, category) values (?, ?, ?, ?)
on conflict (id) do update set title = excluded.title, body = excluded.body",
id,
title,
body,
category
);
match steps.next(6) {
0 => drop(f.db.exec(upsert).unwrap()),
1 => drop(f.db.exec(sql!("delete from articles where id = ?", id)).unwrap()),
2 => drop(f.db.batch([upsert, sql!("update articles set done = 1 - done where id = ?", id / 2)]).unwrap()),
3 => f.db.tx(|tx| tx.exec(upsert).map(drop)).unwrap(),
4 => drop(f.db.exec(sql!("update articles set views = views + 1 where id = ?", id)).unwrap()),
_ => {
let beside = f.beside();
beside.execute("delete from articles where id = ?1", [id]).unwrap();
beside.execute("insert into articles (id, title, body) values (?1, ?2, ?3)", (id, &title, &body)).unwrap();
f.db.exec(sql!("update articles set views = views where id = -1")).unwrap();
}
}
}
fn same_as_afresh(f: &Fixture, articles: &TableIndex<Article>, round: u32) {
let afresh = f.store.index::<Value>(&format!("afresh-{round}")).field("title", 2.0).field("body", 1.0);
let afresh = afresh.filters(["category", "done"]).open().unwrap();
let rows: Vec<Article> = f.db.all(sql!("select * from articles")).unwrap();
let documents: Vec<(String, Value)> = rows
.iter()
.map(|row| {
let document =
json!({ "title": row.title, "body": row.body, "category": row.category, "done": i64::from(row.done) });
(row.id.to_string(), document)
})
.collect();
for chunk in documents.chunks(500) {
afresh.set_many(chunk.iter().map(|(id, document)| (id.as_str(), document))).unwrap();
}
for word in WORDS {
let hits = |found: Vec<(String, f64)>| {
found.into_iter().map(|(id, score)| (id, score.to_bits())).collect::<BTreeSet<_>>()
};
let table = articles.search(word).limit(1000).run().unwrap().hits;
let made = afresh.search(word).limit(1000).run().unwrap().hits;
assert_eq!(
hits(table.into_iter().map(|hit| (hit.id, hit.score)).collect()),
hits(made.into_iter().map(|hit| (hit.id, hit.score)).collect()),
"round {round}: {word}"
);
let table = articles.search(word).filter(eq("done", &true)).limit(1000).run().unwrap();
let made = afresh.search(word).filter(eq("done", &1)).limit(1000).run().unwrap();
assert_eq!(ids(&table).into_iter().collect::<BTreeSet<_>>(), ids(&made).into_iter().collect(), "round {round}");
}
}
#[test]
fn a_write_from_beside_the_store_reaches_the_index_within_a_second_when_the_store_writes_nothing() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open(dir.path(), Options::default()).unwrap();
let db = store.database("app").migrations([("0001_articles.sql", ARTICLES)]).open().unwrap();
let articles = db.search_index::<Article>("articles_search").table("articles").field("title", 1.0).open().unwrap();
articles.ready().unwrap();
let beside = rusqlite::Connection::open(dir.path().join("sql").join("app.db")).unwrap();
beside.busy_timeout(Duration::from_secs(5)).unwrap();
beside.execute("insert into articles (id, title) values (1, 'outside words')", []).unwrap();
let written = std::time::Instant::now();
while articles.search("outside").run().unwrap().hits.is_empty() {
assert!(written.elapsed() < Duration::from_secs(5), "the index never read the row");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn a_column_a_migration_dropped_reads_as_empty_until_the_index_is_opened_without_it() {
let f = fixture();
let articles = f.db.search_index::<Value>("articles_search").table("articles").field("title", 2.0);
let articles = articles.field("body", 1.0).filters(["category", "done"]).open().unwrap();
f.ready(&articles);
f.insert(1, "bread", "salt");
f.db.exec(sql!("alter table articles drop column body")).unwrap();
f.db.exec(sql!("insert into articles (id, title) values (2, 'rye')")).unwrap();
f.db.exec(sql!("update articles set title = 'oat' where id = 1")).unwrap();
assert_eq!(ids(&articles.search("oat rye").run().unwrap()).len(), 2, "the table's writes go on");
assert!(articles.search("salt").run().unwrap().hits.is_empty(), "the dropped column read as empty");
let titles = f.db.search_index::<Value>("articles_search").table("articles").field("title", 2.0);
let titles = titles.filters(["category", "done"]).open().unwrap();
assert_eq!(ids(&titles.search("oat").run().unwrap()), ["1"]);
}
#[test]
fn a_table_a_migration_rebuilt_is_read_again_when_its_index_opens() {
let f = fixture();
drop(f.articles());
f.insert(1, "bread", "");
f.insert(2, "milk", "");
f.store.close().unwrap();
let rebuilt = "create table new_articles (
id integer primary key, title text not null, body text not null default '', category text,
done integer not null default 0, views integer not null default 0, embedding blob, extra text);
insert into new_articles (id, title) select id, title || ' rye' from articles where id != 2;
insert into new_articles (id, title) values (3, 'honey');
drop table articles;
alter table new_articles rename to articles;";
let store = Store::open(f.dir.path(), Options { background: false, ..Options::default() }).unwrap();
let migrations = [("0001_articles.sql", ARTICLES), ("0002_rebuilt.sql", rebuilt)];
let db = store.database("app").migrations(migrations).open().unwrap();
let triggers: i64 = db.scalar(sql!("select count(*) from sqlite_schema where type = 'trigger'")).unwrap();
assert_eq!(triggers, 0, "the triggers went with the old table");
let articles = db.search_index::<Article>("articles_search").table("articles");
let articles = articles.field("title", 2.0).field("body", 1.0).filters(["category", "done"]).open().unwrap();
assert!(matches!(articles.status().unwrap(), Status::Rebuilding { .. }));
search::maintain(&store).unwrap();
articles.ready().unwrap();
assert_eq!(ids(&articles.search("rye").run().unwrap()), ["1"], "a row the migration changed");
assert!(articles.search("milk").run().unwrap().hits.is_empty(), "a row the migration deleted");
assert_eq!(ids(&articles.search("honey").run().unwrap()), ["3"], "a row the migration added");
db.exec(sql!("insert into articles (id, title) values (4, 'after')")).unwrap();
assert_eq!(ids(&articles.search("after").run().unwrap()), ["4"], "the triggers are back");
}
#[test]
fn a_where_by_a_statement_answers_as_the_list_of_its_values_read_in_the_search_s_snapshot() {
let f = fixture();
let articles = f.articles();
f.db.exec("create table picks (article integer, category text)").unwrap();
for (id, category) in [(1, "news"), (2, "news"), (3, "sport"), (4, "news"), (5, "sport")] {
let insert = sql!("insert into articles (id, title, category) values (?, 'bread', ?)", id, category);
f.db.exec(insert).unwrap();
}
f.db.exec("insert into picks values (2, 'sport'), (4, null), (4, null), (9, 'news'), (null, null)").unwrap();
let found = |condition| ids(&articles.search("bread").filter(condition).limit(20).run().unwrap()).join(",");
let picked = sql!("select article from picks where article < ?", 100);
assert_eq!(found(search::is_in("id", picked.clone())), "2,4", "on the key, which no filter names");
assert_eq!(found(search::is_in("id", &picked)), "2,4", "a key of no row passes none, and a null none");
let categories = sql!("select category from picks");
assert_eq!(found(search::is_in("category", categories)), found(search::is_in("category", &["sport", "news"])));
assert_eq!(found(search::is_in("id", sql!("select article from picks where 0"))), "", "no rows pass none");
let both = search::and([search::is_in("id", sql!("select article from picks")), eq("category", "news")]);
assert_eq!(found(both), "2,4");
let inside =
f.db.tx(|tx| -> crate::Result<String> {
tx.exec("insert into picks values (5, null)")?;
let found = tx.with(&articles).search("bread").filter(search::is_in("id", &picked)).limit(20).run()?;
Ok(ids(&found).join(","))
})
.unwrap();
assert_eq!(inside, "2,4,5", "inside a transaction, its own writes");
let refused = |rows: sql::Sql| articles.search("bread").filter(search::is_in("id", rows)).run().unwrap_err();
let writes = refused(sql!("delete from picks returning article"));
assert!(writes.to_string().contains("this one writes"), "{writes}");
assert!(refused(sql!("select article, category from picks")).to_string().contains("gives 2"));
assert_eq!(refused(sql!("select article from picks where article = ?")).kind(), ErrorKind::Invalid);
assert_eq!(refused(sql!("pragma journal_mode = delete")).kind(), ErrorKind::Invalid);
let blob = articles.search("bread").filter(search::is_in("category", sql!("select x'00'"))).run().unwrap_err();
assert_eq!(blob.kind(), ErrorKind::Invalid, "a blob is no filter's value");
let many = sql!("with recursive n(i) as (select 1 union all select i + 1 from n limit 100001) select i from n");
let limit = refused(many);
assert_eq!(limit.kind(), ErrorKind::Limit, "{limit}");
let documents = f.store.index::<Value>("notes").field("title", 1.0).open().unwrap();
let elsewhere = documents.search("bread").filter(search::is_in("id", sql!("select 1"))).run().unwrap_err();
assert!(elsewhere.to_string().contains("an index of documents has no tables"), "{elsewhere}");
}
const TASKS: &str = "create table tasks (
space text not null, n integer not null, title text not null, primary key (space, n)
)";
#[derive(Clone, Debug, PartialEq, Deserialize)]
struct Task {
space: String,
n: i64,
title: String,
}
#[test]
fn a_table_s_index_keyed_by_several_columns_follows_each_row_once_by_their_values_together() {
let f = fixture();
f.db.exec(TASKS).unwrap();
for n in 1..=300 {
f.db.exec(sql!("insert into tasks values ('NW', ?, ?)", n, format!("task {n}"))).unwrap();
}
f.db.exec("insert into tasks values ('EU', 1, 'экран входа'), ('NW', 301, 'экран входа')").unwrap();
let open = || f.db.search_index::<Task>("tasks_search").table("tasks").field("title", 1.0).filters(["space"]);
let tasks = open().open().unwrap();
f.ready(&tasks);
let found = |text: &str| ids(&tasks.search(text).limit(20).run().unwrap()).join(" ");
assert_eq!(found("экран"), r#"["EU",1] ["NW",301]"#, "the primary key of two columns, no key given");
assert_eq!(found("task"), (1..=20).map(|n| format!(r#"["NW",{n}]"#)).collect::<Vec<_>>().join(" "));
assert_eq!(tasks.search("300").run().unwrap().hits.len(), 1, "every row of a fill of several steps");
let hit = &tasks.search("экран").filter(eq("space", "EU")).run().unwrap().hits[0];
assert_eq!(hit.value, Task { space: "EU".to_owned(), n: 1, title: "экран входа".to_owned() }, "its row");
f.db.exec("update tasks set n = 2 where space = 'EU' and n = 1").unwrap();
assert_eq!(found("экран"), r#"["NW",301] ["EU",2]"#, "a key changed leaves its old id");
f.db.exec("update tasks set title = 'выход' where space = 'NW' and n = 301").unwrap();
assert_eq!(found("экран"), r#"["EU",2]"#);
f.db.exec("delete from tasks where space = 'EU'").unwrap();
assert_eq!(found("экран"), "");
let rolled = f.db.tx(|tx| -> crate::Result<()> {
tx.exec("insert into tasks values ('EU', 9, 'экран')")?;
Err(Error::invalid("rolled back"))
});
assert!(rolled.is_err());
assert_eq!(found("экран"), "", "a rollback changes neither");
let named = open().key(["space", "n"]).open().unwrap();
assert_eq!(ids(&named.search("выход").run().unwrap()), [r#"["NW",301]"#], "the same key named");
let other = open().key(["n", "space"]).open().unwrap();
assert!(matches!(other.status().unwrap(), Status::Rebuilding { .. }), "another order is another key, read beside");
f.ready(&other);
assert_eq!(ids(&other.search("выход").run().unwrap()), ["[301,\"NW\"]"], "ids by the key's new order");
}
#[test]
fn a_key_of_several_columns_is_unique_together_and_a_table_without_one_is_told_so_in_no_language_s_syntax() {
let f = fixture();
f.db.exec("create table loose (a text, b integer, title text)").unwrap();
let opened = |key: &[&str]| {
let index = f.db.search_index::<IgnoredAny>("loose_search").table("loose").field("title", 1.0);
index.key(key).open().map(drop)
};
let said = |key: &[&str]| opened(key).unwrap_err().to_string();
let none = "table loose has no primary key: give the index a key, a column or columns of unique values";
assert!(said(&[]).ends_with(&format!("{none}: invalid")), "{}", said(&[]));
let loose = "columns a, b of table loose are no key: their values are not unique together, by a primary key \
or a unique index";
assert!(said(&["a", "b"]).contains(loose), "{}", said(&["a", "b"]));
assert!(said(&["a", "a"]).contains("names column a twice"));
assert!(said(&["a", "c"]).contains("has no column c"));
f.db.exec("create unique index loose_ba on loose (b, a)").unwrap();
opened(&["a", "b"]).unwrap();
let index = f.db.search_index::<IgnoredAny>("loose_search").table("loose").key(["a", "b"]).field("title", 1.0);
let index = index.open().unwrap();
f.ready(&index);
f.db.exec("insert into loose values ('x', 1, 'bread')").unwrap();
let keyless = f.db.exec("insert into loose values (null, 2, 'bread')").unwrap_err();
assert!(keyless.to_string().contains("a row without a key"), "a null in its key fails its write: {keyless}");
assert_eq!(ids(&index.search("bread").run().unwrap()), [r#"["x",1]"#]);
}
#[test]
fn a_table_a_migration_dropped_drops_its_index_at_the_file_s_next_start_and_says_so() {
let f = fixture();
drop(f.articles());
f.insert(1, "bread", "");
f.store.close().unwrap();
let store = Store::open(f.dir.path(), Options { background: false, ..Options::default() }).unwrap();
let dropped = "drop table articles; create table notes (id integer primary key, title text not null);";
let migrations = [("0001_articles.sql", ARTICLES), ("0002_notes.sql", dropped)];
let db = store.database("app").migrations(migrations).open().unwrap();
let notes = db.search_index::<IgnoredAny>("articles_search").table("notes").field("title", 1.0).open();
let notes = notes.expect("a new index of the name: the one of the table gone was dropped");
db.exec("insert into notes (id, title) values (7, 'rye')").unwrap();
search::maintain(&store).unwrap();
notes.ready().unwrap();
assert_eq!(ids(¬es.search("rye").run().unwrap()), ["7"]);
assert!(notes.search("bread").run().unwrap().hits.is_empty(), "nothing of the dropped one's");
}
#[test]
fn another_table_or_key_is_read_beside_the_index_while_the_old_rows_answer_and_take_writes_then_switched_in() {
let f = fixture();
let titles = |table: &str| f.db.search_index::<IgnoredAny>("articles_search").table(table).field("title", 1.0);
let old = titles("articles").open().unwrap();
f.ready(&old);
f.insert(1, "bread", "");
f.db.exec("create table posts (slug text primary key, title text not null)").unwrap();
f.db.exec("insert into posts values ('rye', 'rye bread'), ('oats', 'oat porridge')").unwrap();
let moved = titles("posts").open().unwrap();
assert!(matches!(moved.status().unwrap(), Status::Rebuilding { .. }));
let found = |text: &str| ids(&moved.search(text).limit(20).run().unwrap()).join(" ");
assert_eq!(found("bread"), "1", "the old table answers until the switch");
f.insert(2, "bread again", "");
assert_eq!(found("bread"), "1 2", "and takes its writes");
f.db.exec("insert into posts values ('wheat', 'wheat bread')").unwrap();
f.db.exec("delete from posts where slug = 'oats'").unwrap();
assert_eq!(found("wheat"), "", "the new table's writes wait beside");
let triggers = |table: &str| -> i64 {
f.db.scalar(sql!("select count(*) from sqlite_schema where type = 'trigger' and tbl_name = ?", table)).unwrap()
};
assert_eq!((triggers("articles"), triggers("posts")), (3, 3), "two sets, one a table, never colliding");
f.ready(&moved);
assert_eq!(found("bread"), "rye wheat", "switched in: the new table's rows, its writes meanwhile included");
assert_eq!(found("porridge"), "", "a row deleted beside is gone");
assert_eq!((triggers("articles"), triggers("posts")), (0, 3), "the switch took the old table's triggers off");
f.insert(3, "bread once more", "");
f.db.exec("update posts set title = 'spelt' where slug = 'rye'").unwrap();
assert_eq!(found("bread"), "wheat", "the old table reaches it no longer, the new one does");
let pending: i64 = f.db.scalar(sql!("select count(*) from _tinystore_search_pending")).unwrap();
assert_eq!(pending, 0);
f.db.exec("create unique index posts_title on posts (title)").unwrap();
let rekeyed = titles("posts").key("title").open().unwrap();
assert_eq!(triggers("posts"), 6, "another key of the same table: two sets on it, never colliding");
f.db.exec("insert into posts values ('barley', 'barley bread')").unwrap();
assert_eq!(found("bread"), "wheat barley", "the old key answers until the switch, its writes included");
f.ready(&rekeyed);
assert_eq!(found("bread"), "barley bread wheat bread", "each row by its new key");
assert_eq!(triggers("posts"), 3);
let manual = titles("articles").rebuild(super::Rebuild::Manual).open().map(drop).unwrap_err();
assert!(manual.to_string().contains("table articles by id"), "manual waits for reindex: {manual}");
let rebuilt = titles("articles").rebuild(super::Rebuild::Manual).reindex().unwrap();
f.ready(&rebuilt);
assert_eq!(ids(&rebuilt.search("bread").limit(20).run().unwrap()), ["1", "2", "3"], "and a key back again");
}
#[test]
fn a_table_read_beside_an_index_goes_on_after_a_restart_with_the_writes_made_meanwhile() {
let f = fixture();
drop(f.articles());
f.db.exec("create table posts (slug text primary key, title text not null)").unwrap();
f.db.exec("insert into posts values ('rye', 'rye bread')").unwrap();
let posts = f.db.search_index::<IgnoredAny>("articles_search").table("posts").field("title", 1.0);
drop(posts.open().unwrap());
f.db.exec("insert into posts values ('wheat', 'wheat bread')").unwrap();
f.store.close().unwrap();
let store = Store::open(f.dir.path(), Options { background: false, ..Options::default() }).unwrap();
let db = store.database("app").migrations([("0001_articles.sql", ARTICLES)]).open().unwrap();
db.exec("insert into posts values ('spelt', 'spelt bread')").unwrap();
let posts = db.search_index::<IgnoredAny>("articles_search").table("posts").field("title", 1.0).open().unwrap();
search::maintain(&store).unwrap();
posts.ready().unwrap();
assert_eq!(ids(&posts.search("bread").run().unwrap()), ["rye", "spelt", "wheat"]);
}