use crate::expressions::format_state_name;
use arrow::datatypes::{DataType, Field};
use std::any::Any;
use std::sync::Arc;
use ahash::RandomState;
use arrow::array::{Array, ArrayRef};
use arrow_array::cast::AsArray;
use arrow_array::types::*;
use arrow_array::ArrowNativeTypeOp;
use arrow_buffer::ArrowNativeType;
use std::collections::HashSet;
use crate::aggregate::sum::downcast_sum;
use crate::aggregate::utils::{down_cast_any_ref, Hashable};
use crate::{AggregateExpr, PhysicalExpr};
use datafusion_common::{not_impl_err, Result, ScalarValue};
use datafusion_expr::type_coercion::aggregates::sum_return_type;
use datafusion_expr::Accumulator;
#[derive(Debug)]
pub struct DistinctSum {
name: String,
data_type: DataType,
return_type: DataType,
exprs: Vec<Arc<dyn PhysicalExpr>>,
}
impl DistinctSum {
pub fn new(
exprs: Vec<Arc<dyn PhysicalExpr>>,
name: String,
data_type: DataType,
) -> Self {
let return_type = sum_return_type(&data_type).unwrap();
Self {
name,
data_type,
return_type,
exprs,
}
}
}
impl AggregateExpr for DistinctSum {
fn as_any(&self) -> &dyn Any {
self
}
fn field(&self) -> Result<Field> {
Ok(Field::new(&self.name, self.return_type.clone(), true))
}
fn state_fields(&self) -> Result<Vec<Field>> {
Ok(vec![Field::new_list(
format_state_name(&self.name, "sum distinct"),
Field::new("item", self.return_type.clone(), true),
false,
)])
}
fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.exprs.clone()
}
fn name(&self) -> &str {
&self.name
}
fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
macro_rules! helper {
($t:ty, $dt:expr) => {
Ok(Box::new(DistinctSumAccumulator::<$t>::try_new(&$dt)?))
};
}
downcast_sum!(self, helper)
}
}
impl PartialEq<dyn Any> for DistinctSum {
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.exprs.len() == x.exprs.len()
&& self
.exprs
.iter()
.zip(x.exprs.iter())
.all(|(this, other)| this.eq(other))
})
.unwrap_or(false)
}
}
struct DistinctSumAccumulator<T: ArrowPrimitiveType> {
values: HashSet<Hashable<T::Native>, RandomState>,
data_type: DataType,
}
impl<T: ArrowPrimitiveType> std::fmt::Debug for DistinctSumAccumulator<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DistinctSumAccumulator({})", self.data_type)
}
}
impl<T: ArrowPrimitiveType> DistinctSumAccumulator<T> {
pub fn try_new(data_type: &DataType) -> Result<Self> {
Ok(Self {
values: HashSet::default(),
data_type: data_type.clone(),
})
}
}
impl<T: ArrowPrimitiveType> Accumulator for DistinctSumAccumulator<T> {
fn state(&mut self) -> Result<Vec<ScalarValue>> {
let state_out = {
let distinct_values = self
.values
.iter()
.map(|value| {
ScalarValue::new_primitive::<T>(Some(value.0), &self.data_type)
})
.collect::<Result<Vec<_>>>()?;
vec![ScalarValue::List(ScalarValue::new_list(
&distinct_values,
&self.data_type,
))]
};
Ok(state_out)
}
fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
if values.is_empty() {
return Ok(());
}
let array = values[0].as_primitive::<T>();
match array.nulls().filter(|x| x.null_count() > 0) {
Some(n) => {
for idx in n.valid_indices() {
self.values.insert(Hashable(array.value(idx)));
}
}
None => array.values().iter().for_each(|x| {
self.values.insert(Hashable(*x));
}),
}
Ok(())
}
fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
for x in states[0].as_list::<i32>().iter().flatten() {
self.update_batch(&[x])?
}
Ok(())
}
fn evaluate(&mut self) -> Result<ScalarValue> {
let mut acc = T::Native::usize_as(0);
for distinct_value in self.values.iter() {
acc = acc.add_wrapping(distinct_value.0)
}
let v = (!self.values.is_empty()).then_some(acc);
ScalarValue::new_primitive::<T>(v, &self.data_type)
}
fn size(&self) -> usize {
std::mem::size_of_val(self)
+ self.values.capacity() * std::mem::size_of::<T::Native>()
}
}