alamb commented on code in PR #10591: URL: https://github.com/apache/datafusion/pull/10591#discussion_r1608953945
########## datafusion/optimizer/src/eliminate_group_by_constant.rs: ########## @@ -0,0 +1,318 @@ +// 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. + +//! [`EliminateGroupByConstant`] removes constant expressions from `GROUP BY` clause +use crate::optimizer::ApplyOrder; +use crate::{OptimizerConfig, OptimizerRule}; + +use datafusion_common::tree_node::Transformed; +use datafusion_common::{internal_err, Result}; +use datafusion_expr::{Aggregate, Expr, LogicalPlan, LogicalPlanBuilder, Volatility}; + +/// Optimizer rule that removes constant expressions from `GROUP BY` clause +/// and places additional projection on top of aggregation, to preserve +/// original schema +#[derive(Default)] +pub struct EliminateGroupByConstant {} + +impl EliminateGroupByConstant { + pub fn new() -> Self { + Self {} + } +} + +impl OptimizerRule for EliminateGroupByConstant { + fn supports_rewrite(&self) -> bool { + true + } + + fn rewrite( + &self, + plan: LogicalPlan, + _config: &dyn OptimizerConfig, + ) -> Result<Transformed<LogicalPlan>> { + match plan { + LogicalPlan::Aggregate(aggregate) => { + let (const_group_expr, nonconst_group_expr): (Vec<_>, Vec<_>) = aggregate + .group_expr + .iter() + .partition(|expr| is_constant_expression(expr)); + + // If no constant expressions found (nothing to optimize) or + // constant expression is the only expression in aggregate, + // optimization is skipped + if const_group_expr.is_empty() + || (!const_group_expr.is_empty() + && nonconst_group_expr.is_empty() + && aggregate.aggr_expr.is_empty()) + { + return Ok(Transformed::no(LogicalPlan::Aggregate(aggregate))); + } + + let simplified_aggregate = LogicalPlan::Aggregate(Aggregate::try_new( + aggregate.input, + nonconst_group_expr.into_iter().cloned().collect(), + aggregate.aggr_expr.clone(), + )?); + + let projection_expr = + aggregate.group_expr.into_iter().chain(aggregate.aggr_expr); + + let projection = LogicalPlanBuilder::from(simplified_aggregate) + .project(projection_expr)? + .build()?; + + Ok(Transformed::yes(projection)) + } + _ => Ok(Transformed::no(plan)), + } + } + + fn try_optimize( + &self, + _plan: &LogicalPlan, + _config: &dyn OptimizerConfig, + ) -> Result<Option<LogicalPlan>> { + internal_err!("Should have called EliminateGroupByConstant::rewrite") + } + + fn name(&self) -> &str { + "eliminate_group_by_constant" + } + + fn apply_order(&self) -> Option<ApplyOrder> { + Some(ApplyOrder::BottomUp) + } +} + +/// Checks if expression is constant, and can be eliminated from group by. +/// +/// Intended to be used only within this rule, helper function, which heavily +/// reiles on `SimplifyExpressions` result. +fn is_constant_expression(expr: &Expr) -> bool { Review Comment: I think you could use `TreeNode::Exists` here: https://github.com/apache/datafusion/blob/045e8fcaeac2f2c29afe5017e5efe5a3a2560080/datafusion/common/src/tree_node.rs#L408 Which handles all types of expressions and would be general Something like this, perhaps (untested) ```rust fn is_constant_expression(expr: &Expr) -> bool { !expr.exsts(|expr| { match expr { Expr::Column(_) => true, Expr::ScalarFunction(e) if matches!( e.func.signature().volatility, Volatility::Volatile ) => true, _ => false }) ``` ########## datafusion/sqllogictest/test_files/subquery.slt: ########## @@ -768,8 +766,8 @@ logical_plan 02)--Left Join: t1.t1_int = __scalar_sq_1.t2_int 03)----TableScan: t1 projection=[t1_id, t1_int] 04)----SubqueryAlias: __scalar_sq_1 -05)------Projection: COUNT(*), t2.t2_int, __always_true -06)--------Aggregate: groupBy=[[t2.t2_int, Boolean(true) AS __always_true]], aggr=[[COUNT(Int64(1)) AS COUNT(*)]] +05)------Projection: COUNT(*), t2.t2_int, Boolean(true) AS __always_true +06)--------Aggregate: groupBy=[[t2.t2_int]], aggr=[[COUNT(Int64(1)) AS COUNT(*)]] Review Comment: this certainly looks like a plan improvement (fewer grouping keys) -- among other thing that would also allow this query to use the faster specialized group accumulator -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
