Cotton code
412 lines · 15.0 KB · RustRaw
//! The canonical dump — how conformance is DEFINED (spec R4).//!//! SQLite page layout differs by library build, so "the two files are the same//! database" cannot be a byte comparison. It is this instead://!//! - `user_version`;//! - `schema`: every `sqlite_master` row (type, name, tbl_name, sql), sorted by//!   (type, name), minus `sqlite_sequence` and the FTS5 shadow tables;//! - `tables`: every ordinary table's rows, ordered by ALL columns in//!   declaration order, each value TYPED so `1` and `"1"` and `1.0` are three//!   different dumps;//! - `fts`: every FTS5 table's rowids in order, plus one probe `MATCH`.//!//! Two dumps equal ⇒ the files are the same database.use std::collections::BTreeMap;use rusqlite::types::Value;use serde_json::{json, Map, Value as JsonValue};use crate::driver::Driver;use crate::error::Result;/// The `MATCH` every FTS table is probed with — five vowels, so any table/// holding English text answers with something and an empty index answers 0.const FTS_PROBE: &str = "a OR e OR i OR o OR u";/// A whole file, canonically.pub fn dump(db: &Driver) -> Result<JsonValue> {    let mut out = Map::new();    out.insert(        "user_version".to_string(),        json!(crate::meta::file_schema_version(db)?),    );    out.insert("schema".to_string(), JsonValue::Array(schema_rows(db)?));    let master = master_entries(db)?;    let fts_names: Vec<String> = master        .iter()        .filter(|entry| entry.is_fts5_virtual())        .map(|entry| entry.name.clone())        .collect();    // A shadow table is an FTS index's own storage: `x_data`, `x_idx`,    // `x_docsize`, `x_config`, `x_content`. Its contents are the module's    // business — two builds of FTS5 may lay one out differently while the    // index answers identically — so the dump names the rowids and the probe    // instead.    let mut tables = BTreeMap::new();    for entry in &master {        if entry.kind != "table" || entry.name.starts_with("sqlite_") {            continue;        }        if entry.is_fts5_virtual() || is_fts_shadow(&entry.name, &fts_names) {            continue;        }        tables.insert(entry.name.clone(), table_rows(db, &entry.name)?);    }    out.insert(        "tables".to_string(),        JsonValue::Object(            tables                .into_iter()                .map(|(name, rows)| (name, JsonValue::Array(rows)))                .collect(),        ),    );    let mut fts = BTreeMap::new();    for name in &fts_names {        fts.insert(name.clone(), fts_entry(db, name)?);    }    out.insert(        "fts".to_string(),        JsonValue::Object(fts.into_iter().collect()),    );    Ok(JsonValue::Object(out))}/// The dump as pretty JSON with sorted keys — what a harness diffs and what a/// human reads when it does not match.pub fn dump_to_writer(db: &Driver, writer: impl std::io::Write) -> Result<()> {    let value = dump(db)?;    // serde_json's Map keeps insertion order (the workspace turns on    // `preserve_order`), so the sort is done here rather than assumed.    serde_json::to_writer_pretty(writer, &sorted(&value))        .map_err(|error| crate::error::StoreError::encode(format!("dump: {error}")))?;    Ok(())}fn sorted(value: &JsonValue) -> JsonValue {    match value {        JsonValue::Object(fields) => {            let ordered: BTreeMap<&String, JsonValue> =                fields.iter().map(|(k, v)| (k, sorted(v))).collect();            JsonValue::Object(ordered.into_iter().map(|(k, v)| (k.clone(), v)).collect())        }        JsonValue::Array(items) => JsonValue::Array(items.iter().map(sorted).collect()),        other => other.clone(),    }}struct MasterEntry {    kind: String,    name: String,    tbl_name: String,    sql: Option<String>,}impl MasterEntry {    fn is_fts5_virtual(&self) -> bool {        self.kind == "table"            && self                .sql                .as_deref()                .map(str::to_ascii_lowercase)                .is_some_and(|sql| sql.contains("using fts5"))    }}fn master_entries(db: &Driver) -> Result<Vec<MasterEntry>> {    let rows = db.all(        "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name",        &[],    )?;    Ok(rows        .into_iter()        .map(|row| MasterEntry {            kind: row.text("type").unwrap_or_default().to_string(),            name: row.text("name").unwrap_or_default().to_string(),            tbl_name: row.text("tbl_name").unwrap_or_default().to_string(),            sql: row.text("sql").map(str::to_string),        })        .collect())}fn schema_rows(db: &Driver) -> Result<Vec<JsonValue>> {    let entries = master_entries(db)?;    let fts_names: Vec<String> = entries        .iter()        .filter(|entry| entry.is_fts5_virtual())        .map(|entry| entry.name.clone())        .collect();    Ok(entries        .iter()        // `sqlite_sequence` is SQLite's own AUTOINCREMENT bookkeeping and the        // shadow tables are FTS5's; neither is the file's schema.        .filter(|entry| entry.name != "sqlite_sequence")        .filter(|entry| !is_fts_shadow(&entry.name, &fts_names))        .map(|entry| {            json!({                "type": entry.kind,                "name": entry.name,                "tbl_name": entry.tbl_name,                "sql": entry.sql,            })        })        .collect())}/// `<fts>_data`, `_idx`, `_docsize`, `_config`, `_content` — FTS5's own/// storage for a virtual table the dump already covers.fn is_fts_shadow(name: &str, fts_names: &[String]) -> bool {    const SUFFIXES: [&str; 5] = ["_data", "_idx", "_docsize", "_config", "_content"];    SUFFIXES.iter().any(|suffix| {        name.strip_suffix(suffix)            .is_some_and(|stem| fts_names.iter().any(|fts| fts == stem))    })}fn table_rows(db: &Driver, table: &str) -> Result<Vec<JsonValue>> {    let columns = db.all(&format!("PRAGMA table_info(\"{}\")", escape(table)), &[])?;    if columns.is_empty() {        return Ok(Vec::new());    }    // Ordered by EVERY column in declaration order: a table with no primary    // key (or a duplicated one) still dumps in one determinate order, which is    // what makes "two dumps equal" mean anything.    let order_by = (1..=columns.len())        .map(|index| index.to_string())        .collect::<Vec<_>>()        .join(",");    let rows = db.all(        &format!("SELECT * FROM \"{}\" ORDER BY {order_by}", escape(table)),        &[],    )?;    Ok(rows        .into_iter()        .map(|row| {            JsonValue::Object(                row.columns()                    .iter()                    .map(|(name, value)| (name.clone(), typed(value)))                    .collect(),            )        })        .collect())}/// `{"t":"null"} | {"i":123} | {"r":"1.5"} | {"s":"…"} | {"b":"<hex>"}`.////// The REAL is a string on purpose: a float in JSON is at the mercy of/// whichever side parses it, and the dump has to survive a round trip through/// the harness. `1` and `"1"` and `1.0` are three different dumps, which is/// the point — SQLite's type affinity makes them easy to confuse and a fold/// that stored the wrong one would be invisible otherwise.fn typed(value: &Value) -> JsonValue {    match value {        Value::Null => json!({ "t": "null" }),        Value::Integer(int) => json!({ "i": int }),        Value::Real(real) => json!({ "r": crate::protocol::js::number_to_string(*real) }),        Value::Text(text) => json!({ "s": text }),        Value::Blob(bytes) => json!({ "b": hex::encode(bytes) }),    }}fn fts_entry(db: &Driver, name: &str) -> Result<JsonValue> {    let rowids: Vec<JsonValue> = db        .all(            &format!("SELECT rowid FROM \"{}\" ORDER BY rowid", escape(name)),            &[],        )?        .into_iter()        .map(|row| json!(row.int("rowid").unwrap_or_default()))        .collect();    // A probe that fails is DATA, not a failure: an FTS table whose index is    // corrupt has to show up as a difference between the two sides rather than    // stopping the dump that would have named it.    let probe = match db.get(        &format!(            "SELECT count(*) AS n FROM \"{0}\" WHERE \"{0}\" MATCH ?",            escape(name)        ),        &[Value::Text(FTS_PROBE.to_string())],    ) {        Ok(row) => json!(row.and_then(|row| row.int("n")).unwrap_or_default()),        Err(error) => json!({ "error": error.to_string() }),    };    Ok(json!({ "rowids": rowids, "probe": probe }))}/// A double-quoted identifier escapes an embedded quote by doubling it. No/// Cotton table name has one; the escape is here so a name from/// `sqlite_master` can never be a place where SQL is assembled unsafely.fn escape(identifier: &str) -> String {    identifier.replace('"', "\"\"")}#[cfg(test)]mod tests {    use super::*;    fn fixture() -> Driver {        let db = Driver::open_in_memory().expect("opens");        db.exec("PRAGMA user_version = 7").expect("stamps");        db.exec(            "CREATE TABLE notes (id TEXT PRIMARY KEY, title TEXT, weight REAL, seen INTEGER, blob BLOB)",        )        .expect("creates");        db.exec("CREATE INDEX idx_notes_title ON notes (title)")            .expect("creates");        db.exec("CREATE VIRTUAL TABLE fts_notes USING fts5(title, body)")            .expect("creates");        db.exec(            "INSERT INTO notes (id, title, weight, seen, blob) VALUES \             ('b', 'beta', 1.5, 2, x'00ff'), ('a', 'alpha', NULL, NULL, NULL)",        )        .expect("inserts");        db.exec("INSERT INTO fts_notes (title, body) VALUES ('alpha', 'the quick brown fox')")            .expect("inserts");        db    }    #[test]    fn carries_the_user_version() {        let dumped = dump(&fixture()).expect("dumps");        assert_eq!(dumped["user_version"], json!(7));    }    #[test]    fn the_schema_is_sorted_and_excludes_the_shadow_tables() {        let dumped = dump(&fixture()).expect("dumps");        let names: Vec<&str> = dumped["schema"]            .as_array()            .expect("an array")            .iter()            .map(|entry| entry["name"].as_str().expect("a name"))            .collect();        // `sqlite_autoindex_*` stays: it is real schema, SQLite creates it        // deterministically for a TEXT primary key, and both sides therefore        // have it. Only `sqlite_sequence` (AUTOINCREMENT bookkeeping) and the        // FTS shadow tables are excluded.        assert_eq!(            names,            [                "idx_notes_title",                "sqlite_autoindex_notes_1",                "fts_notes",                "notes"            ]        );        for name in &names {            assert!(!name.ends_with("_data"), "shadow table {name} leaked in");            assert!(!name.ends_with("_idx"), "shadow table {name} leaked in");            assert_ne!(*name, "sqlite_sequence");        }    }    #[test]    fn rows_are_ordered_by_every_column_and_typed() {        let dumped = dump(&fixture()).expect("dumps");        let rows = dumped["tables"]["notes"].as_array().expect("an array");        assert_eq!(rows.len(), 2);        // Ordered by column 1 (`id`), so 'a' comes before 'b' regardless of        // insertion order.        assert_eq!(rows[0]["id"], json!({ "s": "a" }));        assert_eq!(rows[0]["weight"], json!({ "t": "null" }));        assert_eq!(rows[1]["id"], json!({ "s": "b" }));        assert_eq!(rows[1]["weight"], json!({ "r": "1.5" }));        assert_eq!(rows[1]["seen"], json!({ "i": 2 }));        assert_eq!(rows[1]["blob"], json!({ "b": "00ff" }));    }    #[test]    fn an_integer_a_text_and_a_real_of_the_same_number_dump_differently() {        let db = Driver::open_in_memory().expect("opens");        db.exec("CREATE TABLE t (k TEXT, v)").expect("creates");        db.exec("INSERT INTO t VALUES ('i', 1), ('r', 1.0), ('s', '1')")            .expect("inserts");        // SQLite stores 1.0 in a column with no affinity as a REAL.        let dumped = dump(&db).expect("dumps");        let rows = dumped["tables"]["t"].as_array().expect("an array");        let by_key = |k: &str| {            rows.iter()                .find(|row| row["k"] == json!({ "s": k }))                .expect("the row")["v"]                .clone()        };        assert_eq!(by_key("i"), json!({ "i": 1 }));        assert_eq!(by_key("r"), json!({ "r": "1" }));        assert_eq!(by_key("s"), json!({ "s": "1" }));    }    #[test]    fn an_fts_table_dumps_its_rowids_and_a_probe_count() {        let dumped = dump(&fixture()).expect("dumps");        assert_eq!(dumped["fts"]["fts_notes"]["rowids"], json!([1]));        // The probe is a MATCH on the five single-letter vowel TOKENS: the        // fixture's words are not any of them, so 0 is the right answer and a        // difference between two files' probes is a difference in their index.        assert_eq!(dumped["fts"]["fts_notes"]["probe"], json!(0));        // And it is NOT in `tables` — its content is the module's business.        assert!(dumped["tables"].get("fts_notes").is_none());    }    #[test]    fn the_probe_counts_the_rows_that_match_it() {        let db = Driver::open_in_memory().expect("opens");        db.exec("CREATE VIRTUAL TABLE fts_vowels USING fts5(body)")            .expect("creates");        db.exec("INSERT INTO fts_vowels (body) VALUES ('a b c'), ('e f g'), ('x y z')")            .expect("inserts");        let dumped = dump(&db).expect("dumps");        assert_eq!(dumped["fts"]["fts_vowels"]["rowids"], json!([1, 2, 3]));        assert_eq!(dumped["fts"]["fts_vowels"]["probe"], json!(2));    }    #[test]    fn an_empty_fts_table_probes_to_zero_rather_than_failing() {        let db = Driver::open_in_memory().expect("opens");        db.exec("CREATE VIRTUAL TABLE fts_empty USING fts5(body)")            .expect("creates");        let dumped = dump(&db).expect("dumps");        assert_eq!(dumped["fts"]["fts_empty"]["rowids"], json!([]));        assert_eq!(dumped["fts"]["fts_empty"]["probe"], json!(0));    }    #[test]    fn two_files_built_the_same_way_dump_equal() {        assert_eq!(            dump(&fixture()).expect("dumps"),            dump(&fixture()).expect("dumps")        );    }    #[test]    fn one_differing_row_makes_the_dumps_differ() {        let a = fixture();        let b = fixture();        b.exec("UPDATE notes SET title = 'ALPHA' WHERE id = 'a'")            .expect("updates");        assert_ne!(dump(&a).expect("dumps"), dump(&b).expect("dumps"));    }    #[test]    fn the_pretty_form_has_sorted_keys() {        let mut out = Vec::new();        dump_to_writer(&fixture(), &mut out).expect("writes");        let text = String::from_utf8(out).expect("utf-8");        let fts = text.find("\"fts\"").expect("fts key");        let schema = text.find("\"schema\"").expect("schema key");        let tables = text.find("\"tables\"").expect("tables key");        let user_version = text.find("\"user_version\"").expect("user_version key");        assert!(            fts < schema && schema < tables && tables < user_version,            "{text}"        );    }}