//! The values of the columns a person ADDED to a shipped table //! (`cotton_core::definitions::owner`, keys `own_…`): People with his own //! "Met at". Each is a REAL COLUMN of the shipped table's own store table //! (`cotton_people.own_met_at`), added in place by the same add-only step as a //! made table's columns (`package_shape::step_own`) when the database's //! definition row names it (architect, 13 Oct 2026: no key/value store). The //! `own_` prefix keeps it clear of every shipped column; a person reads its //! name from the definition. //! //! - **Read.** Every read of a shipped table that has added columns draws //! them in ([`merge`]): only columns the definition still names, so a //! column the person took off is simply not read. //! - **Write.** A create or patch splits its values ([`split`]): the engine is //! handed its own columns, and the added ones are written onto the same row //! ([`write`]) — after the engine made it. The change row records both, so //! Undo puts an added value back through the same split. //! - **Delete.** A delete that bins or archives the record leaves its values //! on it; one its engine makes outright clears them with it ([`clear`]); //! an erase takes the row and its values together. use cotton_core::definitions::owner::is_own_column; use cotton_core::definitions::TableDefinition; use cotton_core::records::Data; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use super::{sql_err, Stored}; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{now_iso, update_row, Valid}; use crate::mcp::protocol::ToolFailure; /// Whether `definition` is a shipped table a person has added columns to. pub fn has_own(definition: &TableDefinition) -> bool { definition.has_engine() && definition.columns.iter().any(|column| is_own_column(&column.key)) } /// `values` as the engine takes them, and the added columns' values apart. pub fn split(definition: &TableDefinition, values: &Data) -> (Data, Data) { if !has_own(definition) { return (values.clone(), Data::new()); } values.iter().map(|(key, value)| (key.clone(), value.clone())).partition(|(key, _)| !is_own_column(key)) } /// The shipped table's store table, and the added columns the definition /// names that this file holds (the step adds them when the definition lands). fn columns(ctx: &Ctx<'_>, definition: &TableDefinition) -> Valid)>> { let Some(store) = cotton_core::definitions::builtin_store_table(&definition.id) else { return Ok(None) }; let held: Vec = ctx .read .driver() .all(&format!("SELECT name FROM pragma_table_info('{store}')"), &[]) .map_err(sql_err)? .iter() .filter_map(|row| row.text("name").map(str::to_owned)) .filter(|name| is_own_column(name) && definition.column(name).is_some()) .collect(); Ok(Some((store, held))) } /// Whether a `where` may name `key`: an added column of `definition`'s, /// of one value. pub fn narrowable(definition: &TableDefinition, key: &str) -> bool { has_own(definition) && is_own_column(key) && definition.column(key).is_some_and(|column| column.multiple != Some(true)) } /// Whether the store table `table` — the one a read narrows — holds the /// added column `key` yet. pub fn holds(ctx: &Ctx<'_>, definition: &TableDefinition, table: &str, key: &str) -> Valid { Ok(columns(ctx, definition)?.is_some_and(|(store, held)| store == table && held.iter().any(|held| held == key))) } /// The file steps to the columns its definitions name, so a value has its /// column before it is written. fn ready(ctx: &Ctx<'_>, definition: &TableDefinition, keys: &Data) -> Valid<(&'static str, Vec)> { let found = columns(ctx, definition)?; if let Some((store, held)) = &found { if keys.keys().all(|key| held.contains(key)) { return Ok((store, held.clone())); } } let (_, refused) = cotton_store::schema::package_shape::step_file(ctx.read.driver()).map_err(sql_err)?; let (store, held) = columns(ctx, definition)?.ok_or_else(|| ToolFailure::new(format!("{} keeps no table here", definition.plural)))?; if let Some(key) = keys.keys().find(|key| !held.contains(key)) { let why = refused.iter().find(|(table, _)| table == store).map(|(_, why)| why.clone()).unwrap_or_else(|| "it is not in the definition".into()); return Err(ToolFailure::new(format!("{} cannot take the column {key}: {why}", definition.plural))); } Ok((store, held)) } /// The added columns' values of record `id`, as its row keeps them. fn held(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid> { let Some((store, held)) = columns(ctx, definition)? else { return Ok(None) }; if held.is_empty() { return Ok(None); } let row = ctx .read .driver() .get(&format!("SELECT * FROM {store} WHERE id = ?"), &[SqlValue::Text(id.to_string())]) .map_err(sql_err)?; Ok(row.map(|row| values_of(definition, &row, &held))) } /// A row's added-column values, as the definition's types read them. fn values_of(definition: &TableDefinition, row: &cotton_store::Row, held: &[String]) -> Data { use cotton_core::definitions::ColumnType; held.iter() .filter_map(|key| { let bool_column = definition.column(key).is_some_and(|c| c.column_type == ColumnType::Bool); let value = match row.get(key)? { SqlValue::Null => return None, SqlValue::Integer(n) if bool_column => Value::Bool(*n != 0), SqlValue::Integer(n) => Value::from(*n), SqlValue::Real(x) => Value::from(*x), SqlValue::Text(text) => Value::from(text.clone()), SqlValue::Blob(_) => return None, }; Some((key.clone(), value)) }) .collect() } /// Draw each record's added-column values into its data: only columns the /// definition names as added, never a shipped one. pub fn merge(ctx: &Ctx<'_>, definition: &TableDefinition, records: &mut [Stored]) -> Valid<()> { if !has_own(definition) || records.is_empty() { return Ok(()); } let Some((store, held)) = columns(ctx, definition)? else { return Ok(()) }; if held.is_empty() { return Ok(()); } for chunk in records.chunks_mut(super::IN_CHUNK) { let params: Vec = chunk.iter().map(|record| SqlValue::Text(record.id.clone())).collect(); let sql = format!("SELECT * FROM {store} WHERE id IN ({})", vec!["?"; chunk.len()].join(", ")); for row in ctx.read.driver().all(&sql, ¶ms).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, value) in values_of(definition, &row, &held) { record.data.insert(key, value); } } } Ok(()) } /// Write the added columns' values `own` of record `id` onto its row — only /// the columns that moved, a cleared one as null. The caller commits. pub fn write(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, own: &Data) -> Valid<()> { if own.is_empty() { return Ok(()); } let (store, _) = ready(ctx, definition, own)?; let was = held(ctx, definition, id)?.unwrap_or_default(); let moved: Map = own .iter() .filter(|(key, value)| was.get(*key).unwrap_or(&Value::Null) != *value) .map(|(key, value)| (key.clone(), value.clone())) .collect(); if moved.is_empty() { return Ok(()); } let mut patch = moved; patch.insert("updated_at".into(), Value::from(now_iso(ctx))); update_row(ctx, store, id, patch) } /// Clear every added column's value of record `id` (its engine deleted it /// outright). The caller commits. pub fn clear(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> { let Some(was) = held(ctx, definition, id)? else { return Ok(()) }; let cleared: Data = was.keys().map(|key| (key.clone(), Value::Null)).collect(); write(ctx, definition, id, &cleared) } /// The record is being erased: its added columns' values go with its row, /// so nothing is left to erase apart. pub fn erase(_ctx: &mut Ctx<'_>, _id: &str) -> Valid<()> { Ok(()) }