Skip to main content

datafusion_functions_aggregate_common/aggregate/avg_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
5use std::fmt::Debug;
6
7use arrow::array::ArrayRef;
8use arrow::datatypes::{DataType, Float64Type};
9use datafusion_common::{Result, ScalarValue};
10use datafusion_expr_common::accumulator::Accumulator;
11
12use crate::aggregate::sum_distinct::DistinctSumAccumulator;
13
14/// Specialized implementation of `AVG DISTINCT` for Float64 values, leveraging
15/// the existing DistinctSumAccumulator implementation.
16#[derive(Debug)]
17pub struct Float64DistinctAvgAccumulator {
18    // We use the DistinctSumAccumulator to handle the set of distinct values
19    sum_accumulator: DistinctSumAccumulator<Float64Type>,
20}
21
22impl Default for Float64DistinctAvgAccumulator {
23    fn default() -> Self {
24        Self {
25            sum_accumulator: DistinctSumAccumulator::<Float64Type>::new(
26                DataType::Float64,
27            ),
28        }
29    }
30}
31
32impl Accumulator for Float64DistinctAvgAccumulator {
33    fn state(&mut self) -> Result<Vec<ScalarValue>> {
34        self.sum_accumulator.state()
35    }
36
37    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
38        self.sum_accumulator.update_batch(values)
39    }
40
41    fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
42        self.sum_accumulator.merge_batch(states)
43    }
44
45    fn evaluate(&mut self) -> Result<ScalarValue> {
46        // Get the sum from the DistinctSumAccumulator
47        let sum_result = self.sum_accumulator.evaluate()?;
48
49        // Extract the sum value
50        if let ScalarValue::Float64(Some(sum)) = sum_result {
51            // Get the count of distinct values
52            let count = self.sum_accumulator.distinct_count() as f64;
53            // Calculate average
54            let avg = sum / count;
55            Ok(ScalarValue::Float64(Some(avg)))
56        } else {
57            // If sum is None, return None (null)
58            Ok(ScalarValue::Float64(None))
59        }
60    }
61
62    fn size(&self) -> usize {
63        self.sum_accumulator.size()
64    }
65}