Skip to main content

datafusion_functions_aggregate_common/aggregate/count_distinct/
dict.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::{ArrayRef, BooleanArray};
6use arrow::downcast_dictionary_array;
7use datafusion_common::internal_err;
8use datafusion_common::{ScalarValue, arrow_datafusion_err};
9use datafusion_expr_common::accumulator::Accumulator;
10
11#[derive(Debug)]
12pub struct DictionaryCountAccumulator {
13    inner: Box<dyn Accumulator>,
14}
15
16impl DictionaryCountAccumulator {
17    pub fn new(inner: Box<dyn Accumulator>) -> Self {
18        Self { inner }
19    }
20}
21
22impl Accumulator for DictionaryCountAccumulator {
23    fn update_batch(&mut self, values: &[ArrayRef]) -> datafusion_common::Result<()> {
24        let values: Vec<_> = values
25            .iter()
26            .map(|dict| {
27                downcast_dictionary_array! {
28                    dict => {
29                        let buff: BooleanArray = dict.occupancy().into();
30                        arrow::compute::filter(
31                            dict.values(),
32                            &buff
33                        ).map_err(|e| arrow_datafusion_err!(e))
34                    },
35                    _ => internal_err!("DictionaryCountAccumulator only supports dictionary arrays")
36                }
37            })
38            .collect::<Result<Vec<_>, _>>()?;
39        self.inner.update_batch(values.as_slice())
40    }
41
42    fn evaluate(&mut self) -> datafusion_common::Result<ScalarValue> {
43        self.inner.evaluate()
44    }
45
46    fn size(&self) -> usize {
47        self.inner.size()
48    }
49
50    fn state(&mut self) -> datafusion_common::Result<Vec<ScalarValue>> {
51        self.inner.state()
52    }
53
54    fn merge_batch(&mut self, states: &[ArrayRef]) -> datafusion_common::Result<()> {
55        self.inner.merge_batch(states)
56    }
57}