//! Reading `schema::table_specs` — the questions asked of the codec table. //! //! Nothing here decides anything: the data is the declaration, and these are //! the lookups over it. A linear scan is deliberate — 96 specs, and a lazy map //! would buy microseconds at the cost of a lock on a path the fold takes per //! op. //! //! There is no "is this table retired" any more (spec R2): the retired list //! existed so a file could survive an op naming a table its own build had //! dropped, and there is no such file. An unknown table is unknown. use crate::schema::table_specs::TABLE_SPECS; use crate::schema::decl::{Codec, TableSpec}; /// The spec for a table name — `specFor` in tableSpecs.ts. pub fn spec_for(table: &str) -> Option<&'static TableSpec> { TABLE_SPECS.iter().find(|spec| spec.name == table) } /// A table's columns with their codecs, in declaration order. pub fn columns_of(table: &str) -> Option<&'static [(&'static str, Codec)]> { spec_for(table).map(|spec| spec.columns) } /// The codec of one column, where both the table and the column are known. pub fn codec_of(table: &str, column: &str) -> Option { columns_of(table)? .iter() .find(|(name, _)| *name == column) .map(|(_, codec)| *codec) } #[cfg(test)] mod tests { use super::*; #[test] fn a_spec_is_found_by_name_and_an_unknown_name_is_not() { let spec = spec_for("cotton_todos").expect("cotton_todos is a table spec"); assert_eq!(spec.name, "cotton_todos"); assert_eq!(spec.pk, "id"); assert!(spec_for("cotton_not_a_table").is_none()); } /// RULE: Column lookup carries the declared storage codec and refuses unknown columns, so callers cannot silently round stored decimal text. #[test] fn columns_carry_their_codec() { assert_eq!(codec_of("cotton_todos", "id"), Some(Codec::Text)); assert_eq!(codec_of("cotton_todos", "not_a_column"), None); // The one genuine numeric in the schema — a 0..1 router score, stored // as text so nothing rounds it. assert_eq!( codec_of("cotton_inbox_items", "route_confidence"), Some(Codec::DecimalText) ); } #[test] fn a_table_the_ladder_retired_has_no_spec_and_is_simply_unknown() { // `cotton_tags` and the prompt library were retired by the TypeScript // ladder. The Rust store has no memory of them: the file it adopts has // no such table, so the fold's answer is "unknown table", not "retired". assert!(spec_for("cotton_tags").is_none()); assert!(spec_for("cotton_prompt_blocks").is_none()); } } /// The schema data, checked against itself. /// /// `crates/cotton-store/tests/schema_snapshot.rs` proves the shape these files /// build is the committed one; these prove the files are COHERENT — that an /// `fts_into` names an index that exists, that every spec's primary key is one /// of its own columns, that `SCHEMA_DDL` really creates every table a spec /// names. A hand edit that produced a plausible-looking file could still agree /// with a snapshot rewritten beside it; it would not pass these. #[cfg(test)] mod generated_is_self_consistent { use crate::schema::fts::FTS_SOURCES; use crate::schema::ddl::{SCHEMA_DDL, SCHEMA_VERSION}; use crate::schema::table_specs::{DROPPED_TABLES, TABLE_NAMES, TABLE_SPECS}; use std::collections::HashSet; #[test] fn every_fts_into_names_a_source_and_every_source_names_a_table() { let indexes: HashSet<&str> = FTS_SOURCES.iter().map(|source| source.fts).collect(); assert_eq!( indexes.len(), FTS_SOURCES.len(), "two sources share an fts name" ); for spec in TABLE_SPECS { let Some(fts) = spec.fts_into else { continue }; assert!( indexes.contains(fts), "{} points at {fts}, which is not a source", spec.name ); let source = FTS_SOURCES .iter() .find(|source| source.fts == fts) .expect("the index exists"); assert_eq!(source.source, spec.name, "{fts} mirrors a different table"); } for source in FTS_SOURCES { assert!( TABLE_SPECS.iter().any(|spec| spec.name == source.source), "{} mirrors {}, which is not a table spec", source.fts, source.source ); assert!(!source.columns.is_empty(), "{} indexes nothing", source.fts); } } /// RULE: Table names and specs name the same tables once, with valid column keys, so the fold never advertises a missing table or targets an unknown column. #[test] fn table_names_are_unique_and_match_the_specs() { let names: HashSet<&str> = TABLE_NAMES.iter().copied().collect(); assert_eq!( names.len(), TABLE_NAMES.len(), "a table name is declared twice" ); let spec_names: HashSet<&str> = TABLE_SPECS.iter().map(|spec| spec.name).collect(); assert_eq!(names, spec_names, "TABLE_NAMES and TABLE_SPECS disagree"); assert_eq!(spec_names.len(), TABLE_SPECS.len(), "a table spec is declared twice"); for spec in TABLE_SPECS { assert!( spec.columns.iter().any(|(column, _)| *column == spec.pk), "{}'s primary key is not one of its columns", spec.name ); let columns: HashSet<&str> = spec.columns.iter().map(|(name, _)| *name).collect(); assert_eq!( columns.len(), spec.columns.len(), "{} declares a column twice", spec.name ); for key in spec.natural_key { assert!( columns.contains(key), "{}'s natural key names {key}", spec.name ); } } for dropped in DROPPED_TABLES { assert!( !names.contains(dropped), "{dropped} is dropped and still has a spec" ); } } #[test] fn the_ddl_creates_every_table_a_spec_names_and_every_index_a_source_names() { // A spec whose table `SCHEMA_DDL` does not create is a fold that would // write into nothing — the exact drift generating from a real file is // meant to make impossible. // The name a `CREATE …` statement declares: whatever follows the last // keyword, up to the first delimiter SQLite could have put there. // A table SQLite rebuilt under an `ALTER TABLE … RENAME` keeps its name // QUOTED in the stored DDL (`CREATE TABLE "cotton_comments" (…)`), so a // reader that only knows the bare form silently finds nothing. fn created<'a>(sql: &'a str, what: &str) -> Option<&'a str> { let rest = sql.strip_prefix(&format!("CREATE {what} "))?; // A statement a LATER rung also runs carries `IF NOT EXISTS`, so a // fresh file (which runs version 1 — this list — and then every rung // over the top of it) issues it twice. The name is what follows. let rest = rest.strip_prefix("IF NOT EXISTS ").unwrap_or(rest); match rest.strip_prefix('"') { Some(quoted) => quoted.split('"').next(), None => Some( rest.split(['(', ' ', '\n', '\t', '\r']) .next() .unwrap_or(rest), ), } } let names = |what: &'static str| -> HashSet<&'static str> { SCHEMA_DDL .iter() .filter_map(|sql| created(sql, what)) .collect() }; let tables = names("TABLE"); for spec in TABLE_SPECS { assert!( tables.contains(spec.name), "SCHEMA_DDL never creates {}", spec.name ); } let virtuals = names("VIRTUAL TABLE"); for source in FTS_SOURCES { assert!( virtuals.contains(source.fts), "SCHEMA_DDL never creates {}", source.fts ); } } #[test] fn the_ddl_carries_no_implicit_object_sqlite_makes_for_itself() { for sql in SCHEMA_DDL { assert!(!sql.contains("sqlite_autoindex"), "{sql}"); assert!(!sql.contains("sqlite_sequence"), "{sql}"); assert!(!sql.trim().is_empty()); } } #[test] fn the_declared_version_is_the_ladders() { // The claim this test's name makes, said directly. It used to be a // literal, which made the number something two files wrote down and a // schema bump something that had to remember both. assert_eq!(SCHEMA_VERSION, crate::migrate::SCHEMA_VERSION); } }