Skip to main content

wasm_dbms_api/dbms/query/
aggregate.rs

1//! Types for aggregated queries
2
3use serde::{Deserialize, Serialize};
4
5use crate::prelude::Value;
6
7/// An aggregate function applied to a column in a query.
8///
9/// Each variant maps to a SQL aggregate (`COUNT`, `SUM`, `AVG`, `MIN`, `MAX`).
10/// All variants except [`AggregateFunction::Count`] take the name of the
11/// column to aggregate over.
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13#[cfg_attr(feature = "candid", derive(candid::CandidType))]
14pub enum AggregateFunction {
15    /// Count rows in the group.
16    ///
17    /// `None` is equivalent to `COUNT(*)` and counts every row.
18    /// `Some(column)` is equivalent to `COUNT(column)` and counts only rows
19    /// where `column` is non-null.
20    Count(Option<String>),
21    /// Sum the values of the given column (`SUM(column)`).
22    Sum(String),
23    /// Arithmetic mean of the given column (`AVG(column)`).
24    Avg(String),
25    /// Minimum value of the given column (`MIN(column)`).
26    Min(String),
27    /// Maximum value of the given column (`MAX(column)`).
28    Max(String),
29}
30
31/// Result of a single aggregate function applied to a group.
32///
33/// Each variant corresponds to a variant of [`AggregateFunction`]. `Count` is
34/// always a `u64`; the remaining variants wrap a [`Value`] whose concrete
35/// kind matches the aggregated column's data type.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37#[cfg_attr(feature = "candid", derive(candid::CandidType))]
38pub enum AggregatedValue {
39    /// Number of rows counted by [`AggregateFunction::Count`].
40    Count(u64),
41    /// Sum produced by [`AggregateFunction::Sum`].
42    Sum(Value),
43    /// Average produced by [`AggregateFunction::Avg`].
44    Avg(Value),
45    /// Minimum produced by [`AggregateFunction::Min`].
46    Min(Value),
47    /// Maximum produced by [`AggregateFunction::Max`].
48    Max(Value),
49}
50
51/// A single row of aggregated query results.
52///
53/// One `AggregatedRow` is produced per distinct grouping tuple. `values`
54/// contains one [`AggregatedValue`] per requested aggregate, in the same
55/// order as the [`AggregateFunction`] list passed to the query.
56#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
57#[cfg_attr(feature = "candid", derive(candid::CandidType))]
58pub struct AggregatedRow {
59    /// Values of the `GROUP BY` columns that identify this group, in the
60    /// order the columns were declared.
61    pub group_keys: Vec<Value>,
62    /// Aggregate results, one per [`AggregateFunction`] in the query.
63    pub values: Vec<AggregatedValue>,
64}