//! Soft references: a column that only POINTS at a row of another table. //! //! The groundwork (design 3.9) classifies every reference between replicated //! tables as owning or soft. An owning reference means the child is present //! only while its parent is. A SOFT reference is only a value: the row stands //! on its own, and the value **reads as empty while the row it names is not //! present** — trashed, archived, deleted, or never in this file — and reads //! as the name again when that row comes back (an undo). Nothing is nulled on //! the row for a parent going away, so nothing is lost when it returns. //! //! That rule is written ONCE, here, as SQL fragments, and every reader that //! asks "does this soft column name a present row" says it through them: //! //! - [`soft_names`]: the column names a row that is present. //! - [`soft_absent`]: it does not (null, or its row is not present). //! - [`soft_value`]: the value to SHOW — the name while present, else null. //! The generic row projection (`cotton_tools::mcp::read_db`) reads every //! soft column of a table through it, so a handler never sees a name that //! points at nothing. //! //! A raw `col IS NULL`, `col IS NOT NULL` or `col = ?` on a soft column //! outside these fragments is caught by the guard //! `tests/no_raw_sql_tests_a_soft_ref_column_outside_the_fragment.rs`, whose //! allow-list names the readers slice 3b has not moved yet. //! //! The list of soft references is [`SOFT_REFS`] in `schema/table_specs.rs` //! (store-ddl's file, held equal to the live foreign keys there). This module //! only reads it. //! //! Two of them may name a row in another database //! ([`SOFT_REF_DATABASES`]): while the column beside them names that //! database, the row is out of this file's sight, so the fragment reads the //! value as named rather than empty (several databases 4.2). use crate::schema::table_specs::{SOFT_REFS, SOFT_REF_DATABASES, TABLE_SPECS}; /// The columns that say a row is NOT present while set. A row of a table /// without any of them is present whenever it exists. /// /// `hidden_at` (a message the owner hid), `revoked_at` (a token) and a /// `status` of `archived`/`done` are deliberately not here: the row is still /// present, only its standing changed, and a reference to it still names it. pub const GONE_COLUMNS: [&str; 3] = ["deleted_at", "trashed_at", "archived_at"]; /// The parent table a soft column names, or `None` when `(table, column)` is /// not a soft reference. pub fn parent_of(table: &str, column: &str) -> Option<&'static str> { SOFT_REFS .iter() .find(|(child, child_column, _)| *child == table && *child_column == column) .map(|(_, _, parent)| *parent) } /// Every soft column of `table`, as `(column, parent table)`. pub fn soft_columns(table: &str) -> impl Iterator + '_ { SOFT_REFS .iter() .filter(move |(child, _, _)| *child == table) .map(|(_, column, parent)| (*column, *parent)) } /// Which of [`GONE_COLUMNS`] `table` has, from `TABLE_SPECS`. fn gone_columns_of(table: &str) -> Vec<&'static str> { let Some(spec) = TABLE_SPECS.iter().find(|spec| spec.name == table) else { return Vec::new(); }; GONE_COLUMNS .iter() .copied() .filter(|gone| spec.columns.iter().any(|(name, _)| name == gone)) .collect() } /// The alias the fragments give the parent row, so a self-reference /// (`cotton_sessions.parent_session_id → cotton_sessions`) never reads the /// inner row's own column by mistake. const PARENT: &str = "_soft"; /// `column` must name its table — `t.event_id`, `cotton_meetings.event_id` — /// because the fragment is a correlated subquery over the parent, and an /// unqualified name would resolve to the PARENT's column of the same name /// whenever it has one (every self-reference does). A fragment is built from /// constants in the source, so this is a programming error, not an input. fn check_qualified(column: &str) { assert!( column.contains('.') && !column.starts_with('.') && !column.ends_with('.'), "a soft-ref fragment takes the column qualified by its table or alias, got {column:?}" ); } /// The column naming the database `column` points into, qualified as /// `column` is — `s.todo_id` gives `s.todo_database` — when the soft /// reference may cross databases. fn database_column_of(column: &str, parent: &str) -> Option { let (alias, name) = column.rsplit_once('.')?; SOFT_REF_DATABASES .iter() .find(|(child, soft, _)| *soft == name && parent_of(child, soft) == Some(parent)) .map(|(_, _, database)| format!("{alias}.{database}")) } /// `column` names a row of `parent` that is present — or, for a reference /// that may cross databases, a row in the database its pair names. /// /// The parent's gone columns come from its spec, so the fragment is the same /// rule for every table and a table that gains a `trashed_at` gains it here. pub fn soft_names(column: &str, parent: &str) -> String { check_qualified(column); let mut present = String::new(); for gone in gone_columns_of(parent) { present.push_str(&format!(" AND {PARENT}.{gone} IS NULL")); } let here = format!("EXISTS (SELECT 1 FROM {parent} {PARENT} WHERE {PARENT}.id = {column}{present})"); match database_column_of(column, parent) { Some(database) => format!("({column} IS NOT NULL AND ({database} IS NOT NULL OR {here}))"), None => format!("({column} IS NOT NULL AND {here})"), } } /// `column` names no present row of `parent`: it is null, or the row it names /// is not present. pub fn soft_absent(column: &str, parent: &str) -> String { format!("NOT {}", soft_names(column, parent)) } /// The value to show for `column`: its name while the row is present, else /// null — what a projection selects in the column's place. pub fn soft_value(column: &str, parent: &str) -> String { format!("CASE WHEN {} THEN {column} END", soft_names(column, parent)) } #[cfg(test)] #[path = "soft_refs_tests.rs"] mod tests;