|
| 1 | +use crate::analyzer::AnalyzerRule; |
| 2 | +use datafusion_common::config::ConfigOptions; |
| 3 | +use datafusion_common::Result; |
| 4 | +use datafusion_expr::expr::AggregateFunction; |
| 5 | +use datafusion_expr::utils::COUNT_STAR_EXPANSION; |
| 6 | +use datafusion_expr::{aggregate_function, lit, Aggregate, Expr, LogicalPlan}; |
| 7 | +use std::sync::Arc; |
| 8 | + |
| 9 | +pub struct CountWildcardRule {} |
| 10 | + |
| 11 | +impl CountWildcardRule { |
| 12 | + pub fn new() -> Self { |
| 13 | + CountWildcardRule {} |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +impl AnalyzerRule for CountWildcardRule { |
| 18 | + fn analyze( |
| 19 | + &self, |
| 20 | + plan: &LogicalPlan, |
| 21 | + _: &ConfigOptions, |
| 22 | + ) -> datafusion_common::Result<LogicalPlan> { |
| 23 | + let new_plan = match plan { |
| 24 | + LogicalPlan::Window(_window) => plan.clone(), |
| 25 | + LogicalPlan::Aggregate(aggregate) => { |
| 26 | + let aggr_expr = aggregate.clone().aggr_expr; |
| 27 | + let aggr_expr = handle_wildcard(aggr_expr).unwrap(); |
| 28 | + |
| 29 | + LogicalPlan::Aggregate( |
| 30 | + Aggregate::try_new_with_schema( |
| 31 | + Arc::new(plan.inputs().get(0).unwrap().clone().clone()), |
| 32 | + aggregate.clone().group_expr, |
| 33 | + aggr_expr, |
| 34 | + plan.schema().clone(), |
| 35 | + ) |
| 36 | + .unwrap(), |
| 37 | + ) |
| 38 | + } |
| 39 | + _ => plan.clone(), |
| 40 | + }; |
| 41 | + Ok(new_plan) |
| 42 | + } |
| 43 | + |
| 44 | + fn name(&self) -> &str { |
| 45 | + "count_wildcard_rule" |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +//handle Count(Expr:Wildcard) with DataFrame API |
| 50 | +pub fn handle_wildcard(exprs: Vec<Expr>) -> Result<Vec<Expr>> { |
| 51 | + let exprs: Vec<Expr> = exprs |
| 52 | + .iter() |
| 53 | + .map(|expr| match expr { |
| 54 | + Expr::AggregateFunction(AggregateFunction { |
| 55 | + fun: aggregate_function::AggregateFunction::Count, |
| 56 | + args, |
| 57 | + distinct, |
| 58 | + filter, |
| 59 | + }) if args.len() == 1 => match args[0] { |
| 60 | + Expr::Wildcard => Expr::AggregateFunction(AggregateFunction { |
| 61 | + fun: aggregate_function::AggregateFunction::Count, |
| 62 | + args: vec![lit(COUNT_STAR_EXPANSION)], |
| 63 | + distinct: *distinct, |
| 64 | + filter: filter.clone(), |
| 65 | + }), |
| 66 | + _ => expr.clone(), |
| 67 | + }, |
| 68 | + _ => expr.clone(), |
| 69 | + }) |
| 70 | + .collect(); |
| 71 | + Ok(exprs) |
| 72 | +} |
0 commit comments