datafusion_functions_aggregate_common/aggregate/avg_distinct/numeric.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19
20use arrow::array::ArrayRef;
21use arrow::datatypes::{DataType, Float64Type};
22use datafusion_common::{Result, ScalarValue};
23use datafusion_expr_common::accumulator::Accumulator;
24
25use crate::aggregate::sum_distinct::DistinctSumAccumulator;
26
27/// Specialized implementation of `AVG DISTINCT` for Float64 values, leveraging
28/// the existing DistinctSumAccumulator implementation.
29#[derive(Debug)]
30pub struct Float64DistinctAvgAccumulator {
31 // We use the DistinctSumAccumulator to handle the set of distinct values
32 sum_accumulator: DistinctSumAccumulator<Float64Type>,
33}
34
35impl Default for Float64DistinctAvgAccumulator {
36 fn default() -> Self {
37 Self {
38 sum_accumulator: DistinctSumAccumulator::<Float64Type>::new(
39 &DataType::Float64,
40 ),
41 }
42 }
43}
44
45impl Accumulator for Float64DistinctAvgAccumulator {
46 fn state(&mut self) -> Result<Vec<ScalarValue>> {
47 self.sum_accumulator.state()
48 }
49
50 fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
51 self.sum_accumulator.update_batch(values)
52 }
53
54 fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
55 self.sum_accumulator.merge_batch(states)
56 }
57
58 fn evaluate(&mut self) -> Result<ScalarValue> {
59 // Get the sum from the DistinctSumAccumulator
60 let sum_result = self.sum_accumulator.evaluate()?;
61
62 // Extract the sum value
63 if let ScalarValue::Float64(Some(sum)) = sum_result {
64 // Get the count of distinct values
65 let count = self.sum_accumulator.distinct_count() as f64;
66 // Calculate average
67 let avg = sum / count;
68 Ok(ScalarValue::Float64(Some(avg)))
69 } else {
70 // If sum is None, return None (null)
71 Ok(ScalarValue::Float64(None))
72 }
73 }
74
75 fn size(&self) -> usize {
76 self.sum_accumulator.size()
77 }
78}