@@ -10,9 +10,10 @@ use datafusion_common::JoinType;
1010use datafusion_common:: tree_node:: Transformed ;
1111use datafusion_common:: { Column , DFSchemaRef , Result , ScalarValue , plan_err} ;
1212use datafusion_expr:: logical_plan:: LogicalPlan ;
13- use datafusion_expr:: { EmptyRelation , Expr , GroupingSet , Projection , Union , cast, lit} ;
13+ use datafusion_expr:: { EmptyRelation , Expr , Projection , Union , cast, lit} ;
1414
1515use crate :: optimizer:: ApplyOrder ;
16+ use crate :: utils:: aggregate_emits_on_empty_input;
1617use crate :: { OptimizerConfig , OptimizerRule } ;
1718
1819/// Optimization rule that bottom-up to eliminate plan by propagating empty_relation.
@@ -157,13 +158,7 @@ impl OptimizerRule for PropagateEmptyRelation {
157158 }
158159 }
159160 LogicalPlan :: Aggregate ( ref agg) => {
160- // An aggregate over an empty input can be eliminated only when
161- // there is no empty grouping set. An empty grouping set `()`
162- // (from `GROUPING SETS(())`, `ROLLUP(...)`, or `CUBE(...)`)
163- // always produces exactly one row even on empty input, so it
164- // must not be replaced by an empty relation.
165- if !agg. group_expr . is_empty ( )
166- && !has_empty_grouping_set ( & agg. group_expr )
161+ if !aggregate_emits_on_empty_input ( & agg. group_expr )
167162 && let Some ( empty_plan) = empty_child ( & plan) ?
168163 {
169164 return Ok ( Transformed :: yes ( empty_plan) ) ;
@@ -314,30 +309,6 @@ fn build_null_padded_projection(
314309 ) ?) )
315310}
316311
317- /// Returns `true` if any grouping set in the list of GROUP BY expressions is
318- /// the empty set `()`.
319- ///
320- /// An empty grouping set acts as a "grand total" group: the aggregate must
321- /// always produce **exactly one row** for it, even when the input is empty.
322- /// This means an aggregate with an empty grouping set cannot be replaced by
323- /// an empty relation.
324- ///
325- /// The three forms that can contain an empty grouping set:
326- /// - `GROUPING SETS (…, (), …)` — explicitly listed.
327- /// - `ROLLUP(exprs)` — always expands to include `()`.
328- /// - `CUBE(exprs)` — always expands to include `()`.
329- fn has_empty_grouping_set ( group_expr : & [ Expr ] ) -> bool {
330- match group_expr. first ( ) {
331- Some ( Expr :: GroupingSet ( GroupingSet :: GroupingSets ( groups) ) ) => {
332- groups. iter ( ) . any ( |g| g. is_empty ( ) )
333- }
334- // Both ROLLUP and CUBE always include the empty grouping set ().
335- Some ( Expr :: GroupingSet ( GroupingSet :: Rollup ( _) ) )
336- | Some ( Expr :: GroupingSet ( GroupingSet :: Cube ( _) ) ) => true ,
337- _ => false ,
338- }
339- }
340-
341312#[ cfg( test) ]
342313mod tests {
343314
0 commit comments