Cotton code
175 lines · 7.7 KB · RustRaw
//! The schema stops being hand-editable (step 5, R5).//!//! `gen:check` caught exactly one class: the Rust copy drifting from the//! TypeScript declaration. After the flip that class cannot occur, and the//! class that replaces it is worse — a **self-consistent hand edit**, where//! someone renames a column in the DDL and in `TABLE_SPECS` together and//! silently changes the file format with no migration.//!//! So a fresh file's shape survives as a committed snapshot of//! `sqlite_master` at the current version. On the fresh line a shape change is//! allowed, and it is never silent: it moves the built file away from the//! snapshot, and this file says what to do (bump `SCHEMA_VERSION`, re-record,//! add a SHAPE line to the shape ledger). An old file is refused, never//! climbed.//!//! The snapshot is rewritten only by an explicitly ignored run://!//! ```text//! cargo test -p cotton-store --test schema_snapshot -- --ignored//! ```//!//! Never as a side effect of a failing test. A snapshot that repaired itself//! would be a guard that agreed with whatever it was shown.//!//! **Why this is not a photograph of nothing.** A committed snapshot is only//! worth what the thing it was first taken from was worth. This one inherits//! the comparison with the owner's real file recorded in PR #427, when the//! owner's database moved onto his own Mac. There is no second witness: step 5i//! deleted the generator, so this snapshot and `tests/totality.rs` are what//! hold the shape, and `the_flat_ddl_and_the_ladder_build_the_same_file`//! below holds the one-rung ladder equal to `schema::ddl::SCHEMA_DDL`.use std::path::PathBuf;use cotton_store::create::{fresh_schema, schema_objects, SchemaObject};use cotton_store::manifest_dir;use cotton_store::migrate::migrate_store;use cotton_store::Driver;/// The snapshot is found from the RUNTIME manifest directory, never the/// compile-time constant: a cached test binary from an earlier CI checkout/// carries a path that has been deleted, and the failure reads like this guard/// catching real drift. `manifest-dir-at-run-time.test.ts` holds the rule.fn snapshot_path() -> PathBuf {    manifest_dir()        .join("tests")        .join("fixtures")        .join("schema-snapshot.json")}/// A file built the way a real one is built: the ladder, from zero.fn built_by_the_ladder() -> Vec<SchemaObject> {    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("migrates");    schema_objects(&db).expect("reads the schema")}fn committed_snapshot() -> Vec<SchemaObject> {    let path = snapshot_path();    let text = std::fs::read_to_string(&path).unwrap_or_else(|error| {        panic!(            "cotton-store: the committed schema snapshot is missing at {} ({error}) — it is the \             only record of what a file at this version looks like; rewrite it with `cargo test \             -p cotton-store --test schema_snapshot -- --ignored` ONLY after bumping \             SCHEMA_VERSION for a shape change",            path.display()        )    });    serde_json::from_str(&text).expect("the snapshot is JSON this build can read")}/// RULE: The database schema never changes silently: a fresh file is exactly the committed schema snapshot, and a shape change bumps SCHEMA_VERSION and re-records it.#[test]fn the_ladder_builds_exactly_the_committed_snapshot() {    let built = built_by_the_ladder();    let snapshot = committed_snapshot();    // Named first, so a missing or extra object reads as itself rather than as    // a wall of SQL.    let built_names: Vec<&str> = built.iter().map(|object| object.name.as_str()).collect();    let snapshot_names: Vec<&str> = snapshot.iter().map(|object| object.name.as_str()).collect();    let missing: Vec<&&str> = snapshot_names        .iter()        .filter(|name| !built_names.contains(name))        .collect();    let extra: Vec<&&str> = built_names        .iter()        .filter(|name| !snapshot_names.contains(name))        .collect();    assert!(        missing.is_empty() && extra.is_empty(),        "the schema changed: {} object(s) the snapshot has and a fresh file no longer carries \         {missing:?}, {} a fresh file carries and the snapshot does not {extra:?}. On the fresh \         line that is allowed: bump SCHEMA_VERSION in schema/ddl.rs, re-record the snapshot with \         `cargo test -p cotton-store --test schema_snapshot -- --ignored`, and add a SHAPE line \         to the shape ledger. An old file is refused, never climbed.",        missing.len(),        extra.len()    );    for (built, committed) in built.iter().zip(snapshot.iter()) {        assert_eq!(            built, committed,            "`{}` is not the object the snapshot committed. The schema changed: bump \             SCHEMA_VERSION in schema/ddl.rs, re-record the snapshot with `cargo test -p \             cotton-store --test schema_snapshot -- --ignored`, and add a SHAPE line to the shape \             ledger. An old file is refused, never climbed.",            built.name        );    }    assert_eq!(built, snapshot);}#[test]fn the_flat_ddl_and_the_ladder_build_the_same_file() {    // The ladder has one rung and it issues `SCHEMA_DDL`; `create` applies the    // same list in phases. The two paths into a fresh file are one shape.    assert_eq!(fresh_schema().expect("builds"), built_by_the_ladder());}#[test]fn the_snapshot_carries_no_object_sqlite_makes_for_itself() {    let snapshot = committed_snapshot();    let fts: Vec<&str> = snapshot        .iter()        .filter(|object| object.is_fts5_virtual())        .map(|object| object.name.as_str())        .collect();    const SHADOWS: [&str; 5] = ["_data", "_idx", "_docsize", "_config", "_content"];    for object in &snapshot {        assert!(!object.name.starts_with("sqlite_autoindex"), "{object:?}");        assert_ne!(object.name, "sqlite_sequence");        assert!(!object.sql.trim().is_empty(), "{object:?}");        // A shadow table is `<fts>_data` and its four siblings: made by        // `CREATE VIRTUAL TABLE`, and the module's business rather than the        // file's. An ordinary index called `idx_something_idx` is not one, so        // the suffix is only a shadow when its STEM is an index this file has.        let shadow = SHADOWS.iter().any(|suffix| {            object                .name                .strip_suffix(suffix)                .is_some_and(|stem| fts.contains(&stem))        });        assert!(            !shadow,            "an FTS5 shadow table is the module's business, never the file's: {}",            object.name        );    }    // The file carries exactly the search indexes `FTS_SOURCES` declares —    // the rule, not a count that every new index had to edit.    let declared: std::collections::BTreeSet<&str> =        cotton_store::schema::fts::FTS_SOURCES.iter().map(|source| source.fts).collect();    let carried: std::collections::BTreeSet<&str> = fts.iter().copied().collect();    assert_eq!(carried, declared, "the file carries the search indexes FTS_SOURCES declares");}/// Rewrite the committed snapshot. Ignored on purpose: it runs when a shape/// change has bumped SCHEMA_VERSION, and never as a side effect of a red test.#[test]#[ignore = "rewrites the committed snapshot; run it only after bumping SCHEMA_VERSION"]fn rewrite_the_snapshot() {    let built = built_by_the_ladder();    let path = snapshot_path();    std::fs::create_dir_all(path.parent().expect("a fixtures directory")).expect("makes it");    let mut text = serde_json::to_string_pretty(&built).expect("serializes");    text.push('\n');    std::fs::write(&path, text).expect("writes");    println!(        "schema snapshot rewritten: {} objects at {}",        built.len(),        path.display()    );}