xudong963 commented on a change in pull request #1315:
URL: https://github.com/apache/arrow-datafusion/pull/1315#discussion_r750861384



##########
File path: datafusion/src/optimizer/single_distinct_to_groupby.rs
##########
@@ -0,0 +1,261 @@
+// 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.
+
+//! single distinct to group by optimizer rule
+
+use crate::error::Result;
+use crate::execution::context::ExecutionProps;
+use crate::logical_plan::{DFSchema, Expr, LogicalPlan};
+use crate::optimizer::optimizer::OptimizerRule;
+use crate::optimizer::utils;
+use std::sync::Arc;
+
+/// single distinct to group by optimizer rule
+///   - Aggregation
+///          GROUP BY (k)
+///          F1(DISTINCT s0, s1, ...),
+///          F2(DISTINCT s0, s1, ...),
+///       - X
+///
+///   into
+///
+///   - Aggregation
+///            GROUP BY (k)
+///            F1(x)
+///            F2(x)
+///       - Aggregation
+///               GROUP BY (k, s0, s1, ...)
+///            - X
+///   </pre>
+///   <p>
+pub struct SingleDistinctToGroupBy {}
+
+impl SingleDistinctToGroupBy {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+fn optimize(plan: &LogicalPlan, execution_props: &ExecutionProps) -> 
Result<LogicalPlan> {
+    match plan {
+        LogicalPlan::Aggregate {
+            input,
+            aggr_expr,
+            schema: _,
+            group_expr,
+        } => {
+            match is_single_agg(plan) {
+                true => {
+                    let mut all_group_args: Vec<Expr> = Vec::new();
+                    all_group_args.append(&mut group_expr.clone());
+                    // remove distinct and collection args
+                    let mut new_aggr_expr = aggr_expr
+                        .iter()
+                        .map(|aggfunc| match aggfunc {
+                            Expr::AggregateFunction { fun, args, .. } => {
+                                all_group_args.append(&mut args.clone());
+                                Expr::AggregateFunction {
+                                    fun: fun.clone(),
+                                    args: args.clone(),
+                                    distinct: false,
+                                }
+                            }
+                            _ => aggfunc.clone(),
+                        })
+                        .collect::<Vec<_>>();
+
+                    let all_field = all_group_args
+                        .iter()
+                        .map(|expr| expr.to_field(input.schema()).unwrap())
+                        .collect::<Vec<_>>();
+
+                    let grouped_schema = 
Arc::new(DFSchema::new(all_field).unwrap());
+                    let new_aggregate = LogicalPlan::Aggregate {
+                        input: input.clone(),
+                        group_expr: all_group_args,
+                        aggr_expr: Vec::new(),
+                        schema: grouped_schema,
+                    };
+                    let mut expres = group_expr.clone();
+                    expres.append(&mut new_aggr_expr);
+                    utils::from_plan(plan, &expres, &[new_aggregate])
+                }
+                false => {
+                    let expr = plan.expressions();
+                    // apply the optimization to all inputs of the plan
+                    let inputs = plan.inputs();
+
+                    let new_inputs = inputs
+                        .iter()
+                        .map(|plan| optimize(plan, execution_props))
+                        .collect::<Result<Vec<_>>>()?;
+
+                    utils::from_plan(plan, &expr, &new_inputs)
+                }
+            }
+        }
+        _ => {
+            let expr = plan.expressions();
+            let inputs = plan.inputs();
+            let new_inputs = inputs
+                .iter()
+                .map(|plan| optimize(plan, execution_props))
+                .collect::<Result<Vec<_>>>()?;
+            utils::from_plan(plan, &expr, &new_inputs)
+        }
+    }
+}
+
+fn is_single_agg(plan: &LogicalPlan) -> bool {
+    match plan {
+        LogicalPlan::Aggregate {
+            input: _,

Review comment:
       ditto, you can also check other places

##########
File path: datafusion/src/optimizer/single_distinct_to_groupby.rs
##########
@@ -0,0 +1,261 @@
+// 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.
+
+//! single distinct to group by optimizer rule
+
+use crate::error::Result;
+use crate::execution::context::ExecutionProps;
+use crate::logical_plan::{DFSchema, Expr, LogicalPlan};
+use crate::optimizer::optimizer::OptimizerRule;
+use crate::optimizer::utils;
+use std::sync::Arc;
+
+/// single distinct to group by optimizer rule
+///   - Aggregation
+///          GROUP BY (k)
+///          F1(DISTINCT s0, s1, ...),
+///          F2(DISTINCT s0, s1, ...),
+///       - X
+///
+///   into
+///
+///   - Aggregation
+///            GROUP BY (k)
+///            F1(x)
+///            F2(x)
+///       - Aggregation
+///               GROUP BY (k, s0, s1, ...)
+///            - X
+///   </pre>
+///   <p>
+pub struct SingleDistinctToGroupBy {}
+
+impl SingleDistinctToGroupBy {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+fn optimize(plan: &LogicalPlan, execution_props: &ExecutionProps) -> 
Result<LogicalPlan> {
+    match plan {
+        LogicalPlan::Aggregate {
+            input,
+            aggr_expr,
+            schema: _,
+            group_expr,
+        } => {

Review comment:
       ```suggestion
           LogicalPlan::Aggregate {
               input,
               aggr_expr,
               group_expr,
               ..
           } => {
   ```




-- 
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