use std::hash::{Hash, Hasher};
use serde::{Deserialize, Serialize};
use crate::common;
use super::{AggregateKey, ColumnPair, Expression, Filter, FlussoType, join::hash_on};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Aggregate {
pub table: common::TableName,
pub op: AggregateOp,
pub key: AggregateKey,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value_type: Option<FlussoType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filters: Option<Vec<Filter>>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub distinct: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub via: Vec<ViaHop>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub on: Vec<ColumnPair>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViaHop {
pub table: common::TableName,
pub foreign_key: common::ColumnName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filters: Option<Vec<Filter>>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub on: Vec<ColumnPair>,
}
impl Hash for ViaHop {
fn hash<H: Hasher>(&self, state: &mut H) {
let Self {
table,
foreign_key,
filters,
on,
} = self;
table.hash(state);
foreign_key.hash(state);
filters.hash(state);
hash_on("via_on", on, state);
}
}
impl Hash for Aggregate {
fn hash<H: Hasher>(&self, state: &mut H) {
let Self {
table,
op,
key,
value_type,
filters,
distinct,
via,
on,
} = self;
table.hash(state);
op.hash(state);
key.hash(state);
value_type.hash(state);
filters.hash(state);
if *distinct {
distinct.hash(state);
}
if !via.is_empty() {
"via".hash(state);
via.hash(state);
}
hash_on("on", on, state);
}
}
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AggregateOp {
Count,
Sum(Expression),
Avg(Expression),
Min(Expression),
Max(Expression),
Ids {
element_type: FlussoType,
},
Exists,
}
impl AggregateOp {
pub fn input(&self) -> Option<&Expression> {
match self {
Self::Sum(input) | Self::Avg(input) | Self::Min(input) | Self::Max(input) => {
Some(input)
}
Self::Count | Self::Ids { .. } | Self::Exists => None,
}
}
}