pub mod stats;
pub mod utils;
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::{not_impl_err, Result};
use datafusion_expr::type_coercion::aggregates::check_arg_count;
use datafusion_expr::{
function::AccumulatorArgs, Accumulator, AggregateUDF, Expr, GroupsAccumulator,
};
use std::fmt::Debug;
use std::{any::Any, sync::Arc};
use crate::physical_expr::PhysicalExpr;
use crate::sort_expr::{LexOrdering, PhysicalSortExpr};
use self::utils::{down_cast_any_ref, ordering_fields};
pub fn create_aggregate_expr(
fun: &AggregateUDF,
input_phy_exprs: &[Arc<dyn PhysicalExpr>],
sort_exprs: &[Expr],
ordering_req: &[PhysicalSortExpr],
schema: &Schema,
name: impl Into<String>,
ignore_nulls: bool,
) -> Result<Arc<dyn AggregateExpr>> {
let input_exprs_types = input_phy_exprs
.iter()
.map(|arg| arg.data_type(schema))
.collect::<Result<Vec<_>>>()?;
check_arg_count(
fun.name(),
&input_exprs_types,
&fun.signature().type_signature,
)?;
let ordering_types = ordering_req
.iter()
.map(|e| e.expr.data_type(schema))
.collect::<Result<Vec<_>>>()?;
let ordering_fields = ordering_fields(ordering_req, &ordering_types);
Ok(Arc::new(AggregateFunctionExpr {
fun: fun.clone(),
args: input_phy_exprs.to_vec(),
data_type: fun.return_type(&input_exprs_types)?,
name: name.into(),
schema: schema.clone(),
sort_exprs: sort_exprs.to_vec(),
ordering_req: ordering_req.to_vec(),
ignore_nulls,
ordering_fields,
}))
}
pub trait AggregateExpr: Send + Sync + Debug + PartialEq<dyn Any> {
fn as_any(&self) -> &dyn Any;
fn field(&self) -> Result<Field>;
fn create_accumulator(&self) -> Result<Box<dyn Accumulator>>;
fn state_fields(&self) -> Result<Vec<Field>>;
fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>>;
fn order_bys(&self) -> Option<&[PhysicalSortExpr]> {
None
}
fn name(&self) -> &str {
"AggregateExpr: default name"
}
fn groups_accumulator_supported(&self) -> bool {
false
}
fn create_groups_accumulator(&self) -> Result<Box<dyn GroupsAccumulator>> {
not_impl_err!("GroupsAccumulator hasn't been implemented for {self:?} yet")
}
fn reverse_expr(&self) -> Option<Arc<dyn AggregateExpr>> {
None
}
fn create_sliding_accumulator(&self) -> Result<Box<dyn Accumulator>> {
not_impl_err!("Retractable Accumulator hasn't been implemented for {self:?} yet")
}
}
#[derive(Debug)]
pub struct AggregateFunctionExpr {
fun: AggregateUDF,
args: Vec<Arc<dyn PhysicalExpr>>,
data_type: DataType,
name: String,
schema: Schema,
sort_exprs: Vec<Expr>,
ordering_req: LexOrdering,
ignore_nulls: bool,
ordering_fields: Vec<Field>,
}
impl AggregateFunctionExpr {
pub fn fun(&self) -> &AggregateUDF {
&self.fun
}
}
impl AggregateExpr for AggregateFunctionExpr {
fn as_any(&self) -> &dyn Any {
self
}
fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.args.clone()
}
fn state_fields(&self) -> Result<Vec<Field>> {
self.fun.state_fields(
self.name(),
self.data_type.clone(),
self.ordering_fields.clone(),
)
}
fn field(&self) -> Result<Field> {
Ok(Field::new(&self.name, self.data_type.clone(), true))
}
fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
let acc_args = AccumulatorArgs::new(
&self.data_type,
&self.schema,
self.ignore_nulls,
&self.sort_exprs,
);
self.fun.accumulator(acc_args)
}
fn create_sliding_accumulator(&self) -> Result<Box<dyn Accumulator>> {
let accumulator = self.create_accumulator()?;
if !accumulator.supports_retract_batch() {
return not_impl_err!(
"Aggregate can not be used as a sliding accumulator because \
`retract_batch` is not implemented: {}",
self.name
);
}
Ok(accumulator)
}
fn name(&self) -> &str {
&self.name
}
fn groups_accumulator_supported(&self) -> bool {
self.fun.groups_accumulator_supported()
}
fn create_groups_accumulator(&self) -> Result<Box<dyn GroupsAccumulator>> {
self.fun.create_groups_accumulator()
}
fn order_bys(&self) -> Option<&[PhysicalSortExpr]> {
(!self.ordering_req.is_empty()).then_some(&self.ordering_req)
}
}
impl PartialEq<dyn Any> for AggregateFunctionExpr {
fn eq(&self, other: &dyn Any) -> bool {
down_cast_any_ref(other)
.downcast_ref::<Self>()
.map(|x| {
self.name == x.name
&& self.data_type == x.data_type
&& self.fun == x.fun
&& self.args.len() == x.args.len()
&& self
.args
.iter()
.zip(x.args.iter())
.all(|(this_arg, other_arg)| this_arg.eq(other_arg))
})
.unwrap_or(false)
}
}