korowa commented on code in PR #10591: URL: https://github.com/apache/datafusion/pull/10591#discussion_r1615214582
########## 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: Thank you for the hint. I've checked id out, and seems like there is no TreeNode API method for this case, since it requires all arguments of scalar function to be literals, and `exists` will return on first match. -- 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]
