//! Making a file. //! //! [`create_workspace`] builds a fresh file in ONE transaction: the flat DDL //! ([`crate::schema::ddl::SCHEMA_DDL`], every phase), the //! `PRAGMA user_version` stamp at `SCHEMA_VERSION`, and the identity row. //! //! **A fresh file IS the flat DDL.** There is no ladder to climb: the one rung //! in [`crate::migrate::MIGRATIONS`] issues the same list. The guard against a //! shape change nobody recorded is `tests/schema_snapshot.rs`, which holds what //! this builds equal to the committed snapshot, and the shape ledger, which //! carries a SHAPE line for every change. //! //! The statements can also be applied in phases ([`SchemaPhase`]). A phase is //! read from each statement's leading keywords, independent of its position //! in the list. use serde::{Deserialize, Serialize}; use crate::driver::Driver; use crate::error::{Result, StoreError}; use crate::meta::{seed_meta, Meta}; use crate::migrate::SCHEMA_VERSION; #[cfg(test)] use crate::migrate::schema_statements; /// One `sqlite_master` object that belongs to a file's schema. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SchemaObject { /// `table`, `index`, `trigger` — SQLite's own word. pub kind: String, pub name: String, pub tbl_name: String, pub sql: String, } impl SchemaObject { /// An FTS5 index rather than an ordinary table. Read off the stored SQL /// because there is no other way to ask: `sqlite_master.type` is `table` /// for a virtual table too. pub fn is_fts5_virtual(&self) -> bool { self.kind == "table" && self.sql.to_ascii_lowercase().contains("using fts5") } } /// Which group of the flat DDL's statements a statement belongs to. /// /// The order of the variants is the order the phases must be issued in: a /// trigger cannot be created before the tables it names, and an index cannot /// be created before its table. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum SchemaPhase { /// `CREATE TABLE` — ordinary tables, the system tables among them. Tables, /// `CREATE VIRTUAL TABLE` — the FTS5 indexes. Fts, /// `CREATE INDEX` and `CREATE UNIQUE INDEX`. Indexes, /// `CREATE TRIGGER` — the FTS mirrors and the record-version writers. Triggers, } impl SchemaPhase { /// Every phase, in issue order. pub const ALL: [SchemaPhase; 4] = [ SchemaPhase::Tables, SchemaPhase::Fts, SchemaPhase::Indexes, SchemaPhase::Triggers, ]; } /// The phase a statement belongs to, read off its own leading keywords. /// /// `None` for a shape this crate does not know, and a `None` is FATAL rather /// than skipped ([`apply_schema_phases`] refuses on one): a statement no phase /// claims would simply never be issued, and a file missing an object nobody /// noticed is the exact failure the generator exists to prevent. pub fn phase_of(statement: &str) -> Option { let text = statement.trim_start(); // Longest prefix first: `CREATE TABLE` is a prefix of nothing here, but // `CREATE UNIQUE INDEX` and `CREATE VIRTUAL TABLE` both start `CREATE ` and // a shorter match would claim them. for (prefix, phase) in [ ("CREATE VIRTUAL TABLE ", SchemaPhase::Fts), ("CREATE UNIQUE INDEX ", SchemaPhase::Indexes), ("CREATE INDEX ", SchemaPhase::Indexes), ("CREATE TRIGGER ", SchemaPhase::Triggers), ("CREATE TABLE ", SchemaPhase::Tables), ] { if text.len() >= prefix.len() && text[..prefix.len()].eq_ignore_ascii_case(prefix) { return Some(phase); } } None } /// Issue the statements belonging to `phases`, phase by phase in issue order /// and, within a phase, in the list's own order. /// /// Every statement is classified BEFORE any is issued, so a statement list the /// generator wrote in a shape this crate cannot read refuses the whole build /// rather than silently leaving something out of it. pub fn apply_schema_phases(db: &Driver, phases: &[SchemaPhase]) -> Result<()> { let statements = crate::schema::package_tables::fresh_schema()?; let mut classified = Vec::with_capacity(statements.len()); for statement in statements { let Some(phase) = phase_of(&statement) else { let head: String = statement.chars().take(60).collect(); return Err(StoreError::refused(format!( "cotton-store: the flat DDL carries a statement this build cannot place \ in a phase, so it would never be issued: {head}…" ))); }; classified.push((phase, statement)); } for phase in SchemaPhase::ALL { if !phases.contains(&phase) { continue; } for (of, statement) in &classified { if *of == phase { db.exec(statement)?; } } } Ok(()) } /// The flat DDL's whole shape on an empty file, in issue order, without /// identity and without the `user_version` stamp. pub fn apply_schema(db: &Driver) -> Result<()> { apply_schema_phases(db, &SchemaPhase::ALL) } /// Build a fresh file: the schema, the identity, the stamp — one transaction, /// so a file that fails half way through is a file that was never created. /// /// Refuses a file that already carries a schema, BEFORE issuing a statement. /// Without the check the first `CREATE TABLE` fails with "table _meta already /// exists" — true, rolled back, and no help at all to someone who has just /// pointed `create` at the file holding their life. pub fn create_workspace(db: &Driver, meta: &Meta) -> Result<()> { let stamped = crate::meta::file_schema_version(db)?; let existing = schema_objects(db)?; if stamped != 0 || !existing.is_empty() { return Err(StoreError::refused(format!( "cotton-store: this file already has a schema ({} objects, stamped {stamped}) — \ `create` makes a NEW file; the file was not touched", existing.len() ))); } // The schema, the stamp and the identity are ONE transaction, so a create // that fails half way is a create that never happened. db.transaction(|db| { apply_schema(db)?; // PRAGMA does not accept a bound parameter; the value is this crate's // own constant. db.exec(&format!("PRAGMA user_version = {SCHEMA_VERSION}"))?; seed_meta(db, meta, SCHEMA_VERSION) })?; Ok(()) } /// The schema of an OPEN file, as the comparison sees it. /// /// Three kinds of object are left out, and each for its own reason: /// /// - `sql IS NULL` — SQLite's implicit indexes behind a UNIQUE or a /// non-INTEGER PRIMARY KEY. There is no statement, and re-creating the table /// re-creates them. /// - `sqlite_sequence` — AUTOINCREMENT bookkeeping SQLite creates itself. /// - the FTS5 shadow tables — `fts_x_data` and its four siblings are carried in /// `sqlite_master` with real DDL, but `CREATE VIRTUAL TABLE` is what makes /// them, and their layout is the module's business rather than the file's. /// /// The same three the flat DDL's own statements leave out, for the same /// reasons — which is what makes the two sets comparable at all. pub fn schema_objects(db: &Driver) -> Result> { let rows = db.all( "SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name", &[], )?; let all: Vec = rows .into_iter() .filter_map(|row| { Some(SchemaObject { kind: row.text("type")?.to_string(), name: row.text("name")?.to_string(), tbl_name: row.text("tbl_name")?.to_string(), // A NULL `sql` is an implicit index; `text` answers None for it. sql: row.text("sql")?.to_string(), }) }) .collect(); let fts_names: Vec = all .iter() .filter(|object| object.is_fts5_virtual()) .map(|object| object.name.clone()) .collect(); Ok(all .into_iter() .filter(|object| object.name != "sqlite_sequence") .filter(|object| !is_fts_shadow(&object.name, &fts_names)) .collect()) } /// `_data`, `_idx`, `_docsize`, `_config`, `_content`. 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)) }) } /// The schema a fresh `create` produces, built on a throwaway in-memory file. /// /// Read from a real SQLite rather than parsed out of the statements, because what /// schema comparisons need is what SQLite STORES — and SQLite rewrites some of /// it (a table rebuilt under an `ALTER TABLE … RENAME` keeps its name quoted). /// Parsing the statements would compare the wrong text. pub fn fresh_schema() -> Result> { let db = Driver::open_in_memory()?; apply_schema(&db)?; schema_objects(&db) } /// Where a file stands in its birth — THE question "is this file a born /// database", asked by everything that must not mistake a half-born file for /// a finished one or write into one. /// /// **Born is the stamp.** [`create_workspace`] issues the schema, the /// `user_version` stamp and `_meta` in one transaction, so a nonzero stamp is a /// file whose birth committed and a zero stamp is one whose birth never did — /// whatever else a stray writer left in it. #[derive(Debug, Clone, PartialEq, Eq)] pub enum FileBirth { /// Stamped: a finished database (of this build or another). Born, /// Unstamped and holding nothing at all. Empty, /// Unstamped and holding only device-local tables the store schema does /// not create (a worker's `CREATE TABLE IF NOT EXISTS _money_state` that /// reached the file before its birth). Their names, sorted. Strays(Vec), /// Unstamped and holding something else — a store table, or a table /// nothing here knows. Never finished in place and never cleared: the /// names, so a refusal can say what is there. Foreign(Vec), } /// [`FileBirth`] of an open file. One `PRAGMA` for a born file; the objects are /// read only for an unstamped one. pub fn file_birth(db: &Driver) -> Result { if crate::meta::file_schema_version(db)? != 0 { return Ok(FileBirth::Born); } let objects = schema_objects(db)?; if objects.is_empty() { return Ok(FileBirth::Empty); } let store = store_object_names()?; let stray = |object: &SchemaObject| { object.tbl_name.starts_with('_') && !store.contains(&object.tbl_name) && !store.contains(&object.name) }; let mut foreign: Vec = objects .iter() .filter(|object| !stray(object)) .map(|object| object.name.clone()) .collect(); if !foreign.is_empty() { foreign.sort(); return Ok(FileBirth::Foreign(foreign)); } let mut tables: Vec = objects .into_iter() .filter(|object| object.kind == "table") .map(|object| object.name) .collect(); tables.sort(); tables.dedup(); Ok(FileBirth::Strays(tables)) } /// Drop the stray device-local tables an unborn file holds, so its birth can /// run on an empty file. Refused, touching nothing, for any file that is not /// [`FileBirth::Empty`] or [`FileBirth::Strays`]. Answers what it dropped. pub fn clear_strays(db: &Driver) -> Result> { db.transaction(|db| match file_birth(db)? { FileBirth::Empty => Ok(Vec::new()), FileBirth::Strays(tables) => { for table in &tables { db.exec(&format!("DROP TABLE \"{}\"", table.replace('"', "\"\"")))?; } Ok(tables) } FileBirth::Born => Err(StoreError::refused( "cotton-store: this file is a born database; nothing in it is a stray, and it was not touched", )), FileBirth::Foreign(names) => Err(StoreError::refused(format!( "cotton-store: this unborn file holds {} — not only device-local worker tables — so it is \ neither finished in place nor cleared; the file was not touched", names.join(", ") ))), }) } /// Every object name the flat DDL creates, built once per process. fn store_object_names() -> Result<&'static std::collections::HashSet> { static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new(); if let Some(names) = NAMES.get() { return Ok(names); } let names = fresh_schema()? .into_iter() .flat_map(|object| [object.name, object.tbl_name]) .collect(); Ok(NAMES.get_or_init(|| names)) } #[cfg(test)] mod tests { use super::*; #[test] fn a_file_is_born_by_its_stamp_and_a_stray_worker_table_is_not_a_birth() { let db = Driver::open_in_memory().expect("opens"); assert_eq!(file_birth(&db).expect("asks"), FileBirth::Empty); db.exec("CREATE TABLE _money_state (job TEXT PRIMARY KEY)").expect("a stray"); db.exec("CREATE INDEX _money_state_job ON _money_state (job)").expect("its index"); assert_eq!( file_birth(&db).expect("asks"), FileBirth::Strays(vec!["_money_state".to_string()]) ); assert_eq!(clear_strays(&db).expect("clears"), vec!["_money_state".to_string()]); assert_eq!(file_birth(&db).expect("asks"), FileBirth::Empty); create_workspace(&db, &meta()).expect("an empty file is born"); assert_eq!(file_birth(&db).expect("asks"), FileBirth::Born); assert!(clear_strays(&db).is_err(), "a born file is never cleared"); } #[test] fn an_unborn_file_holding_a_store_table_or_an_unknown_one_is_foreign_and_never_cleared() { for statement in [ crate::schema::ddl::PARKED_TABLE, "CREATE TABLE notes (body TEXT)", ] { let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE _media_index (source TEXT PRIMARY KEY)").expect("a stray"); db.exec(statement).expect("something else"); assert!( matches!(file_birth(&db).expect("asks"), FileBirth::Foreign(_)), "{statement}" ); assert!(clear_strays(&db).is_err(), "{statement}"); assert_eq!(schema_objects(&db).expect("reads").len(), 2, "nothing was dropped"); } } fn meta() -> Meta { Meta { workspace_id: "11111111-1111-4111-8111-111111111111".to_string(), owner_id: "owner-1".to_string(), device_id: "device:01J0000000000000000000000A".to_string(), last_server_seq: 0, last_hlc: None, } } #[test] fn a_created_file_is_the_fresh_schema_stamped_at_this_version() { let db = Driver::open_in_memory().expect("opens"); create_workspace(&db, &meta()).expect("creates"); assert_eq!( schema_objects(&db).expect("reads the schema"), fresh_schema().expect("builds") ); assert_eq!( crate::migrate::current_version(&db).expect("reads"), SCHEMA_VERSION ); assert_eq!( crate::meta::file_schema_version(&db).expect("reads"), SCHEMA_VERSION ); assert_eq!( crate::meta::read_meta(&db).expect("reads").expect("seeded"), meta() ); let row = db .get("SELECT schema_version FROM _meta", &[]) .expect("reads") .expect("a row"); assert_eq!(row.int("schema_version"), Some(i64::from(SCHEMA_VERSION))); } #[test] fn a_created_file_and_the_canonical_dump_agree_about_what_the_schema_is() { // Two modules answer "which objects are the schema" — this one and // `dump`. They must agree on which objects belong to the schema. let db = Driver::open_in_memory().expect("opens"); create_workspace(&db, &meta()).expect("creates"); let dumped = crate::dump::dump(&db).expect("dumps"); let named: Vec = dumped["schema"] .as_array() .expect("an array") .iter() .filter(|entry| !entry["sql"].is_null()) .map(|entry| entry["name"].as_str().expect("a name").to_string()) .collect(); let mut ours: Vec = schema_objects(&db) .expect("reads") .into_iter() .map(|object| object.name) .collect(); let mut theirs = named; ours.sort(); theirs.sort(); assert_eq!(ours, theirs); } #[test] fn two_created_files_have_the_same_schema() { let a = Driver::open_in_memory().expect("opens"); let b = Driver::open_in_memory().expect("opens"); create_workspace(&a, &meta()).expect("creates"); create_workspace(&b, &meta()).expect("creates"); assert_eq!( crate::dump::dump(&a).expect("dumps")["schema"], crate::dump::dump(&b).expect("dumps")["schema"] ); } #[test] fn creating_over_a_file_that_already_has_one_is_refused_by_name() { let db = Driver::open_in_memory().expect("opens"); create_workspace(&db, &meta()).expect("creates"); let mut other = meta(); other.workspace_id = "22222222-2222-4222-8222-222222222222".to_string(); let error = create_workspace(&db, &other).expect_err("a second create is refused"); let message = error.to_string(); assert!(message.contains("already has a schema"), "got {message}"); assert!( message.contains("`create` makes a NEW file"), "got {message}" ); // And the first identity survives, untouched. assert_eq!( crate::meta::read_meta(&db).expect("reads").expect("seeded"), meta() ); } #[test] fn creating_into_a_file_that_only_has_an_identity_still_refuses() { // The narrower shape: no schema stamp, but somebody's `_meta` is there. // `seed_meta` would catch it — this catches it a statement earlier. let db = Driver::open_in_memory().expect("opens"); crate::meta::create_system_tables(&db).expect("system tables"); let error = create_workspace(&db, &meta()).expect_err("refused"); assert!( error.to_string().contains("already has a schema"), "got {error}" ); } #[test] fn every_generated_statement_lands_in_exactly_one_phase() { // A statement no phase claims would simply never be issued, and the // file would be missing an object with nothing said. The count has to // add up to the whole list. let mut counted = 0; for statement in schema_statements() { assert!( phase_of(statement).is_some(), "no phase claims: {}", &statement[..statement.len().min(60)] ); counted += 1; } assert_eq!(counted, schema_statements().len()); } #[test] fn the_phases_read_the_statement_rather_than_its_position() { assert_eq!( phase_of("CREATE TABLE cotton_todos (id TEXT)"), Some(SchemaPhase::Tables) ); assert_eq!( phase_of("CREATE VIRTUAL TABLE fts_todos USING fts5(title)"), Some(SchemaPhase::Fts) ); assert_eq!( phase_of("CREATE INDEX idx_x ON cotton_todos (id)"), Some(SchemaPhase::Indexes) ); assert_eq!( phase_of("CREATE UNIQUE INDEX uq_x ON cotton_todos (id)"), Some(SchemaPhase::Indexes) ); assert_eq!( phase_of("CREATE TRIGGER t AFTER INSERT ON cotton_todos BEGIN SELECT 1; END"), Some(SchemaPhase::Triggers) ); // A virtual table is NOT a table: the longer prefix has to win, or // every FTS index would be created in the first phase and the copy // would run with them present. assert_ne!( phase_of("CREATE VIRTUAL TABLE fts_todos USING fts5(title)"), Some(SchemaPhase::Tables) ); assert_eq!(phase_of("DROP TABLE cotton_todos"), None); assert_eq!(phase_of("ALTER TABLE cotton_todos ADD COLUMN x TEXT"), None); } #[test] fn a_file_built_without_the_trigger_phase_has_the_tables_and_no_triggers() { let db = Driver::open_in_memory().expect("opens"); apply_schema_phases( &db, &[SchemaPhase::Tables, SchemaPhase::Fts, SchemaPhase::Indexes], ) .expect("applies"); let objects = schema_objects(&db).expect("reads"); assert!(objects.iter().all(|object| object.kind != "trigger")); assert!(objects.iter().any(|object| object.name == "cotton_todos")); assert!(objects.iter().any(|object| object.name == "fts_todos")); assert!(objects.iter().any(|object| object.kind == "index")); // And the triggers land on a second pass, over the same file. apply_schema_phases(&db, &[SchemaPhase::Triggers]).expect("applies"); assert_eq!( schema_objects(&db).expect("reads").len(), schema_statements().len() ); } #[test] fn the_fresh_schema_is_the_ddl_and_nothing_else() { let objects = fresh_schema().expect("builds"); assert_eq!(objects.len(), schema_statements().len()); for object in &objects { assert_ne!(object.name, "sqlite_sequence"); assert!(!object.name.starts_with("sqlite_autoindex")); assert!(!object.sql.is_empty()); } // The shadow tables are made by the module and never compared. for object in &objects { assert!(!object.name.ends_with("_docsize"), "{}", object.name); } } }