## Coverage Report

#### Created: 2025-11-22 06:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)

    /Users/andrewlamb/Software/datafusion/datafusion/functions-aggregate-common/src/aggregate/count_distinct/native.rs

    Line
    Count
    Source
    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
    18
    //! Specialized implementation of `COUNT DISTINCT` for "Native" arrays such as
    19
    //! [`Int64Array`] and [`Float64Array`]
    20
    //!
    21
    //! [`Int64Array`]: arrow::array::Int64Array
    22
    //! [`Float64Array`]: arrow::array::Float64Array
    23
    use std::collections::HashSet;
    24
    use std::fmt::Debug;
    25
    use std::hash::Hash;
    26
    use std::mem::size_of_val;
    27
    use std::sync::Arc;
    28
    29
    use ahash::RandomState;
    30
    use arrow::array::types::ArrowPrimitiveType;
    31
    use arrow::array::ArrayRef;
    32
    use arrow::array::PrimitiveArray;
    33
    use arrow::datatypes::DataType;
    34
    35
    use datafusion_common::cast::{as_list_array, as_primitive_array};
    36
    use datafusion_common::utils::memory::estimate_memory_size;
    37
    use datafusion_common::utils::SingleRowListArrayBuilder;
    38
    use datafusion_common::ScalarValue;
    39
    use datafusion_expr_common::accumulator::Accumulator;
    40
    41
    use crate::utils::GenericDistinctBuffer;
    42
    43
    #[derive(Debug)]
    44
    pub struct PrimitiveDistinctCountAccumulator<T>
    45
    where
    46
        T: ArrowPrimitiveType + Send,
    47
        T::Native: Eq + Hash,
    48
    {
    49
        values: HashSet<T::Native, RandomState>,
    50
        data_type: DataType,
    51
    }
    52
    53
    impl<T> PrimitiveDistinctCountAccumulator<T>
    54
    where
    55
        T: ArrowPrimitiveType + Send,
    56
        T::Native: Eq + Hash,
    57
    {
    58
    0
        pub fn new(data_type: &DataType) -> Self {
    59
    0
            Self {
    60
    0
                values: HashSet::default(),
    61
    0
                data_type: data_type.clone(),
    62
    0
            }
    63
    0
        }
    64
    }
    65
    66
    impl<T> Accumulator for PrimitiveDistinctCountAccumulator<T>
    67
    where
    68
        T: ArrowPrimitiveType + Send + Debug,
    69
        T::Native: Eq + Hash,
    70
    {
    71
    0
        fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
    72
    0
            let arr = Arc::new(
    73
    0
                PrimitiveArray::<T>::from_iter_values(self.values.iter().cloned())
    74
    0
                    .with_data_type(self.data_type.clone()),
    75
            );
    76
    0
            Ok(vec![SingleRowListArrayBuilder::new(arr).build_list_scalar()])
    77
    0
        }
    78
    79
    0
        fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
    80
    0
            if values.is_empty() {
    81
    0
                return Ok(());
    82
    0
            }
    83
    84
    0
            let arr = as_primitive_array::<T>(&values[0])?;
    85
    0
            arr.iter().for_each(|value| {
    86
    0
                if let Some(value) = value {
    87
    0
                    self.values.insert(value);
    88
    0
                }
    89
    0
            });
    90
    91
    0
            Ok(())
    92
    0
        }
    93
    94
    0
        fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
    95
    0
            if states.is_empty() {
    96
    0
                return Ok(());
    97
    0
            }
    98
    0
            assert_eq!(
    99
    0
                states.len(),
    100
                1,
    101
    0
                "count_distinct states must be single array"
    102
            );
    103
    104
    0
            let arr = as_list_array(&states[0])?;
    105
    0
            arr.iter().try_for_each(|maybe_list| {
    106
    0
                if let Some(list) = maybe_list {
    107
    0
                    let list = as_primitive_array::<T>(&list)?;
    108
    0
                    self.values.extend(list.values())
    109
    0
                };
    110
    0
                Ok(())
    111
    0
            })
    112
    0
        }
    113
    114
    0
        fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
    115
    0
            Ok(ScalarValue::Int64(Some(self.values.len() as i64)))
    116
    0
        }
    117
    118
    0
        fn size(&self) -> usize {
    119
    0
            let num_elements = self.values.len();
    120
    0
            let fixed_size = size_of_val(self) + size_of_val(&self.values);
    121
    122
    0
            estimate_memory_size::<T::Native>(num_elements, fixed_size).unwrap()
    123
    0
        }
    124
    }
    125
    126
    #[derive(Debug)]
    127
    pub struct FloatDistinctCountAccumulator<T: ArrowPrimitiveType> {
    128
        values: GenericDistinctBuffer<T>,
    129
    }
    130
    131
    impl<T: ArrowPrimitiveType> FloatDistinctCountAccumulator<T> {
    132
    0
        pub fn new() -> Self {
    133
    0
            Self {
    134
    0
                values: GenericDistinctBuffer::new(T::DATA_TYPE),
    135
    0
            }
    136
    0
        }
    137
    }
    138
    139
    impl<T: ArrowPrimitiveType> Default for FloatDistinctCountAccumulator<T> {
    140
    0
        fn default() -> Self {
    141
    0
            Self::new()
    142
    0
        }
    143
    }
    144
    145
    impl<T: ArrowPrimitiveType + Debug> Accumulator for FloatDistinctCountAccumulator<T> {
    146
    0
        fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
    147
    0
            self.values.state()
    148
    0
        }
    149
    150
    0
        fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
    151
    0
            self.values.update_batch(values)
    152
    0
        }
    153
    154
    0
        fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
    155
    0
            self.values.merge_batch(states)
    156
    0
        }
    157
    158
    0
        fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
    159
    0
            Ok(ScalarValue::Int64(Some(self.values.values.len() as i64)))
    160
    0
        }
    161
    162
    0
        fn size(&self) -> usize {
    163
    0
            size_of_val(self) + self.values.size()
    164
    0
        }
    165
    }