Cotton code
266 lines · 8.9 KB · RustRaw
//! Which index mirrors which table, the SQL that refills one, and — since//! step 5i — the declaration both are read from.//!//! ONE statement of an index's shape, deliberately. Every CREATE, every//! trigger and every re-index is built from `FTS_SOURCES` below; a//! hand-written column list anywhere else would be a second statement of the//! same shape, and the two would drift on the next schema change that adds a//! column — the index created wide and filled narrow, with nothing raised and//! a search that silently never matches.use crate::schema::decl::FtsSource;/// The source entry for a DOMAIN table — the index its rows are mirrored into.pub fn fts_source_for(table: &str) -> Option<&'static FtsSource> {    FTS_SOURCES.iter().find(|source| source.source == table)}/// The source entry for an FTS5 table, by the index's own name.pub fn fts_source_named(fts: &str) -> Option<&'static FtsSource> {    FTS_SOURCES.iter().find(|source| source.fts == fts)}/// The statement that refills one index from its source table — for a rebuild,/// and for anything that has to prove the index and the table agree.////// One line, because the index is EXTERNAL-CONTENT: it stores no copy of the/// text, so `'rebuild'` is FTS5 re-reading the content table it already points/// at. This used to be a hand-written `INSERT … SELECT` per index, nineteen of/// them, each naming its own column list — a second statement of a shape/// [`FTS_SOURCES`] already declares, and the second one is the one that would/// be forgotten.pub fn fts_reindex(fts: &str) -> Option<String> {    fts_source_named(fts).map(|source| {        format!(            "INSERT INTO {name}({name}) VALUES ('rebuild')",            name = source.fts        )    })}// ---------------------------------------------------------------------------// The declaration itself, and this file owns it.//// It was written by `scripts/rust-gen.ts` out of `packages/store/src/schema/// fts.ts` until step 5i deleted both. Changing an index's columns here is// changing what search matches, so it travels with a `MIGRATIONS` entry in// `crate::migrate` and a new `schema_snapshot` fixture — never alone.// ---------------------------------------------------------------------------/// A word index: words split as Unicode says, diacritics folded.pub const WORDS: &str = "unicode61 remove_diacritics 2";/// Any three characters in a row, case folded: a match needs no word/// boundary, so it works in every script (Chat's search, v149).pub const TRIGRAM: &str = "trigram";pub static FTS_SOURCES: &[FtsSource] = &[    FtsSource {        fts: "fts_todos",        source: "cotton_todos",        columns: &["title", "notes"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_events",        source: "cotton_events",        columns: &["title", "notes", "location"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_notes",        source: "cotton_notes",        columns: &["title", "body"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_people",        source: "cotton_people",        columns: &["full_name", "org", "role_title", "summary"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_locations",        source: "cotton_locations",        columns: &["name", "address", "note"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_meetings",        source: "cotton_meetings",        columns: &["title", "summary_md"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_pages",        source: "cotton_pages",        columns: &["title", "text"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_messages",        source: "cotton_msg_messages",        columns: &["body"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_memories",        source: "cotton_memories",        columns: &["title", "body"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_documents",        source: "cotton_documents",        columns: &["title", "issuer", "summary", "original_name"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_document_pages",        source: "cotton_document_pages",        columns: &["text"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_prompts",        source: "cotton_prompts",        columns: &["text"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_emails",        source: "cotton_emails",        columns: &["subject", "body"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_moods",        source: "cotton_moods",        columns: &["line"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_thoughts",        source: "cotton_inbox_items",        columns: &["raw_text"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_session_messages",        source: "cotton_session_messages",        columns: &["body"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_photos",        source: "cotton_photos",        columns: &["caption", "summary", "ocr_text"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_videos",        source: "cotton_videos",        columns: &["caption", "summary"],        tokenize: WORDS,    },    // Version 6. The PLAIN columns only: `value_enc` is the sealed payload and    // indexing it would put a secret's ciphertext tokens in a table every    // device downloads.    FtsSource {        fts: "fts_secrets",        source: "cotton_secrets",        columns: &["name", "site", "username", "service"],        tokenize: WORDS,    },    // Version 19. A pull request and an issue are prose a person searches for    // by words they half-remember — "the pull that fixed the launch crash" —    // so both take the FTS lane, and `title` and `body` are the whole of what    // is indexed: `labels` and `checks` are JSON nobody searches by word, and    // a branch name is already found by the history screens.    FtsSource {        fts: "fts_repo_pulls",        source: "cotton_repo_pulls",        columns: &["title", "body"],        tokenize: WORDS,    },    FtsSource {        fts: "fts_repo_issues",        source: "cotton_repo_issues",        columns: &["title", "body"],        tokenize: WORDS,    },    // v42 — `decision`.    FtsSource {        fts: "fts_decisions",        source: "cotton_decisions",        columns: &["title", "why"],        tokenize: WORDS,    },    // v86 — `post`.    FtsSource {        fts: "fts_posts",        source: "cotton_posts",        columns: &["caption", "author_name", "author_handle"],        tokenize: WORDS,    },    // v122 — mail's wide index, filled in the background beside    // `fts_emails` and read once whole (`crate::fts_fill`): a typed word, a    // sender's name and a sender's address are one search.    FtsSource {        fts: "fts_mail",        source: "cotton_emails",        columns: &["subject", "body", "from_name", "from_email"],        tokenize: WORDS,    },    // v149 — Chat's search by any three characters in a row, filled in the    // background beside `fts_messages` (which stays the messages' index for    // every other reader): a match needs no word boundary, in any script.    FtsSource {        fts: "fts_chat",        source: "cotton_msg_messages",        columns: &["body"],        tokenize: TRIGRAM,    },    // gen-kind: fts-sources];#[cfg(test)]mod tests {    use super::*;    #[test]    fn a_domain_table_finds_its_index_and_the_index_finds_it_back() {        let source = fts_source_for("cotton_msg_messages").expect("messages are indexed");        assert_eq!(source.fts, "fts_messages");        assert_eq!(source.columns, &["body"]);        assert_eq!(fts_source_named("fts_messages"), Some(source));        assert!(fts_source_for("cotton_todos_not_a_table").is_none());        assert!(fts_source_named("fts_not_an_index").is_none());    }    #[test]    fn every_source_has_a_rebuild_that_names_its_own_index() {        // The column list is no longer asserted because it can no longer be        // wrong: an external-content index stores no copy of the text, so a        // rebuild is FTS5 re-reading the content table through the column list        // the CREATE already declared. What is still worth pinning is that        // every source HAS one and that it names itself — a rebuild pointed at        // the wrong index would silently leave one stale.        for source in FTS_SOURCES {            let sql = fts_reindex(source.fts)                .unwrap_or_else(|| panic!("{} has no rebuild", source.fts));            assert_eq!(                sql,                format!(                    "INSERT INTO {name}({name}) VALUES ('rebuild')",                    name = source.fts                ),                "{}",                source.fts            );        }        assert!(fts_reindex("fts_not_an_index").is_none());    }}