use std::borrow::Cow;
use std::collections::{BTreeMap, HashSet};
use relate_core::{Result, Value};
use relate_ir::{AggregateKind, Expr};
use super::{fold_aggregate, FoldInput};
use crate::eval::{eval, expr_vars, is_agg_expr};
use crate::overlay::ExecGraph;
use crate::row::Row;
#[derive(Clone, Copy, Debug)]
struct HorizontalAgg(AggregateKind);
impl HorizontalAgg {
fn of(kind: AggregateKind) -> Option<Self> {
match kind {
AggregateKind::Count
| AggregateKind::Sum
| AggregateKind::Avg
| AggregateKind::Min
| AggregateKind::Max
| AggregateKind::Collect => Some(Self(kind)),
AggregateKind::StDev
| AggregateKind::StDevP
| AggregateKind::PercentileCont
| AggregateKind::PercentileDisc => None,
}
}
}
struct HorizontalCall<'a> {
kind: HorizontalAgg,
name: String,
arg: &'a Expr,
}
fn horizontal_call(expr: &Expr) -> Option<HorizontalCall<'_>> {
let Expr::Function {
name,
distinct,
args,
} = expr
else {
return None;
};
if *distinct || args.len() != 1 {
return None;
}
let kind = HorizontalAgg::of(name.with_str(relate_ir::classify_aggregate)?)?;
Some(HorizontalCall {
kind,
name: name.to_string(),
arg: &args[0],
})
}
pub(crate) fn rewrite_horizontal_aggregates<'e>(
graph: &ExecGraph<'_>,
row: &Row,
expr: &'e Expr,
params: &BTreeMap<String, Value>,
) -> Result<Cow<'e, Expr>> {
if !is_agg_expr(expr) {
return Ok(Cow::Borrowed(expr));
}
match horizontal_call(expr) {
Some(call) => {
let mut vars = HashSet::new();
expr_vars(call.arg, &mut vars);
let list_vars: Vec<_> = vars
.into_iter()
.filter_map(|name| match row.get(&name) {
Some(Value::List(values)) => Some((name, values)),
_ => None,
})
.collect();
let Some(len) = list_vars.iter().map(|(_, values)| values.len()).max() else {
return Ok(Cow::Borrowed(expr));
};
let mut values = Vec::new();
for index in 0..len {
let mut iteration = row.clone();
for (name, items) in &list_vars {
iteration.insert(
name.clone(),
items.get(index).cloned().unwrap_or(Value::Null),
);
}
values.push(eval(graph, &iteration, call.arg, params)?);
}
let value = horizontal_aggregate(call.kind, &call.name, values)?;
Ok(Cow::Owned(Expr::RuntimeValue(value)))
}
None => {
let mut rewrites: Vec<Cow<'e, Expr>> = Vec::new();
expr.try_each_child::<relate_core::Error>(&mut |child| {
rewrites.push(rewrite_horizontal_aggregates(graph, row, child, params)?);
Ok(())
})?;
if rewrites.iter().all(|r| matches!(r, Cow::Borrowed(_))) {
return Ok(Cow::Borrowed(expr));
}
let mut rewrites = rewrites.into_iter();
expr.map_children(&mut |_| {
Ok(rewrites
.next()
.expect("map_children rebuilds exactly the children each_child visited")
.into_owned())
})
.map(Cow::Owned)
}
}
}
fn horizontal_aggregate(kind: HorizontalAgg, name: &str, values: Vec<Value>) -> Result<Value> {
fold_aggregate(FoldInput::Many(kind.0), name, values)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::exec::test_support::{agg_fn, duration};
use crate::graph::Graph;
fn list_row(values: Vec<Value>) -> Row {
let mut row = Row::new();
row.insert("x".into(), Value::List(values.into()));
row
}
fn rewritten(graph: &ExecGraph<'_>, row: &Row, expr: &Expr) -> Value {
match rewrite_horizontal_aggregates(graph, row, expr, &BTreeMap::new()).unwrap() {
Cow::Owned(Expr::RuntimeValue(value)) => value,
other => panic!("horizontal aggregate was not folded: {other:?}"),
}
}
#[test]
fn untransformed_trees_borrow_instead_of_cloning() {
let graph = Graph::default();
let graph = ExecGraph::read(&graph);
let empty = Row::new();
let plain = Expr::Binary {
op: relate_ir::BinaryOp::Gt,
left: Box::new(Expr::Variable("n".into())),
right: Box::new(Expr::Int(1)),
};
assert!(matches!(
rewrite_horizontal_aggregates(&graph, &empty, &plain, &BTreeMap::new()).unwrap(),
Cow::Borrowed(_)
));
assert!(matches!(
rewrite_horizontal_aggregates(&graph, &empty, &agg_fn("max"), &BTreeMap::new())
.unwrap(),
Cow::Borrowed(_)
));
let nested = Expr::Binary {
op: relate_ir::BinaryOp::Gt,
left: Box::new(agg_fn("max")),
right: Box::new(Expr::Int(1)),
};
assert!(matches!(
rewrite_horizontal_aggregates(&graph, &empty, &nested, &BTreeMap::new()).unwrap(),
Cow::Borrowed(_)
));
let foldable = agg_fn("max");
let folded = rewrite_horizontal_aggregates(
&graph,
&list_row(vec![Value::Int(1), Value::Int(3)]),
&foldable,
&BTreeMap::new(),
)
.unwrap();
assert!(matches!(folded, Cow::Owned(_)));
}
#[test]
fn horizontal_rewrite_folds_row_bound_list_kinds() {
let graph = Graph::default();
let graph = ExecGraph::read(&graph);
let row = list_row(vec![Value::Int(1), Value::Null, Value::Int(3)]);
assert_eq!(rewritten(&graph, &row, &agg_fn("sum")), Value::Int(4));
assert_eq!(rewritten(&graph, &row, &agg_fn("avg")), Value::Float(2.0));
assert_eq!(rewritten(&graph, &row, &agg_fn("min")), Value::Int(1));
assert_eq!(rewritten(&graph, &row, &agg_fn("max")), Value::Int(3));
assert_eq!(rewritten(&graph, &row, &agg_fn("count")), Value::Int(2));
assert_eq!(
rewritten(&graph, &row, &agg_fn("collect")),
Value::List(vec![Value::Int(1), Value::Int(3)].into())
);
let empty = list_row(vec![Value::Null]);
assert_eq!(rewritten(&graph, &empty, &agg_fn("sum")), Value::Int(0));
assert_eq!(rewritten(&graph, &empty, &agg_fn("avg")), Value::Null);
}
#[test]
fn horizontal_rewrite_sum_and_avg_accept_durations() {
let graph = Graph::default();
let graph = ExecGraph::read(&graph);
let row = list_row(vec![
Value::Null,
duration(0, 0, 1_000_000_000),
duration(0, 0, 3_000_000_000),
]);
assert_eq!(
rewritten(&graph, &row, &agg_fn("sum")),
duration(0, 0, 4_000_000_000)
);
assert_eq!(
rewritten(&graph, &row, &agg_fn("avg")),
duration(0, 0, 2_000_000_000)
);
let mixed = list_row(vec![duration(0, 0, 1), Value::Int(1)]);
assert!(
rewrite_horizontal_aggregates(&graph, &mixed, &agg_fn("sum"), &BTreeMap::new())
.is_err(),
"mixing durations and numbers is a type error"
);
}
#[test]
fn horizontal_rewrite_sum_and_avg_reject_non_numeric_values() {
let graph = Graph::default();
let graph = ExecGraph::read(&graph);
let row = list_row(vec![Value::String("x".into())]);
for name in ["sum", "avg"] {
assert!(
rewrite_horizontal_aggregates(&graph, &row, &agg_fn(name), &BTreeMap::new())
.is_err(),
"a non-numeric {name} operand is a type error"
);
}
}
#[test]
fn horizontal_rewrite_min_max_keep_the_first_of_equal_extremes() {
let graph = Graph::default();
let graph = ExecGraph::read(&graph);
for name in ["min", "max"] {
assert_eq!(
rewritten(
&graph,
&list_row(vec![Value::Int(1), Value::Float(1.0)]),
&agg_fn(name)
),
Value::Int(1),
"{name}"
);
assert_eq!(
rewritten(
&graph,
&list_row(vec![Value::Float(1.0), Value::Int(1)]),
&agg_fn(name)
),
Value::Float(1.0),
"{name}"
);
}
}
#[test]
fn horizontal_subset_excludes_stdev_and_percentiles() {
for kind in [
AggregateKind::StDev,
AggregateKind::StDevP,
AggregateKind::PercentileCont,
AggregateKind::PercentileDisc,
] {
assert!(HorizontalAgg::of(kind).is_none(), "{kind:?}");
}
for kind in [
AggregateKind::Count,
AggregateKind::Sum,
AggregateKind::Min,
AggregateKind::Max,
AggregateKind::Avg,
AggregateKind::Collect,
] {
assert!(HorizontalAgg::of(kind).is_some(), "{kind:?}");
}
}
}