Ted-Jiang commented on code in PR #2405:
URL: https://github.com/apache/arrow-datafusion/pull/2405#discussion_r863583500


##########
datafusion/physical-expr/src/aggregate/sum_distinct.rs:
##########
@@ -0,0 +1,301 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::aggregate::sum;
+use crate::expressions::format_state_name;
+use arrow::datatypes::{DataType, Field};
+use std::any::Any;
+use std::fmt::Debug;
+use std::sync::Arc;
+
+use ahash::RandomState;
+use arrow::array::{Array, ArrayRef};
+use std::collections::HashSet;
+
+use crate::{AggregateExpr, PhysicalExpr};
+use datafusion_common::ScalarValue;
+use datafusion_common::{DataFusionError, Result};
+use datafusion_expr::Accumulator;
+
+/// Expression for a SUM(DISTINCT) aggregation.
+#[derive(Debug)]
+pub struct DistinctSum {
+    /// Column name
+    name: String,
+    /// The DataType for the final sum
+    data_type: DataType,
+    /// The input arguments, only contains 1 item for sum
+    exprs: Vec<Arc<dyn PhysicalExpr>>,
+}
+
+impl DistinctSum {
+    /// Create a SUM(DISTINCT) aggregate function.
+    pub fn new(
+        exprs: Vec<Arc<dyn PhysicalExpr>>,
+        name: String,
+        data_type: DataType,
+    ) -> Self {
+        Self {
+            name,
+            data_type,
+            exprs,
+        }
+    }
+}
+
+impl AggregateExpr for DistinctSum {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn field(&self) -> Result<Field> {
+        Ok(Field::new(&self.name, self.data_type.clone(), true))
+    }
+
+    fn state_fields(&self) -> Result<Vec<Field>> {
+        // State field is a List which stores items to rebuild hash set.
+        Ok(vec![Field::new(
+            &format_state_name(&self.name, "sum distinct"),
+            DataType::List(Box::new(Field::new("item", self.data_type.clone(), 
true))),
+            false,
+        )])
+    }
+
+    fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
+        self.exprs.clone()
+    }
+
+    fn name(&self) -> &str {
+        &self.name
+    }
+
+    fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
+        Ok(Box::new(DistinctSumAccumulator::try_new(&self.data_type)?))
+    }
+}
+
+#[derive(Debug)]
+struct DistinctSumAccumulator {
+    hash_values: HashSet<ScalarValue, RandomState>,
+    data_type: DataType,
+}
+impl DistinctSumAccumulator {
+    pub fn try_new(data_type: &DataType) -> Result<Self> {
+        Ok(Self {
+            hash_values: HashSet::default(),
+            data_type: data_type.clone(),
+        })
+    }
+
+    fn update(&mut self, values: &[ScalarValue]) -> Result<()> {
+        values.iter().for_each(|v| {
+            // If the value is NULL, it is not included in the final sum.
+            if !v.is_null() {
+                self.hash_values.insert(v.clone());
+            }
+        });
+
+        Ok(())
+    }
+
+    fn merge(&mut self, states: &[ScalarValue]) -> Result<()> {
+        if states.is_empty() {
+            return Ok(());
+        }
+
+        states.iter().try_for_each(|state| match state {
+            ScalarValue::List(Some(values), _) => self.update(values.as_ref()),
+            _ => Err(DataFusionError::Internal(format!(
+                "Unexpected accumulator state {:?}",
+                state
+            ))),
+        })
+    }
+}
+
+impl Accumulator for DistinctSumAccumulator {
+    fn state(&self) -> Result<Vec<ScalarValue>> {
+        let mut cols_out = {
+            let values = Box::new(Vec::new());

Review Comment:
   `let values = Box::new(Vec::new());`
   A little confuse, why not change hashset to vec here. Without creating 
`cols_vec`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to