Skip to main content

datafusion_functions_aggregate_common/aggregate/sum_distinct/
numeric.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Defines the accumulator for `SUM DISTINCT` for primitive numeric types
6
7use std::fmt::Debug;
8use std::mem::size_of_val;
9
10use arrow::array::ArrayRef;
11use arrow::array::ArrowNativeTypeOp;
12use arrow::array::ArrowPrimitiveType;
13use arrow::datatypes::ArrowNativeType;
14use arrow::datatypes::DataType;
15
16use datafusion_common::Result;
17use datafusion_common::ScalarValue;
18use datafusion_expr_common::accumulator::Accumulator;
19
20use crate::utils::GenericDistinctBuffer;
21
22/// Accumulator for computing SUM(DISTINCT expr)
23#[derive(Debug)]
24pub struct DistinctSumAccumulator<T: ArrowPrimitiveType> {
25    values: GenericDistinctBuffer<T>,
26    data_type: DataType,
27}
28
29impl<T: ArrowPrimitiveType> DistinctSumAccumulator<T> {
30    pub fn new(data_type: DataType) -> Self {
31        Self {
32            values: GenericDistinctBuffer::new(data_type.clone()),
33            data_type,
34        }
35    }
36
37    pub fn distinct_count(&self) -> usize {
38        self.values.values.len()
39    }
40
41    /// Iterates the distinct values collected so far. `AVG(DISTINCT)` re-sums
42    /// them in a wider type instead of using [`Self::evaluate`]'s input-typed
43    /// sum.
44    pub(crate) fn distinct_values(&self) -> impl Iterator<Item = T::Native> + '_ {
45        self.values.values.iter().map(|v| v.0)
46    }
47}
48
49impl<T: ArrowPrimitiveType + Debug> Accumulator for DistinctSumAccumulator<T> {
50    fn state(&mut self) -> Result<Vec<ScalarValue>> {
51        self.values.state()
52    }
53
54    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
55        self.values.update_batch(values)
56    }
57
58    fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
59        self.values.merge_batch(states)
60    }
61
62    fn evaluate(&mut self) -> Result<ScalarValue> {
63        if self.distinct_count() == 0 {
64            ScalarValue::new_primitive::<T>(None, &self.data_type)
65        } else {
66            let mut acc = T::Native::usize_as(0);
67            for distinct_value in self.values.values.iter() {
68                acc = acc.add_wrapping(distinct_value.0)
69            }
70            ScalarValue::new_primitive::<T>(Some(acc), &self.data_type)
71        }
72    }
73
74    fn size(&self) -> usize {
75        size_of_val(self) + self.values.size()
76    }
77}