//! Computed columns: a column whose value the core works out from other
//! columns and records instead of anyone writing it.
//!
//! A column carries `computed`, exactly one of six closed shapes:
//!
//! - `{"lookup": {"through": , "column": }}` — a
//! value of the record a link column points at;
//! - `{"rollup": {"table": t, "link": c, "op": count|sum|min|max|first|latest|average,
//! "column": c, "where": {column, values}, "by": c}}` — over the records of
//! another table whose link points here;
//! - `{"formula": {"op": sum|difference|sign|join, "of": […],
//! "flip_when": {column, values}, "separator": "…"}}` — over columns of the
//! same record;
//! - `{"running": {"column": c, "opening": number|{rollup}}}` — a cumulative
//! sum including this row, in the table's sort order;
//! - `{"previous": {"column": c}}` — the preceding row's value in that order;
//! - `{"activity": {"handles": t, "link": c, "op": latest|count,
//! "within_days": n}}` — the messages, calls and mail this database holds
//! with any of the record's handles (the rows of `t` whose `link` points
//! here): the newest one's time, or how many there were in the last `n`
//! days.
//!
//! Nothing else: no expressions, no strings of code. A computed column is
//! read-only, is stored in no synced column, and may read another computed
//! column — the core orders them — but never, by any path, itself.
//!
//! This file is the SHAPE and its validation. One table can be checked alone
//! ([`TableDefinition::validate`] calls `validate_computed`); what a lookup
//! or a rollup names in ANOTHER table needs the tables side by side
//! ([`validate_across`]).
use std::collections::BTreeSet;
use serde::{Deserialize, Serialize};
use super::{
among_choices, is_valid_id, Column, ColumnType, DefinitionError, SummaryOp, TableDefinition,
ValueMatch,
};
/// What a computed column is worked out from — exactly one shape.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Computed {
Lookup(Lookup),
Rollup(Rollup),
Formula(Formula),
Running(Running),
Previous(Previous),
Activity(Activity),
}
/// What an activity column says of the events with a record's handles.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ActivityOp {
/// When the newest one was: a date.
Latest,
/// How many there were: a number.
Count,
}
/// The messages, calls and mail with any handle of the record — the same
/// evidence a handle's channels are read from (`records::page_channels`).
/// The engine works it out when a fold brings an event with one of the
/// handles, never on a read.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Activity {
/// The table of handles: a `kind` choice and a `normalised` text.
pub handles: String,
/// A link column of `handles` pointing at this column's table.
pub link: String,
pub op: ActivityOp,
/// Only the events of the last this many days, counted from the time
/// the engine works it out.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub within_days: Option,
}
/// The columns of an activity's handles table it reads a handle by.
pub const HANDLE_KIND: &str = "kind";
pub const HANDLE_VALUE: &str = "normalised";
/// Cumulative values in the table's explicit sort order, including this row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Running {
pub column: String,
/// Restart the ordered state for each tuple of these columns' values.
/// Amounts also partition by their resolved currency.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub partition: Vec,
pub opening: RunningOpening,
/// The date or number column the sum walks by, oldest first (ruling 03:55
/// IST 17 Oct 2026, item 2): So far lists newest first and still says each
/// row's balance after it. Rows alike walk as the list's sort meets them,
/// oldest of them first. Absent: the table's sort, as it reads.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order: Option,
/// The words the list says its opening in, above its first row: the
/// opening as an amount, then these ("₹1,20,000 held today", Ahead's
/// opening, ruling 16:43 IST 17 Oct 2026). The core says the line; a
/// list with a group has no one first row, and takes none.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub opening_label: Option,
}
/// An opening's exact JSON number, separate from the floating-point timing
/// numbers used elsewhere in definitions and by the native decoder.
pub type RunningNumber = serde_json::Number;
/// One starting value for the ordered table, numeric or gathered from another table.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RunningOpening {
Number(RunningNumber),
Rollup(RunningRollup),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunningRollup {
pub rollup: RunningAggregate,
}
/// A table-wide opening. Ordinary rollups remain linked to a target row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunningAggregate {
pub table: String,
pub op: RollupOp,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub column: Option,
#[serde(rename = "where", default, skip_serializing_if = "Option::is_none")]
pub where_: Option,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub by: Option,
}
/// Shared aggregation inputs; only ordinary rollups gather by a backlink.
#[derive(Debug, Clone, Copy)]
pub struct RollupRead<'a> {
pub table: &'a str,
pub link: Option<&'a str>,
pub op: RollupOp,
pub column: Option<&'a str>,
pub where_: Option<&'a ValueMatch>,
pub by: Option<&'a str>,
}
impl RunningAggregate {
pub fn read(&self) -> RollupRead<'_> {
RollupRead { table: &self.table, link: None, op: self.op, column: self.column.as_deref(), where_: self.where_.as_ref(), by: self.by.as_deref() }
}
}
/// The preceding live row's column, or nothing on the first row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Previous {
pub column: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub partition: Vec,
}
/// A value of the record `through` points at.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Lookup {
/// A link column of this table holding one record.
pub through: String,
/// The column read off that record; its type is this column's type.
pub column: String,
}
/// What a rollup does with the records it gathers (the tile summary's ops,
/// plus first, latest and average) and what a formula does with its columns:
/// one arithmetic, in `cotton-rules`.
pub use cotton_rules::computed::{FormulaOp, RollupOp};
/// The tile summary's op a rollup's is, so the two share one implementation;
/// none for `first`, `latest` and `average`, which a tile has no use for.
pub fn rollup_summary(op: RollupOp) -> Option {
match op {
RollupOp::Count => Some(SummaryOp::Count),
RollupOp::Sum => Some(SummaryOp::Sum),
RollupOp::Min => Some(SummaryOp::Min),
RollupOp::Max => Some(SummaryOp::Max),
RollupOp::First | RollupOp::Latest | RollupOp::Average => None,
}
}
/// Whether a rollup picks one record by order (first, latest).
fn ordered(op: RollupOp) -> bool {
matches!(op, RollupOp::First | RollupOp::Latest)
}
/// Over the records of `table` whose `link` points at this record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rollup {
pub table: String,
/// A link column of `table` pointing at this column's table.
pub link: String,
pub op: RollupOp,
/// The column of `table` the op reads; absent for `count`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub column: Option,
/// Only the records of `table` whose column holds one of the values.
#[serde(rename = "where", default, skip_serializing_if = "Option::is_none")]
pub where_: Option,
/// What `first` and `latest` order by: a date, time or number column of
/// `table`. Absent: that table's own `date` column.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub by: Option,
}
impl Rollup {
pub fn read(&self) -> RollupRead<'_> {
RollupRead { table: &self.table, link: Some(&self.link), op: self.op, column: self.column.as_deref(), where_: self.where_.as_ref(), by: self.by.as_deref() }
}
}
/// Over columns of the same record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Formula {
pub op: FormulaOp,
pub of: Vec,
/// `signed` only: the records whose amount reads the other way up.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub flip_when: Option,
/// `join` only: what stands between the words. Absent: one space.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub separator: Option,
}
const NUMERIC: (&[ColumnType], &str) = (&[ColumnType::Number, ColumnType::Amount], "a_number_or_an_amount");
const SMALLEST: (&[ColumnType], &str) = (
&[ColumnType::Date, ColumnType::Number, ColumnType::Amount],
"a_date_a_number_or_an_amount",
);
const WORDS: (&[ColumnType], &str) = (
&[ColumnType::Text, ColumnType::Longtext, ColumnType::Choice, ColumnType::Url],
"a_text_a_long_text_a_choice",
);
const ORDER: (&[ColumnType], &str) = (
&[ColumnType::Date, ColumnType::Time, ColumnType::Number],
"a_date_a_time_or_a_number",
);
/// One column of one table, as the cycle walk names it.
type Node<'a> = (&'a str, &'a str);
/// An amount reads its sibling currency or the currency of its linked account.
/// The account's currency is a dependency even when no transaction changed.
fn currency_reads<'a>(table: &'a TableDefinition, key: &str) -> Vec> {
let Some(currency) = table.column(key).and_then(|column| column.currency.as_deref()) else { return Vec::new() };
let currency = if currency == "account" { "account_id" } else { currency };
let Some(source) = table.column(currency) else { return Vec::new() };
let mut reads = vec![(table.id.as_str(), source.key.as_str())];
if source.column_type == ColumnType::Link && source.link_to.as_deref() == Some("money_account") {
reads.push(("money_account", "currency"));
}
reads
}
impl Computed {
/// Every column this one is worked out from, in `table` or another.
/// What names a table `tables` does not hold is left out: it is refused
/// where the tables are checked side by side, not here.
pub fn reads<'a>(
&'a self,
table: &'a TableDefinition,
tables: &[&'a TableDefinition],
) -> Vec> {
let mut reads: Vec> = Vec::new();
match self {
Computed::Lookup(lookup) => {
reads.push((&table.id, &lookup.through));
let target = table
.column(&lookup.through)
.and_then(|through| through.link_to.as_deref());
if let Some(target) = target {
reads.push((target, &lookup.column));
}
}
Computed::Rollup(rollup) => {
let other = rollup.table.as_str();
reads.push((other, &rollup.link));
if let Some(column) = &rollup.column {
reads.push((other, column));
}
if let Some(filter) = &rollup.where_ {
reads.push((other, &filter.column));
}
if ordered(rollup.op) {
let date = tables
.iter()
.find(|table| table.id == other)
.and_then(|table| table.date.as_deref());
if let Some(by) = rollup.by.as_deref().or(date) {
reads.push((other, by));
}
}
}
Computed::Running(running) => {
reads.push((&table.id, &running.column));
reads.extend(running.partition.iter().map(|key| (table.id.as_str(), key.as_str())));
reads.extend(currency_reads(table, &running.column));
if let Some(order) = &running.order {
reads.push((&table.id, order));
}
if let RunningOpening::Rollup(opening) = &running.opening {
let rollup = &opening.rollup;
// Even count without a column depends on the source row set.
reads.push((&rollup.table, "id"));
if let Some(column) = &rollup.column {
reads.push((&rollup.table, column));
if let Some(source) = tables.iter().find(|table| table.id == rollup.table) {
reads.extend(currency_reads(source, column));
}
}
if let Some(filter) = &rollup.where_ { reads.push((&rollup.table, &filter.column)); }
if ordered(rollup.op) {
if let Some(by) = rollup.by.as_deref().or_else(|| tables.iter().find(|t| t.id == rollup.table).and_then(|t| t.date.as_deref())) {
reads.push((&rollup.table, by));
}
}
}
}
Computed::Previous(previous) => {
reads.push((&table.id, &previous.column));
reads.extend(previous.partition.iter().map(|key| (table.id.as_str(), key.as_str())));
reads.extend(currency_reads(table, &previous.column));
},
Computed::Activity(activity) => {
reads.push((&activity.handles, &activity.link));
reads.push((&activity.handles, HANDLE_KIND));
reads.push((&activity.handles, HANDLE_VALUE));
}
Computed::Formula(formula) => {
reads.extend(formula.of.iter().map(|of| (table.id.as_str(), of.as_str())));
if let Some(flip) = &formula.flip_when {
reads.push((&table.id, &flip.column));
}
}
}
if self.is_ordered() {
if let Some(sort) = &table.sort {
reads.push((&table.id, &sort.column));
if let Some(tie) = &sort.tie { reads.push((&table.id, tie)); }
}
}
reads
}
pub fn is_ordered(&self) -> bool {
matches!(self, Self::Running(_) | Self::Previous(_))
}
/// The rollup a shape reads, including a running opening.
pub fn rollup(&self) -> Option> {
match self {
Self::Rollup(rollup) => Some(rollup.read()),
Self::Running(Running { opening: RunningOpening::Rollup(opening), .. }) => Some(opening.rollup.read()),
_ => None,
}
}
}
/// The two columns hold the same kind of value: one type, and for a link the
/// same table.
fn same_kind(this: &Column, that: &Column) -> bool {
this.column_type == that.column_type
&& (this.column_type != ColumnType::Link || this.link_to == that.link_to)
}
/// A `where` or `flip_when` over `table`: a declared column, at least one
/// value, and for a choice column only its choices.
fn check_match(
table: &TableDefinition,
slot: &str,
filter: &ValueMatch,
) -> Result<(), DefinitionError> {
let column = table.named(&format!("{slot}.column"), &filter.column, None)?;
if filter.values.is_empty() {
return Err(DefinitionError::EmptyAt(format!("{slot}.values")));
}
if column.column_type == ColumnType::Choice && column.choices.is_some() {
among_choices(&format!("{slot}.values"), column, filter.values.iter())?;
}
Ok(())
}
/// No computed column reads itself, directly or through other computed
/// columns, in the tables given.
fn refuse_cycles(tables: &[&TableDefinition]) -> Result<(), DefinitionError> {
fn visit<'a>(
node: Node<'a>,
tables: &[&'a TableDefinition],
path: &mut Vec>,
clear: &mut BTreeSet>,
) -> Result<(), DefinitionError> {
if clear.contains(&node) {
return Ok(());
}
if path.contains(&node) {
return Err(DefinitionError::ComputedCycle {
table: node.0.into(),
column: node.1.into(),
});
}
let Some(table) = tables.iter().copied().find(|table| table.id == node.0) else {
return Ok(());
};
let Some(computed) = table.column(node.1).and_then(|c| c.computed.as_ref()) else {
return Ok(());
};
path.push(node);
for read in computed.reads(table, tables) {
visit(read, tables, path, clear)?;
}
path.pop();
clear.insert(node);
Ok(())
}
let mut clear = BTreeSet::new();
for table in tables.iter().copied() {
for column in table.columns.iter().filter(|c| c.computed.is_some()) {
visit((&table.id, &column.key), tables, &mut Vec::new(), &mut clear)?;
}
}
Ok(())
}
/// Every computed column of `tables` as `(table, column)`, each after every
/// computed column it reads — the order to work them out in. The tables are
/// taken as already checked side by side ([`validate_across`]): a cycle is
/// simply not followed.
pub fn derive_order(tables: &[&TableDefinition]) -> Vec<(String, String)> {
fn visit<'a>(
node: Node<'a>,
tables: &[&'a TableDefinition],
path: &mut Vec>,
seen: &mut BTreeSet>,
order: &mut Vec<(String, String)>,
) {
if seen.contains(&node) || path.contains(&node) {
return;
}
let Some(table) = tables.iter().copied().find(|table| table.id == node.0) else {
return;
};
let Some(computed) = table.column(node.1).and_then(|c| c.computed.as_ref()) else {
return;
};
path.push(node);
for read in computed.reads(table, tables) {
visit(read, tables, path, seen, order);
}
path.pop();
seen.insert(node);
order.push((node.0.to_string(), node.1.to_string()));
}
let mut seen = BTreeSet::new();
let mut order = Vec::new();
for table in tables.iter().copied() {
for column in table.columns.iter().filter(|c| c.computed.is_some()) {
visit((&table.id, &column.key), tables, &mut Vec::new(), &mut seen, &mut order);
}
}
order
}
/// Validate aggregation keys and the output type before looking up its source.
fn validate_rollup(column: &Column, rollup: RollupRead<'_>, base: &str) -> Result<(), DefinitionError> {
let slot = |field: &str| format!("{base}{field}");
let own = |field: &str, (allowed, wanted): (&[ColumnType], &'static str)| {
if allowed.contains(&column.column_type) { Ok(()) } else {
let named = column.key.as_str();
Err(DefinitionError::WrongColumnType { slot: slot(field), column: named.to_string(), found: column.column_type, wanted })
}
};
let column_key = |name: &str| {
if is_valid_id(name) { Ok(()) } else { Err(DefinitionError::BadColumnKey(name.into())) }
};
if !is_valid_id(rollup.table) {
return Err(DefinitionError::BadId(rollup.table.into()));
}
if let Some(link) = rollup.link { column_key(link)?; }
match (rollup.op, &rollup.column) {
(RollupOp::Count, Some(_)) => {
return Err(DefinitionError::Conflict {
slot: slot(".column"),
other: "op: count",
})
}
(RollupOp::Count, None) => {
own(".op", (&[ColumnType::Number], "a number"))?
}
(_, None) => {
return Err(DefinitionError::Requires {
slot: slot(".column"),
needs: "the_column_the_op_reads",
})
}
(op, Some(read)) => {
column_key(read)?;
match op {
RollupOp::Sum => own(".op", NUMERIC)?,
RollupOp::Min | RollupOp::Max => own(".op", SMALLEST)?,
RollupOp::Average => own(".op", (&[ColumnType::Number], "a number"))?,
_ => {}
}
}
}
if let Some(filter) = &rollup.where_ {
column_key(&filter.column)?;
if filter.values.is_empty() {
return Err(DefinitionError::EmptyAt(slot(".where.values")));
}
}
if let Some(by) = &rollup.by {
if !ordered(rollup.op) {
return Err(DefinitionError::Requires {
slot: slot(".by"),
needs: "op_first_or_latest",
});
}
column_key(by)?;
}
Ok(())
}
impl TableDefinition {
/// Whether any column of the table is computed.
pub fn has_computed(&self) -> bool {
self.columns.iter().any(|column| column.computed.is_some())
}
/// What one table can say about its own computed column: the keys it
/// cannot sit beside, the shape's own rules, and every column it names in
/// THIS table. What it names in another table is [`validate_across`]'s.
pub(super) fn validate_computed(&self, column: &Column) -> Result<(), DefinitionError> {
let Some(computed) = &column.computed else {
return Ok(());
};
let key = column.key.as_str();
let slot = |field: &str| format!("columns.{key}.computed{field}");
for (held, other) in [
(column.readonly == Some(false), "readonly_false"),
(column.required == Some(true), "required_true"),
(column.default.is_some(), "default"),
(column.secret.is_some(), "secret"),
(column.multiple == Some(true), "multiple_true"),
(column.link_by.is_some(), "link_by"),
(column.choices_from.is_some(), "choices_from"),
] {
if held {
return Err(DefinitionError::Conflict {
slot: slot(""),
other,
});
}
}
let own = |field: &str, (allowed, wanted): (&[ColumnType], &'static str)| {
if allowed.contains(&column.column_type) {
Ok(())
} else {
Err(DefinitionError::WrongColumnType {
slot: slot(field),
column: key.into(),
found: column.column_type,
wanted,
})
}
};
let column_key = |name: &str| {
if is_valid_id(name) {
Ok(())
} else {
Err(DefinitionError::BadColumnKey(name.into()))
}
};
if computed.is_ordered() {
if self.sort.is_none() {
return Err(DefinitionError::Requires { slot: slot(""), needs: "an_explicit_table_sort" });
}
if self.order.is_some() || self.day_grouping.is_some() {
return Err(DefinitionError::Requires { slot: slot(""), needs: "a_table_sort_without_manual_order_or" });
}
}
match computed {
Computed::Running(running) => {
for key in &running.partition { self.named(&slot(".running.partition"), key, None)?; }
own(".running", NUMERIC)?;
let source = self.named(&slot(".running.column"), &running.column, Some(NUMERIC))?;
if !same_kind(column, source) {
return Err(DefinitionError::Requires { slot: slot(".running.column"), needs: "a_column_of_this_column_s_own" });
}
if let Some(order) = &running.order {
self.named(&slot(".running.order"), order, Some(SMALLEST))?;
}
if let Some(label) = &running.opening_label {
if label.trim().is_empty() {
return Err(DefinitionError::Requires { slot: slot(".running.opening_label"), needs: "the_words_the_opening_is_said_in" });
}
if self.group.is_some() {
return Err(DefinitionError::Requires {
slot: slot(".running.opening_label"),
needs: "a_list_without_a_group_whose_first",
});
}
}
match &running.opening {
RunningOpening::Number(number) if column.column_type == ColumnType::Amount && number.as_i64().is_none() => {
return Err(DefinitionError::Requires {
slot: slot(".running.opening"),
needs: "a_signed_whole_amount_in_minor_units",
});
}
RunningOpening::Rollup(opening) => validate_rollup(column, opening.rollup.read(), &slot(".running.opening.rollup"))?,
_ => {}
}
}
Computed::Previous(previous) => {
for key in &previous.partition { self.named(&slot(".previous.partition"), key, None)?; }
let source = self.named(&slot(".previous.column"), &previous.column, None)?;
if !same_kind(column, source) || source.multiple == Some(true) {
return Err(DefinitionError::Requires { slot: slot(".previous.column"), needs: "a_single_value_of_this_column_s" });
}
}
Computed::Lookup(lookup) => {
let through = self.named(
&slot(".lookup.through"),
&lookup.through,
Some((&[ColumnType::Link], "a link")),
)?;
if through.link_to.is_none() || through.multiple == Some(true) {
return Err(DefinitionError::Requires {
slot: slot(".lookup.through"),
needs: "a_link_to_one_record_of_one",
});
}
column_key(&lookup.column)?;
}
Computed::Rollup(rollup) => validate_rollup(column, rollup.read(), &slot(".rollup"))?,
Computed::Activity(activity) => {
if !is_valid_id(&activity.handles) {
return Err(DefinitionError::BadId(activity.handles.clone()));
}
column_key(&activity.link)?;
match activity.op {
ActivityOp::Latest => own(".activity.op", (&[ColumnType::Date], "a date"))?,
ActivityOp::Count => own(".activity.op", (&[ColumnType::Number], "a number"))?,
}
if activity.within_days == Some(0) {
return Err(DefinitionError::Requires { slot: slot(".activity.within_days"), needs: "one_day_or_more" });
}
}
Computed::Formula(formula) => {
let (least, most, needs) = match formula.op {
FormulaOp::Sum => (2, usize::MAX, "two_or_more_columns"),
FormulaOp::Difference => (2, 2, "exactly_two_columns"),
FormulaOp::Sign | FormulaOp::Signed => (1, 1, "exactly_one_column"),
FormulaOp::Join => (2, usize::MAX, "two_or_more_columns"),
};
if formula.of.len() < least || formula.of.len() > most {
return Err(DefinitionError::Requires {
slot: slot(".formula.of"),
needs,
});
}
let read = match formula.op {
FormulaOp::Join => {
own(".formula.op", (&[ColumnType::Text], "a text"))?;
WORDS
}
// -1, 0 or 1 is a number whatever it is the sign of.
FormulaOp::Sign => {
own(".formula.op", (&[ColumnType::Number], "a number"))?;
NUMERIC
}
_ => {
own(".formula.op", NUMERIC)?;
match column.column_type {
ColumnType::Amount => (&[ColumnType::Amount][..], "an amount"),
_ => (&[ColumnType::Number][..], "a number"),
}
}
};
for of in &formula.of {
self.named(&slot(".formula.of"), of, Some(read))?;
}
match (&formula.flip_when, formula.op) {
(Some(flip), FormulaOp::Signed) => {
check_match(self, &slot(".formula.flip_when"), flip)?
}
(None, FormulaOp::Signed) => {
return Err(DefinitionError::Requires {
slot: slot(".formula.flip_when"),
needs: "the_column_and_values_that_turn_the",
})
}
(Some(_), _) => {
return Err(DefinitionError::Requires {
slot: slot(".formula.flip_when"),
needs: "op: signed",
})
}
(None, _) => {}
}
if let Some(separator) = &formula.separator {
if formula.op != FormulaOp::Join {
return Err(DefinitionError::Requires {
slot: slot(".formula.separator"),
needs: "op: join",
});
}
if separator.is_empty() {
return Err(DefinitionError::EmptyAt(slot(".formula.separator")));
}
}
}
}
refuse_cycles(&[self])
}
}
/// What a computed column names in ANOTHER table, checked with the tables
/// side by side: a lookup's column exists where its link points and holds
/// this column's kind of value; a rollup's table exists, its link points
/// back here, its column suits its op, its `where` reads that table and a
/// `first` or `latest` has something to order by; and no column reads itself
/// through any path. Every table is taken as already valid on its own.
pub fn validate_across(tables: &[&TableDefinition]) -> Result<(), DefinitionError> {
for table in tables.iter().copied() {
for column in table.columns.iter().filter(|column| column.computed.is_some()) {
check_across(tables, table, column)?;
}
}
refuse_cycles(tables)
}
/// What [`validate_beside`] does with a rollup whose table is not among the
/// tables it was given.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AbsentTable {
/// Refused, naming the table: installing a tool whose rollup reads a
/// table this database does not have.
Refuse,
/// Left for the install to check: reading a package on its own, whose
/// rollup may read a table another tool brings (Customers counting the
/// Orders tool's orders).
Defer,
}
/// The computed columns of `own` (a package's tables) checked against `own`
/// beside `beside` (the built-ins, and at install the database's installed
/// tables) — and every computed column of `beside` that reads one of `own`,
/// since an upgrade can take away what an installed rollup counts. A table of
/// `own` stands in for one of `beside` with its id. No column may read itself
/// through any path, across all of them.
pub fn validate_beside(
own: &[&TableDefinition],
beside: &[&TableDefinition],
absent: AbsentTable,
) -> Result<(), DefinitionError> {
let owned = |id: &str| own.iter().any(|table| table.id == id);
let all: Vec<&TableDefinition> = own
.iter()
.copied()
.chain(beside.iter().copied().filter(|table| !owned(&table.id)))
.collect();
let present = |id: &str| all.iter().any(|table| table.id == id);
for table in all.iter().copied() {
for column in &table.columns {
let Some(computed) = &column.computed else {
continue;
};
let reads: Option<&str> = match computed {
Computed::Lookup(lookup) => table
.column(&lookup.through)
.and_then(|through| through.link_to.as_deref()),
Computed::Rollup(rollup) => Some(rollup.table.as_str()),
Computed::Activity(activity) => Some(activity.handles.as_str()),
Computed::Running(_) => computed.rollup().map(|rollup| rollup.table),
Computed::Formula(_) | Computed::Previous(_) => None,
};
if !owned(&table.id) && !reads.is_some_and(owned) {
continue;
}
if let (Some(rollup), AbsentTable::Defer) = (computed.rollup(), absent) {
if !present(rollup.table) {
continue;
}
}
check_across(&all, table, column)?;
}
}
refuse_cycles(&all)
}
/// `(table, column)` of every computed column of `tables` that does not stand
/// beside them — a rollup whose table is gone, a lookup whose column is —
/// for a reader that leaves those columns empty and works out the rest.
pub fn dangling(tables: &[&TableDefinition]) -> Vec<(String, String)> {
tables
.iter()
.copied()
.flat_map(|table| {
table
.columns
.iter()
.filter(|column| column.computed.is_some())
.filter(|column| check_across(tables, table, column).is_err())
.map(|column| (table.id.clone(), column.key.clone()))
})
.collect()
}
/// One computed column of `table`, checked against what it names in the
/// other `tables` (see [`validate_across`]).
fn check_across(
tables: &[&TableDefinition],
table: &TableDefinition,
column: &Column,
) -> Result<(), DefinitionError> {
let Some(computed) = &column.computed else {
return Ok(());
};
let find = |slot: &str, id: &str| {
tables
.iter()
.copied()
.find(|table| table.id == id)
.ok_or_else(|| DefinitionError::UnknownTable {
slot: slot.into(),
table: id.into(),
})
};
let slot = |field: &str| format!("{}.columns.{}.computed{field}", table.id, column.key);
let own_kind = |slot: String, read: &Column| {
if same_kind(column, read) {
Ok(())
} else {
Err(DefinitionError::Requires {
slot,
needs: "a_column_of_this_column_s_own",
})
}
};
match computed {
Computed::Lookup(lookup) => {
let through = table.named(&slot(".lookup.through"), &lookup.through, None)?;
let target = find(
&slot(".lookup.through"),
through.link_to.as_deref().unwrap_or_default(),
)?;
let read = target.named(&slot(".lookup.column"), &lookup.column, None)?;
own_kind(slot(".lookup.column"), read)?;
}
Computed::Rollup(rollup) => check_rollup_across(tables, table, column, rollup.read(), &slot(".rollup"))?,
Computed::Running(running) => {
if let RunningOpening::Rollup(opening) = &running.opening {
check_rollup_across(tables, table, column, opening.rollup.read(), &slot(".running.opening.rollup"))?;
}
}
Computed::Activity(activity) => {
let handles = find(&slot(".activity.handles"), &activity.handles)?;
let link = handles.named(&slot(".activity.link"), &activity.link, Some((&[ColumnType::Link], "a link")))?;
if link.link_to.as_deref() != Some(table.id.as_str()) || link.multiple == Some(true) {
return Err(DefinitionError::Requires {
slot: slot(".activity.link"),
needs: "a_link_to_one_record_of_this",
});
}
handles.named(&slot(".activity.handles"), HANDLE_KIND, None)?;
handles.named(&slot(".activity.handles"), HANDLE_VALUE, None)?;
}
Computed::Formula(_) | Computed::Previous(_) => {}
}
Ok(())
}
fn check_rollup_across(tables: &[&TableDefinition], table: &TableDefinition, column: &Column, rollup: RollupRead<'_>, base: &str) -> Result<(), DefinitionError> {
let slot = |field: &str| format!("{base}{field}");
let find = |at: &str, id: &str| tables.iter().copied().find(|table| table.id == id)
.ok_or_else(|| DefinitionError::UnknownTable { slot: at.into(), table: id.into() });
let own_kind = |at: String, read: &Column| {
if same_kind(column, read) { Ok(()) } else { Err(DefinitionError::Requires { slot: at, needs: "a_column_of_this_column_s_own" }) }
};
let other = find(&slot(".table"), rollup.table)?;
if let Some(link_key) = rollup.link {
let link = other.named(
&slot(".link"),
link_key,
Some((&[ColumnType::Link], "a link")),
)?;
if link.link_to.as_deref() != Some(table.id.as_str()) || link.multiple == Some(true) {
return Err(DefinitionError::Requires {
slot: slot(".link"),
needs: "a_link_to_one_record_of_this",
});
}
}
if let Some(read) = &rollup.column {
let read = other.named(&slot(".column"), read, None)?;
own_kind(slot(".column"), read)?;
}
if let Some(filter) = &rollup.where_ {
check_match(other, &slot(".where"), filter)?;
}
if ordered(rollup.op) {
let Some(by) = rollup.by.or(other.date.as_deref()) else {
return Err(DefinitionError::Requires {
slot: slot(".by"),
needs: "a_column_to_order_by_the_other",
});
};
other.named(&slot(".by"), by, Some(ORDER))?;
}
Ok(())
}
#[cfg(test)]
#[path = "computed_tests.rs"]
mod tests;