Cotton code
221 lines · 9.6 KB · RustRaw
//! **NO FOREIGN KEY BETWEEN REPLICATED TABLES MOVES A ROW.** The fold does.//!//! A row leaves the file in exactly one way: a retract receipt, minted by the//! writer that asked for it, that every other file folds the same way. SQLite's//! `ON DELETE CASCADE` removed a parent's children with no receipt of their//! own — a child vanished on the file that applied the delete and nowhere//! else, and nothing could say why. `ON DELETE SET NULL` is the same defect on//! a column: a soft value went empty on one file and stayed on another.//! Cotton note "Sync groundwork 1" (3.9, "Every reference classified") holds//! the rule; `schema::table_specs::OWNING_REFS` and `SOFT_REFS` hold the//! classification, and `tests/fresh_line_schema.rs` holds those two lists//! equal to the file.//!//! So this guard asks the file three things://!//! 1. **No `CASCADE` at all**, except `workspace_id → cotton_workspaces`: the//!    workspace is the file, and a file is wiped, never retracted row by row.//! 2. **Every owning reference is a plain `REFERENCES parent(id)`** — a//!    tripwire that refuses a child written under a parent that is not there,//!    never a mover. When a parent is retracted the fold moves its children//!    itself and mints nothing for them (`cotton_store::fold`).//! 3. **No `SET NULL`**: the allow-list below is empty since slice 3b took//!    the foreign key off every soft column; a new one fails here.//!//! And one thing of a server-only child (`SERVER_ONLY_CHILD_REFS`): its//! reference to a replicated parent is a column with no constraint, because//! its rows never cross a file boundary and the server's own code moves them.//!//! The scan is of the BUILT file (`pragma_foreign_key_list`), so it holds for//! every statement the ladder issues, and once more of the DDL source, so a//! constraint written into a constant the ladder does not yet issue fails//! before it is issued.use std::collections::BTreeSet;use cotton_store::migrate::migrate_store;use cotton_store::schema::table_specs::{    is_server_only, OWNING_REFS, SERVER_ONLY_CHILD_REFS, SOFT_REFS,};use cotton_store::Driver;/// The `ON DELETE SET NULL` actions allowed on the file: none since schema 81,/// when slice 3b took the foreign key off every soft column, so this guard/// refuses every `SET NULL`. `(child table, child column, parent table)`.const SET_NULL_STILL_ALLOWED: &[(&str, &str, &str)] = &[];struct LiveKey {    child: String,    col: String,    parent: String,    on_delete: String,}/// Every foreign key in a freshly built file.fn live_foreign_keys() -> Vec<LiveKey> {    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("migrates");    db.all(        "SELECT m.name AS child, f.\"from\" AS col, f.\"table\" AS parent, f.on_delete AS on_delete \         FROM sqlite_master m, pragma_foreign_key_list(m.name) f \         WHERE m.type = 'table' ORDER BY m.name, f.\"from\", f.\"table\"",        &[],    )    .expect("reads")    .iter()    .map(|row| LiveKey {        child: row.text("child").unwrap_or_default().to_string(),        col: row.text("col").unwrap_or_default().to_string(),        parent: row.text("parent").unwrap_or_default().to_string(),        on_delete: row.text("on_delete").unwrap_or_default().to_string(),    })    .collect()}fn names(key: &LiveKey) -> String {    format!("{}.{} → {}", key.child, key.col, key.parent)}fn listed(list: &[(&str, &str, &str)], key: &LiveKey) -> bool {    list.iter()        .any(|(c, k, p)| *c == key.child && *k == key.col && *p == key.parent)}/// RULE: No foreign key between replicated tables cascades or sets null — an owning reference is a plain tripwire, the fold moves children itself, and SET NULL survives only on the allow-list slice 3b empties.#[test]fn no_cascade_between_replicated_tables() {    let keys = live_foreign_keys();    assert!(!keys.is_empty(), "the file has no foreign keys at all — the query is wrong");    let mut faults: Vec<String> = Vec::new();    for key in &keys {        // Device-local receipt projections are not replicated records.        if key.child.starts_with('_') && key.parent.starts_with('_') { continue; }        let is_workspace = key.col == "workspace_id" && key.parent == "cotton_workspaces";        if is_workspace {            if key.on_delete != "CASCADE" {                faults.push(format!(                    "{} is ON DELETE {} — the workspace is the file, and its reference stays CASCADE",                    names(key),                    key.on_delete                ));            }            continue;        }        if is_server_only(&key.child) {            faults.push(format!(                "{} is a constraint on a server-only child — its rows never leave this file, \                 so the reference is a column with no FOREIGN KEY (SERVER_ONLY_CHILD_REFS)",                names(key)            ));            continue;        }        match key.on_delete.as_str() {            "CASCADE" => faults.push(format!(                "{} is ON DELETE CASCADE — SQLite would remove the child with no receipt; \                 write it as a plain REFERENCES and let the fold move it",                names(key)            )),            "SET NULL" => {                if !listed(SET_NULL_STILL_ALLOWED, key) {                    faults.push(format!(                        "{} is ON DELETE SET NULL and not on SET_NULL_STILL_ALLOWED — a soft \                         value goes empty through soft_absent, never through SQLite",                        names(key)                    ));                }                if !listed(SOFT_REFS, key) {                    faults.push(format!(                        "{} is ON DELETE SET NULL but SOFT_REFS does not name it",                        names(key)                    ));                }            }            "NO ACTION" => {                if !listed(OWNING_REFS, key) && !listed(SOFT_REFS, key) {                    faults.push(format!(                        "{} is a plain reference between replicated tables that neither \                         OWNING_REFS nor SOFT_REFS names — classify it",                        names(key)                    ));                }            }            other => faults.push(format!("{} is ON DELETE {other} — not a thing the file allows", names(key))),        }    }    // The allow-list is exactly the SET NULLs still on the file: an entry whose    // action 3b already dropped is deleted here in the same commit.    for (child, col, parent) in SET_NULL_STILL_ALLOWED {        let still_there = keys.iter().any(|key| {            key.child == *child && key.col == *col && key.parent == *parent && key.on_delete == "SET NULL"        });        if !still_there {            faults.push(format!(                "{child}.{col} → {parent} is on SET_NULL_STILL_ALLOWED but is no longer ON DELETE SET NULL — delete its line"            ));        }    }    // A server-only child's reference is a column the file still carries.    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("migrates");    for (child, col, parent) in SERVER_ONLY_CHILD_REFS {        let has_column = db            .all(&format!("SELECT name FROM pragma_table_info('{child}')"), &[])            .expect("reads")            .iter()            .any(|row| row.text("name") == Some(col));        if !has_column {            faults.push(format!(                "{child}.{col} → {parent} is in SERVER_ONLY_CHILD_REFS but {child} has no column {col}"            ));        }    }    assert!(faults.is_empty(), "the file's foreign keys break the rule:\n  {}", faults.join("\n  "));}/// RULE: Replicated DDL carries no ON DELETE CASCADE except workspace_id; device-local receipt projections may follow their local receipt lifecycle.#[test]fn the_ddl_source_carries_no_cascade_but_the_workspace() {    let source = std::fs::read_to_string(        cotton_store::manifest_dir().join("src").join("schema").join("ddl.rs"),    )    .expect("the DDL source is beside this test");    let offenders: Vec<String> = source        .lines()        .enumerate()        .filter(|(_, line)| line.contains("FOREIGN KEY") || line.contains("REFERENCES"))        .filter(|(_, line)| line.contains("ON DELETE CASCADE"))        .filter(|(_, line)| !line.contains("workspace_id"))        .filter(|(_, line)| !line.contains("REFERENCES _writes(op_id)"))        .map(|(index, line)| format!("ddl.rs:{}: {}", index + 1, line.trim()))        .collect();    assert!(        offenders.is_empty(),        "ON DELETE CASCADE between replicated tables in the DDL source:\n  {}",        offenders.join("\n  ")    );    // And the tripwires are all still there: every owning reference appears as    // a plain REFERENCES somewhere in the source.    let plain: BTreeSet<(String, String)> = source        .lines()        .filter(|line| line.contains("REFERENCES") && !line.contains("ON DELETE"))        .filter_map(|line| {            let col = line.split("FOREIGN KEY (").nth(1)?.split(')').next()?.trim().to_string();            let parent = line.split("REFERENCES ").nth(1)?.split('(').next()?.trim().to_string();            Some((col, parent))        })        .collect();    let missing: Vec<String> = OWNING_REFS        .iter()        .filter(|(_, col, parent)| !plain.contains(&(col.to_string(), parent.to_string())))        .map(|(child, col, parent)| format!("{child}.{col} → {parent}"))        .collect();    assert!(        missing.is_empty(),        "owning references with no plain FOREIGN KEY … REFERENCES line in ddl.rs: {missing:?}"    );}