Cotton code
145 lines · 6.0 KB · RustRaw
//! `_computed` — the device-local index of computed columns — and the hook//! that keeps it in step with the rows.//!//! A computed column (a lookup, a rollup, a formula) is stored in no synced//! column: every device works it out from the records it holds, with the one//! implementation, so no two devices can hold rows that disagree. This crate//! knows no definitions, so the working out is handed in: a process installs//! its [`Derive`] once ([`install`]), and EVERY fold on every handle calls it//! — inside the fold's own transaction, with the rows that fold changed, so//! a reader never sees a record without the values derived from it. One//! pass for the process, not one per handle: a handle opened somewhere that//! forgot to ask for it would fold records and leave the index quietly wrong.//!//! **A derive pass never fails a fold.** The index is derived; the rows are//! the truth. A pass that errors is rolled back to where it started and the//! index is marked stale ([`mark_stale`]) — as it is by a fold in a process//! that installed no pass at all — and the next background pass or fold//! answers a stale index with a full rebuild.use std::sync::{Arc, OnceLock};use crate::driver::Driver;use crate::error::Result;use rusqlite::types::Value as SqlValue;/// Works out a file's computed columns. Implemented where the definitions/// are known.pub trait Derive: Send + Sync {    /// Whether a change to a row of `table` can move a computed value.    fn reads(&self, table: &str) -> bool;    /// Bring `_computed` in step with `rows` — `(store table, row id)`, the    /// rows a fold just changed — inside that fold's transaction.    fn derive(&self, db: &Driver, rows: &[(String, String)]) -> Result<()>;    /// Fill the typed columns an engine works out on this device (a money    /// row's running balance on a copy the object has not stamped), after    /// `rows` folded, inside that fold's transaction. Run on every fold,    /// whatever the state of `_computed`: a fold resets a column no receipt    /// names, so the engine fills it again in the same transaction and a    /// reader never sees it empty.    fn fill(&self, _db: &Driver, _rows: &[(String, String)]) -> Result<()> {        Ok(())    }}static DERIVE: OnceLock<Arc<dyn Derive>> = OnceLock::new();/// Give this process its derive pass. The first one stands.pub fn install(derive: Arc<dyn Derive>) {    let _ = DERIVE.set(derive);}/// The tables whose rows a computed column can read when no pass is/// installed to say: the definitions, and every made table's own table/// (a name no compiled spec owns, `package_shape::may_arrive`).const READ_WITHOUT_A_PASS: &[&str] = &["cotton_table_definitions"];fn read_without_a_pass(table: &str) -> bool {    READ_WITHOUT_A_PASS.contains(&table) || crate::schema::package_shape::may_arrive(table)}/// The row that says which derivation `_computed` was last rebuilt whole by:/// no table has the empty id, so it can never be a record's.const MARKER: (&str, &str, &str) = ("", "", "derivation");/// The fold's call, with the rows it changed. An error inside the pass/// undoes the pass alone and marks the index stale; so does a fold in a/// process with no pass. The fold stands either way.pub(crate) fn after_fold(db: &Driver, rows: &[(String, String)]) {    // An engine's fill is undone alone when it errs; the fold stands, and    // the next fold that moves its inputs fills again.    if let Some(derive) = DERIVE.get() {        let _ = db.transaction(|db| derive.fill(db, rows));    }    let stale = match DERIVE.get() {        Some(derive) => {            rows.iter().any(|(table, _)| derive.reads(table))                && (!db.derivation_ready() || db.transaction(|db| derive.derive(db, rows)).is_err())        }        None => rows.iter().any(|(table, _)| read_without_a_pass(table)),    };    if stale {        // A file with no `_computed` (a test's bare protocol tables) has no        // index to mark.        let _ = db.transaction(mark_stale);    }}/// The derivation `_computed` was last rebuilt whole by, if it is not stale.pub fn derivation(db: &Driver) -> Result<Option<String>> {    Ok(db        .get(            "SELECT value FROM _computed WHERE table_id = ? AND record_id = ? AND key = ?",            &marker(),        )?        .and_then(|row| row.text("value").map(str::to_string)))}/// [`derivation`] of the file's own `_computed`, never a TEMP one this/// connection works a rebuild out on — an unqualified name finds that first.pub fn main_derivation(db: &Driver) -> Result<Option<String>> {    Ok(db        .get(            "SELECT value FROM main._computed WHERE table_id = ? AND record_id = ? AND key = ?",            &marker(),        )?        .and_then(|row| row.text("value").map(str::to_string)))}/// Say `_computed` was rebuilt whole by `derivation`.pub fn mark_rebuilt(db: &Driver, derivation: &str) -> Result<()> {    let mut params = marker();    params.push(SqlValue::Text(derivation.to_string()));    db.run(        "INSERT INTO _computed (table_id, record_id, key, value) VALUES (?, ?, ?, ?) \         ON CONFLICT (table_id, record_id, key) DO UPDATE SET value = excluded.value",        &params,    )?;    Ok(())}/// The key each table's stamp is kept under, on the row whose `record_id`/// is the table's id: what that table's values were worked out from.pub const STAMP: &str = "stamp";/// Say `_computed` can no longer be trusted: the next derive pass rebuilds/// it whole. Its stamps go with the marker — rows that no pass derived are/// in no table's values, whatever the table's stamp says.pub fn mark_stale(db: &Driver) -> Result<()> {    db.run(        "DELETE FROM _computed WHERE table_id = ? AND record_id = ? AND key = ?",        &marker(),    )?;    db.run("DELETE FROM _computed WHERE table_id = '' AND key = ?", &[SqlValue::Text(STAMP.to_string())])?;    Ok(())}fn marker() -> Vec<SqlValue> {    vec![        SqlValue::Text(MARKER.0.to_string()),        SqlValue::Text(MARKER.1.to_string()),        SqlValue::Text(MARKER.2.to_string()),    ]}