Skip to main content

vantage_table/table/impls/
rollup.rs

1//! Roll-up columns: an aggregate over the rows a has_many relation gives for
2//! each parent row (an invoice's total over its lines).
3
4use std::sync::Arc;
5
6use vantage_core::{Result, error};
7use vantage_expressions::{Expression, Expressive, SelectableDataSource, expr_any};
8use vantage_types::{EmptyEntity, Entity};
9use vantage_vista::ReferenceKind;
10
11use crate::{
12    source::SelectSeed,
13    table::{Table, base::ExpressionFn},
14    traits::table_source::TableSource,
15};
16
17/// The aggregate a roll-up column computes. Over no rows, `Count` and `Sum`
18/// give 0; `Min`, `Max` and `Avg` give null.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum RollupOp {
21    Count,
22    Sum,
23    Min,
24    Max,
25    Avg,
26}
27
28impl<T: TableSource + 'static, E: Entity<T::Value> + 'static> Table<T, E> {
29    /// The table roll-up column `name` aggregates: `relation`'s target,
30    /// built now. `column` is the target column it reads. Every backend's
31    /// [`TableSource::rollup_expression`] starts here, so the refusals are
32    /// the same on each.
33    pub fn rollup_target(
34        &self,
35        name: &str,
36        relation: &str,
37        column: Option<&str>,
38    ) -> Result<Table<T, EmptyEntity>> {
39        let target = self.get_ref_target_erased(relation)?;
40        // Over its own table the column would read itself, without end.
41        if target.table_name() == self.table_name() && column == Some(name) {
42            return Err(error!(
43                "a roll-up column can't aggregate itself",
44                column = name,
45                relation = relation,
46                table = self.table_name()
47            ));
48        }
49        // A window would aggregate one page of children, or, past the first
50        // page, skip the aggregate's only row.
51        if target.pagination().is_some() {
52            return Err(error!(
53                "a roll-up's relation target can't have pagination",
54                relation = relation,
55                table = self.table_name()
56            ));
57        }
58        Ok(target)
59    }
60}
61
62impl<T, E> Table<T, E>
63where
64    T: SelectableDataSource<T::Value, T::Condition> + TableSource,
65    T::Source: SelectSeed<T::Select, T::Value, T::Condition>,
66    T::Select: Expressive<T::Value>,
67    T::Value: From<String>,
68    T::Column<T::AnyType>: Expressive<T::Value>,
69    E: Entity<T::Value> + 'static,
70{
71    /// Add a read-only column `name` holding `op` over `column` of the rows
72    /// `relation` gives for each row, narrowed by `condition`. `column` is
73    /// required for every op but `Count`.
74    ///
75    /// The column is an expression column like any other
76    /// ([`Self::with_try_expression`]): the backend renders it
77    /// ([`TableSource::rollup_expression`], a correlated subquery by default)
78    /// each time a query that includes the column is built. The relation's
79    /// target is built then, not here, so adding a roll-up builds no table.
80    ///
81    /// Errors here: an unknown relation, one that isn't a has_many or is
82    /// joined by more than one key, an op without the column it needs.
83    ///
84    /// Errors when a query includes the column ([`Self::try_select`]), and
85    /// from [`Self::check_expressions`]: a target that fails to build or has
86    /// a window, an unknown or computed child column, a column that would
87    /// aggregate itself, a backend that refuses roll-ups.
88    pub fn with_rollup(
89        mut self,
90        name: &str,
91        relation: &str,
92        op: RollupOp,
93        column: Option<&str>,
94        condition: Option<T::Condition>,
95    ) -> Result<Self> {
96        if self.ref_cardinality(relation)? != ReferenceKind::HasMany {
97            return Err(error!(
98                "a roll-up needs a has_many relation",
99                relation = relation,
100                table = self.table_name()
101            ));
102        }
103        // The aggregate correlates one key; the others would be dropped.
104        if self.ref_keys(relation)?.len() > 1 {
105            return Err(error!(
106                "a roll-up's relation can't be joined by more than one key",
107                relation = relation,
108                table = self.table_name()
109            ));
110        }
111        if op != RollupOp::Count && column.is_none() {
112            return Err(error!("roll-up needs a column", op = op));
113        }
114        let rollup = name.to_string();
115        let relation = relation.to_string();
116        let column = column.map(str::to_string);
117        let expr_fn: ExpressionFn<T> = Arc::new(move |parent| {
118            parent.data_source().rollup_expression(
119                parent,
120                &rollup,
121                &relation,
122                op,
123                column.as_deref(),
124                condition.clone(),
125            )
126        });
127        self.expressions.insert(name.to_string(), expr_fn);
128        Ok(self)
129    }
130
131    /// `op` over `column` of this table's rows as a parenthesised subquery:
132    /// [`Self::get_count_query`] and its siblings, with the sum wrapped in
133    /// `COALESCE(…, 0)` so no rows read 0.
134    pub fn aggregate_query(
135        &self,
136        op: RollupOp,
137        column: Option<&str>,
138    ) -> Result<Expression<T::Value>> {
139        let column = || {
140            let name = column.ok_or_else(|| error!("roll-up needs a column", op = op))?;
141            // The aggregate reads the stored field, not the expression.
142            if self.is_calculated_column(name) {
143                return Err(error!(
144                    "a roll-up can't aggregate a computed column",
145                    column = name,
146                    table = self.table_name()
147                ));
148            }
149            self.columns().get(name).ok_or_else(|| {
150                error!(
151                    "roll-up column not found",
152                    column = name,
153                    table = self.table_name()
154                )
155            })
156        };
157        Ok(match op {
158            RollupOp::Count => self.get_count_query(),
159            RollupOp::Sum => expr_any!("COALESCE({}, 0)", (self.get_sum_query(column()?))),
160            RollupOp::Min => self.get_min_query(column()?),
161            RollupOp::Max => self.get_max_query(column()?),
162            RollupOp::Avg => self.get_avg_query(column()?),
163        })
164    }
165}