Skip to main content

datafusion_functions_aggregate_common/
utils.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
5use arrow::array::{
6    Array, ArrayRef, ArrowNativeTypeOp, ArrowPrimitiveType, PrimitiveArray,
7};
8use arrow::compute::SortOptions;
9use arrow::datatypes::{
10    ArrowNativeType, DataType, DecimalType, Field, FieldRef, ToByteSlice,
11};
12use datafusion_common::cast::{as_list_array, as_primitive_array};
13use datafusion_common::hash_utils::RandomState;
14use datafusion_common::utils::SingleRowListArrayBuilder;
15use datafusion_common::utils::memory::estimate_memory_size;
16use datafusion_common::{
17    HashSet, Result, ScalarValue, exec_err, internal_datafusion_err,
18};
19use datafusion_expr_common::accumulator::Accumulator;
20use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
21use std::sync::Arc;
22
23/// Convert scalar values from an accumulator into arrays.
24pub fn get_accum_scalar_values_as_arrays(
25    accum: &mut dyn Accumulator,
26) -> Result<Vec<ArrayRef>> {
27    accum
28        .state()?
29        .iter()
30        .map(|s| s.to_array_of_size(1))
31        .collect()
32}
33
34/// Construct corresponding fields for the expressions in an ORDER BY clause.
35pub fn ordering_fields(
36    order_bys: &[PhysicalSortExpr],
37    // Data type of each expression in the ordering requirement
38    data_types: &[DataType],
39) -> Vec<FieldRef> {
40    order_bys
41        .iter()
42        .zip(data_types.iter())
43        .map(|(sort_expr, dtype)| {
44            Field::new(
45                sort_expr.expr.to_string().as_str(),
46                dtype.clone(),
47                // Multi partitions may be empty hence field should be nullable.
48                true,
49            )
50        })
51        .map(Arc::new)
52        .collect()
53}
54
55/// Selects the sort option attribute from all the given `PhysicalSortExpr`s.
56pub fn get_sort_options(ordering_req: &LexOrdering) -> Vec<SortOptions> {
57    ordering_req.iter().map(|item| item.options).collect()
58}
59
60/// A wrapper around a type to provide hash for floats
61#[derive(Copy, Clone, Debug)]
62pub struct Hashable<T>(pub T);
63
64impl<T: ToByteSlice> std::hash::Hash for Hashable<T> {
65    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
66        self.0.to_byte_slice().hash(state)
67    }
68}
69
70impl<T: ArrowNativeTypeOp> PartialEq for Hashable<T> {
71    fn eq(&self, other: &Self) -> bool {
72        self.0.is_eq(other.0)
73    }
74}
75
76impl<T: ArrowNativeTypeOp> Eq for Hashable<T> {}
77
78/// Computes averages for `Decimal128`/`Decimal256` values, checking for overflow
79///
80/// This is needed because different precisions for Decimal128/Decimal256 can
81/// store different ranges of values and thus sum/count may not fit in
82/// the target type.
83///
84/// For example, the precision is 3, the max of value is `999` and the min
85/// value is `-999`
86pub struct DecimalAverager<T: DecimalType> {
87    /// scale factor for sum values (10^sum_scale)
88    sum_mul: T::Native,
89    /// scale factor for target (10^target_scale)
90    target_mul: T::Native,
91    /// the output precision
92    target_precision: u8,
93    /// the output scale
94    target_scale: i8,
95}
96
97impl<T: DecimalType> DecimalAverager<T> {
98    /// Create a new `DecimalAverager`:
99    ///
100    /// * sum_scale: the scale of `sum` values passed to [`Self::avg`]
101    /// * target_precision: the output precision
102    /// * target_scale: the output scale
103    ///
104    /// Errors if the resulting data can not be stored
105    pub fn try_new(
106        sum_scale: i8,
107        target_precision: u8,
108        target_scale: i8,
109    ) -> Result<Self> {
110        let sum_mul = T::Native::from_usize(10_usize)
111            .map(|b| b.pow_wrapping(sum_scale as u32))
112            .ok_or_else(|| {
113                internal_datafusion_err!("Failed to compute sum_mul in DecimalAverager")
114            })?;
115
116        let target_mul = T::Native::from_usize(10_usize)
117            .map(|b| b.pow_wrapping(target_scale as u32))
118            .ok_or_else(|| {
119                internal_datafusion_err!(
120                    "Failed to compute target_mul in DecimalAverager"
121                )
122            })?;
123
124        if target_mul >= sum_mul {
125            Ok(Self {
126                sum_mul,
127                target_mul,
128                target_precision,
129                target_scale,
130            })
131        } else {
132            // can't convert the lit decimal to the returned data type
133            exec_err!("Arithmetic Overflow in AvgAccumulator")
134        }
135    }
136
137    /// Returns the `sum`/`count` as a i128/i256 Decimal128/Decimal256 with
138    /// target_scale and target_precision and reporting overflow.
139    ///
140    /// * sum: The total sum value stored as Decimal128 with sum_scale
141    ///   (passed to `Self::try_new`)
142    /// * count: total count, stored as a i128/i256 (*NOT* a Decimal128/Decimal256 value)
143    #[inline(always)]
144    pub fn avg(&self, sum: T::Native, count: T::Native) -> Result<T::Native> {
145        if let Ok(value) = sum.mul_checked(self.target_mul.div_wrapping(self.sum_mul)) {
146            let new_value = value.div_wrapping(count);
147
148            let validate = T::validate_decimal_precision(
149                new_value,
150                self.target_precision,
151                self.target_scale,
152            );
153
154            if validate.is_ok() {
155                Ok(new_value)
156            } else {
157                exec_err!("Arithmetic Overflow in AvgAccumulator")
158            }
159        } else {
160            // can't convert the lit decimal to the returned data type
161            exec_err!("Arithmetic Overflow in AvgAccumulator")
162        }
163    }
164}
165
166/// Generic way to collect distinct values for accumulators.
167///
168/// The intermediate state is represented as a List of scalar values updated by
169/// `merge_batch` and a `Vec` of `ArrayRef` that are converted to scalar values
170/// in the final evaluation step so that we avoid expensive conversions and
171/// allocations during `update_batch`.
172pub struct GenericDistinctBuffer<T: ArrowPrimitiveType> {
173    pub values: HashSet<Hashable<T::Native>, RandomState>,
174    data_type: DataType,
175}
176
177impl<T: ArrowPrimitiveType> std::fmt::Debug for GenericDistinctBuffer<T> {
178    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179        write!(
180            f,
181            "GenericDistinctBuffer({}, values={})",
182            self.data_type,
183            self.values.len()
184        )
185    }
186}
187
188impl<T: ArrowPrimitiveType> GenericDistinctBuffer<T> {
189    pub fn new(data_type: DataType) -> Self {
190        Self {
191            values: HashSet::default(),
192            data_type,
193        }
194    }
195
196    /// Mirrors [`Accumulator::state`].
197    pub fn state(&self) -> Result<Vec<ScalarValue>> {
198        let arr = Arc::new(
199            PrimitiveArray::<T>::from_iter_values(self.values.iter().map(|v| v.0))
200                // Ideally we'd just use T::DATA_TYPE but this misses things like
201                // decimal scale/precision and timestamp timezones, which need to
202                // match up with Accumulator::state_fields
203                .with_data_type(self.data_type.clone()),
204        );
205        Ok(vec![
206            SingleRowListArrayBuilder::new(arr).build_list_scalar(),
207        ])
208    }
209
210    /// Mirrors [`Accumulator::update_batch`].
211    pub fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
212        if values.is_empty() {
213            return Ok(());
214        }
215
216        debug_assert_eq!(
217            values.len(),
218            1,
219            "DistinctValuesBuffer::update_batch expects only a single input array"
220        );
221
222        let arr = as_primitive_array::<T>(&values[0])?;
223        if arr.null_count() > 0 {
224            self.values.extend(arr.iter().flatten().map(Hashable));
225        } else {
226            self.values
227                .extend(arr.values().iter().copied().map(Hashable));
228        }
229
230        Ok(())
231    }
232
233    /// Mirrors [`Accumulator::merge_batch`].
234    pub fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
235        if states.is_empty() {
236            return Ok(());
237        }
238
239        let array = as_list_array(&states[0])?;
240        for list in array.iter().flatten() {
241            self.update_batch(&[list])?;
242        }
243
244        Ok(())
245    }
246
247    /// Mirrors [`Accumulator::size`].
248    pub fn size(&self) -> usize {
249        let num_elements = self.values.len();
250        let fixed_size = size_of_val(self) + size_of_val(&self.values);
251        estimate_memory_size::<T::Native>(num_elements, fixed_size).unwrap()
252    }
253}