Cotton code
193 lines · 9.7 KB · RustRaw
//! The values of the columns a phone's copy keeps for the object's//! definition of a shipped table (`cotton_store::schema::package_shape:://! add_served`): the running balance the object's money engine writes on//! every transaction (`balance_before_minor`, `balance_after_minor`), which//! this build's `cotton_money_transactions` has no column for. The copy adds//! the column when the served definition names it and the pull fills it; a//! read draws it here, so a list, a page and a card say what the object said.//!//! - **The object's, unless the definition gives it to the person.** A//!   column the definition marks read-only (a balance) is the object's and a//!   write here never names one. A column it leaves the person (an event's//!   kind, chosen on the fan; its picture) is written here into the copy's//!   column ([`split`], [`write`]), and the phone's push sends it with the//!   storage map's columns (`cotton_client::transport::object`), so the//!   object sees the person's write.//! - **Typed by the definition.** Only a column the definition names, not//!   computed, of the type its column says (a flag a boolean, a list its//!   JSON's values).//! - **The phone's own engine first for scalar facts.** Relationship lists//!   include both the engine's links and the object's served links.use cotton_core::definitions::{ColumnType, TableDefinition};use cotton_core::rules::people::birthday;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use super::{sql_err, Stored};use cotton_core::records::{Condition, WhereClause};use crate::mcp::read_db::{Filter, Query};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{now_iso, update_row, Valid};use crate::mcp::protocol::ToolFailure;/// The served columns of `definition`'s store table this file holds that the/// definition names as stored columns, with the table. A shipped table with no/// engine (a device key, on `cotton_vault_keys`) has served columns too; only/// an engine binding other than the one compiled for the table reads none.fn columns(ctx: &Ctx<'_>, definition: &TableDefinition) -> Valid<Option<(&'static str, Vec<String>)>> {    if definition.engine.is_some() && !definition.has_engine() {        return Ok(None);    }    let Some(store) = definition.store_table() else { return Ok(None) };    let held = cotton_store::schema::package_shape::served_on(ctx.read.driver(), store)        .map_err(|error| ToolFailure::new(error.to_string()))?        .into_iter()        .filter(|name| definition.column(name).is_some_and(|column| column.computed.is_none()))        .collect();    Ok(Some((store, held)))}/// Whether this file holds `column` as a served column of `definition`'s/// store table (named by the definition, not computed).pub(super) fn holds(ctx: &Ctx<'_>, definition: &TableDefinition, column: &str) -> Valid<bool> {    Ok(columns(ctx, definition)?.is_some_and(|(_, held)| held.iter().any(|name| name == column)))}/// One stored value as the definition's column reads it.fn value_of(definition: &TableDefinition, key: &str, value: &SqlValue) -> Option<Value> {    let column = definition.column(key)?;    match value {        SqlValue::Null | SqlValue::Blob(_) => None,        SqlValue::Integer(n) if column.column_type == ColumnType::Bool => Some(Value::Bool(*n != 0)),        SqlValue::Integer(n) => Some(Value::from(*n)),        SqlValue::Real(x) => Some(Value::from(*x)),        SqlValue::Text(text) if column.multiple == Some(true) => serde_json::from_str(text).ok(),        SqlValue::Text(text) => Some(Value::from(text.clone())),    }}/// Draw each record's served-column values into its data, beside what the/// read already answered.pub fn merge(ctx: &Ctx<'_>, definition: &TableDefinition, records: &mut [Stored]) -> Valid<()> {    if records.is_empty() {        return Ok(());    }    let Some((store, held)) = columns(ctx, definition)? else { return Ok(()) };    if held.is_empty() {        return Ok(());    }    let selected: Vec<String> = held.iter().map(|name| format!("\"{name}\"")).collect();    for chunk in records.chunks_mut(400) {        let params: Vec<SqlValue> = chunk.iter().map(|record| SqlValue::Text(record.id.clone())).collect();        let sql = format!(            "SELECT id, {} FROM {store} WHERE id IN ({})",            selected.join(", "),            vec!["?"; chunk.len()].join(", ")        );        for row in ctx.read.driver().all(&sql, &params).map_err(sql_err)? {            let Some(id) = row.text("id") else { continue };            let Some(record) = chunk.iter_mut().find(|record| record.id == id) else { continue };            for key in &held {                if let (Some(Value::Array(held)), Some(Value::Array(served))) = (                    record.data.get_mut(key), row.get(key).and_then(|value| value_of(definition, key, value)),                ) {                    if definition.column(key).is_some_and(|column| column.column_type == ColumnType::Link && column.multiple == Some(true)) {                        for value in served {                            if !held.contains(&value) { held.push(value); }                        }                    }                    continue;                }                if record.data.get(key).is_some_and(|value| !value.is_null()) {                    continue;                }                if let Some(value) = row.get(key).and_then(|value| value_of(definition, key, value)) {                    record.data.insert(key.clone(), value);                }            }        }    }    Ok(())}/// The keys of `patch` that are served columns of `definition`'s store table/// the person writes (held in this file, named by the definition, neither/// read-only nor computed), taken out of it: what [`write`] writes.pub fn split(ctx: &Ctx<'_>, definition: &TableDefinition, patch: &mut Map<String, Value>) -> Valid<Map<String, Value>> {    let Some((store, held)) = columns(ctx, definition)? else { return Ok(Map::new()) };    let mut served = Map::new();    for key in held {        // A person's birthday is the people engine's to write, both its        // forms in one write (`rules::people::birthday`), never the whole        // date alone beside parts that would still say the old day.        if store == birthday::PEOPLE_TABLE && key == birthday::WHOLE_COLUMN {            continue;        }        let writes = definition.column(&key).is_some_and(|column| column.readonly != Some(true));        if writes {            if let Some(value) = patch.remove(&key) {                served.insert(key, value);            }        }    }    Ok(served)}/// The person's values of served columns ([`split`]) written into the/// record's row, stamped as changed now.pub fn write(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, values: Map<String, Value>) -> Valid<()> {    if values.is_empty() {        return Ok(());    }    let Some(store) = definition.store_table() else {        return Err(ToolFailure::new(format!("{} keeps no row of its own to write into", definition.plural)));    };    let mut patch = values;    patch.insert("updated_at".into(), Value::String(now_iso(ctx)));    update_row(ctx, store, id, patch)?;    ctx.commit()}/// A relationship can be held by the native engine and by the object's/// served column. Read the same union the card receives, before pagination,/// so a related deck's total and its records agree with its visible people.pub(super) fn narrow_links(    ctx: &Ctx<'_>, definition: &TableDefinition, clause: &WhereClause,    engine: fn(&Ctx<'_>, &TableDefinition, &Condition) -> Valid<Vec<Filter>>,) -> Valid<Vec<Filter>> {    let held = columns(ctx, definition)?;    let stored_link = definition.column(&clause.column).is_some_and(|column|        column.column_type == ColumnType::Link && column.multiple == Some(true));    let Some((store, _columns)) = held.filter(|(_, columns)| stored_link && columns.contains(&clause.column)) else {        return engine(ctx, definition, &clause.condition);    };    let without = matches!(clause.condition, Condition::Present(false));    let condition = if without { &Condition::Present(true) } else { &clause.condition };    let mut native = Query::on(store).columns(&["id"]);    for filter in engine(ctx, definition, condition)? { native = native.filter(filter); }    let mut ids: Vec<String> = ctx.read.select(&native).map_err(sql_err)?.iter()        .filter_map(|row| row.get("id").and_then(Value::as_str).map(str::to_string)).collect();    // The column name comes only from served_on's schema declaration;    // values remain bound parameters and membership is counted in SQLite.    let wanted: Vec<&Value> = match condition {        Condition::Is(value) => vec![value],        Condition::OneOf(values) => values.iter().collect(),        Condition::Present(true) => Vec::new(),        _ => unreachable!("the engine refuses unsupported link conditions"),    };    let params: Vec<SqlValue> = wanted.iter().filter_map(|value| value.as_str().map(|value| SqlValue::Text(value.into()))).collect();    let membership = if matches!(condition, Condition::Present(true)) {        String::new()    } else {        format!(" WHERE linked.type = 'text' AND linked.value IN ({})", vec!["?"; params.len()].join(","))    };    let sql = format!("SELECT id FROM {store} WHERE EXISTS (SELECT 1 FROM json_each(\"{}\") linked{membership})", clause.column);    for row in ctx.read.driver().all(&sql, &params).map_err(sql_err)? {        if let Some(id) = row.text("id") { ids.push(id.to_string()); }    }    ids.sort();    ids.dedup();    let ids = ids.into_iter().map(SqlValue::Text).collect();    Ok(vec![if without { Filter::NotIn("id".into(), ids) } else { Filter::In("id".into(), ids) }])}