use sea_query::{Alias, Expr, Func, SimpleExpr};
#[derive(Debug, Clone)]
pub enum Aggregate {
Count(Option<String>),
Sum(String),
Avg(String),
Max(String),
Min(String),
}
impl Aggregate {
pub fn count() -> Self {
Aggregate::Count(None)
}
pub fn count_col(name: impl Into<String>) -> Self {
Aggregate::Count(Some(name.into()))
}
pub fn sum(name: impl Into<String>) -> Self {
Aggregate::Sum(name.into())
}
pub fn avg(name: impl Into<String>) -> Self {
Aggregate::Avg(name.into())
}
pub fn max(name: impl Into<String>) -> Self {
Aggregate::Max(name.into())
}
pub fn min(name: impl Into<String>) -> Self {
Aggregate::Min(name.into())
}
pub fn source_column(&self) -> Option<&str> {
match self {
Aggregate::Count(c) => c.as_deref(),
Aggregate::Sum(c) | Aggregate::Avg(c) | Aggregate::Max(c) | Aggregate::Min(c) => {
Some(c.as_str())
}
}
}
pub fn to_simple_expr(&self) -> SimpleExpr {
match self {
Aggregate::Count(None) => Func::count(Expr::col(sea_query::Asterisk)).into(),
Aggregate::Count(Some(col)) => Func::count(Expr::col(Alias::new(col.as_str()))).into(),
Aggregate::Sum(col) => Func::sum(Expr::col(Alias::new(col.as_str()))).into(),
Aggregate::Avg(col) => Func::avg(Expr::col(Alias::new(col.as_str()))).into(),
Aggregate::Max(col) => Func::max(Expr::col(Alias::new(col.as_str()))).into(),
Aggregate::Min(col) => Func::min(Expr::col(Alias::new(col.as_str()))).into(),
}
}
pub fn kind(&self) -> AggregateKind {
match self {
Aggregate::Count(_) => AggregateKind::Count,
Aggregate::Sum(_) => AggregateKind::Sum,
Aggregate::Avg(_) => AggregateKind::Avg,
Aggregate::Max(_) => AggregateKind::Max,
Aggregate::Min(_) => AggregateKind::Min,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggregateKind {
Count,
Sum,
Avg,
Max,
Min,
}