use crate::optimizer::ApplyOrder;
use crate::{OptimizerConfig, OptimizerRule};
use datafusion_common::Result;
use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion_expr::expr::AggregateFunction;
use datafusion_expr::expr_rewriter::NamePreserver;
use datafusion_expr::{DistinctHandling, Expr, LogicalPlan};
#[derive(Default, Debug)]
pub struct EliminateAggregateDistinct {}
impl EliminateAggregateDistinct {
pub fn new() -> Self {
Self {}
}
}
impl OptimizerRule for EliminateAggregateDistinct {
fn name(&self) -> &str {
"eliminate_aggregate_distinct"
}
fn apply_order(&self) -> Option<ApplyOrder> {
Some(ApplyOrder::BottomUp)
}
fn rewrite(
&self,
plan: LogicalPlan,
_config: &dyn OptimizerConfig,
) -> Result<Transformed<LogicalPlan>> {
let LogicalPlan::Aggregate(aggregate) = &plan else {
return Ok(Transformed::no(plan));
};
if !can_strip_every_distinct(&aggregate.aggr_expr)? {
return Ok(Transformed::no(plan));
}
let name_preserver = NamePreserver::new(&plan);
plan.map_expressions(|expr| {
let saved_name = name_preserver.save(&expr);
expr.transform_down(strip_insensitive_distinct)
.map(|t| t.update_data(|e| saved_name.restore(e)))
})
}
}
fn can_strip_every_distinct(aggr_expr: &[Expr]) -> Result<bool> {
let mut found_distinct = false;
let mut all_insensitive = true;
for expr in aggr_expr {
expr.apply(|e| {
if let Expr::AggregateFunction(AggregateFunction { func, params }) = e
&& params.distinct
{
found_distinct = true;
if func.distinct_handling() != DistinctHandling::Insensitive {
all_insensitive = false;
return Ok(TreeNodeRecursion::Stop);
}
}
Ok(TreeNodeRecursion::Continue)
})?;
if !all_insensitive {
break;
}
}
Ok(found_distinct && all_insensitive)
}
fn strip_insensitive_distinct(expr: Expr) -> Result<Transformed<Expr>> {
Ok(match expr {
Expr::AggregateFunction(mut agg)
if agg.params.distinct
&& agg.func.distinct_handling() == DistinctHandling::Insensitive =>
{
agg.params.distinct = false;
Transformed::yes(Expr::AggregateFunction(agg))
}
_ => Transformed::no(expr),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::OptimizerContext;
use crate::assert_optimized_plan_eq_snapshot;
use crate::test::udfs::DistinctHandlingTestUDAF;
use crate::test::*;
use crate::single_distinct_to_groupby::SingleDistinctToGroupBy;
use datafusion_expr::{AggregateUDF, ExprFunctionExt, LogicalPlanBuilder, col, lit};
use datafusion_functions_aggregate::expr_fn::{bit_xor, max, min, sum};
use std::sync::Arc;
macro_rules! assert_optimized_plan_equal {
(
$plan:expr,
@ $expected:literal $(,)?
) => {{
let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> =
vec![Arc::new(EliminateAggregateDistinct::new())];
assert_optimized_plan_eq_snapshot!(
optimizer_ctx,
rules,
$plan,
@ $expected,
)
}};
}
fn tagged(name: &'static str, handling: DistinctHandling) -> AggregateUDF {
AggregateUDF::from(DistinctHandlingTestUDAF::new(name, handling))
}
#[test]
fn eliminate_distinct_from_min() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(vec![col("a")], vec![min(col("b")).distinct().build()?])?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b)]]
TableScan: test
")
}
#[test]
fn keep_distinct_on_sum() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(vec![col("a")], vec![sum(col("b")).distinct().build()?])?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[sum(DISTINCT test.b)]]
TableScan: test
")
}
#[test]
fn keep_distinct_on_bit_xor() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(vec![col("a")], vec![bit_xor(col("b")).distinct().build()?])?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[bit_xor(DISTINCT test.b)]]
TableScan: test
")
}
#[test]
fn mixed_node_is_left_alone() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
min(col("b")).distinct().build()?,
sum(col("c")).distinct().build()?,
],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[min(DISTINCT test.b), sum(DISTINCT test.c)]]
TableScan: test
")
}
#[test]
fn eliminate_distinct_from_every_insensitive_aggregate() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
min(col("b")).distinct().build()?,
max(col("c")).distinct().build()?,
],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b), max(test.c) AS max(DISTINCT test.c)]]
TableScan: test
")
}
#[test]
fn eliminate_distinct_beside_non_distinct_aggregate() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![min(col("b")).distinct().build()?, sum(col("c"))],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) AS min(DISTINCT test.b), sum(test.c)]]
TableScan: test
")
}
#[test]
fn keep_sensitive_distinct_in_group_expr() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![sum(col("c")).distinct().build()?],
vec![min(col("b")).distinct().build()?],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[sum(DISTINCT test.c)]], aggr=[[min(test.b) AS min(DISTINCT test.b)]]
TableScan: test
")
}
#[test]
fn eliminate_distinct_keeps_filter() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
min(col("b"))
.distinct()
.filter(col("c").gt(lit(0u32)))
.build()?,
],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[min(test.b) FILTER (WHERE test.c > UInt32(0)) AS min(DISTINCT test.b) FILTER (WHERE test.c > UInt32(0))]]
TableScan: test
")
}
#[test]
fn mixed_node_still_reaches_single_distinct_to_groupby() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
min(col("b")).distinct().build()?,
sum(col("b")).distinct().build()?,
],
)?
.build()?;
let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
let rules: Vec<Arc<dyn OptimizerRule + Send + Sync>> = vec![
Arc::new(EliminateAggregateDistinct::new()),
Arc::new(SingleDistinctToGroupBy::new()),
];
assert_optimized_plan_eq_snapshot!(
optimizer_ctx,
rules,
plan,
@r"
Projection: test.a, min(alias1) AS min(DISTINCT test.b), sum(alias1) AS sum(DISTINCT test.b)
Aggregate: groupBy=[[test.a]], aggr=[[min(alias1), sum(alias1)]]
Aggregate: groupBy=[[test.a, test.b AS alias1]], aggr=[[]]
TableScan: test
",
)
}
#[test]
fn eliminate_distinct_from_insensitive_udaf() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
tagged("first_seen", DistinctHandling::Insensitive)
.call(vec![col("b")])
.distinct()
.filter(col("c").gt(lit(0u32)))
.order_by(vec![col("b").sort(true, false)])
.build()?,
],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) FILTER (WHERE test.c > UInt32(0)) ORDER BY [test.b ASC NULLS LAST] AS first_seen(DISTINCT test.b) FILTER (WHERE test.c > UInt32(0)) ORDER BY [test.b ASC NULLS LAST]]]
TableScan: test
")
}
#[test]
fn keep_distinct_on_sensitive_udaf() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
tagged("counts_uniques", DistinctHandling::Sensitive)
.call(vec![col("b")])
.distinct()
.build()?,
],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[counts_uniques(DISTINCT test.b)]]
TableScan: test
")
}
#[test]
fn keep_distinct_on_unsupported_udaf() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
tagged("needs_dedup", DistinctHandling::Unsupported)
.call(vec![col("b")])
.distinct()
.build()?,
],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[needs_dedup(DISTINCT test.b)]]
TableScan: test
")
}
#[test]
fn mixed_udaf_node_is_left_alone() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
tagged("first_seen", DistinctHandling::Insensitive)
.call(vec![col("b")])
.distinct()
.build()?,
tagged("counts_uniques", DistinctHandling::Sensitive)
.call(vec![col("c")])
.distinct()
.build()?,
],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[first_seen(DISTINCT test.b), counts_uniques(DISTINCT test.c)]]
TableScan: test
")
}
#[test]
fn already_aliased_aggregate_gets_no_second_alias() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![
tagged("first_seen", DistinctHandling::Insensitive)
.call(vec![col("b")])
.distinct()
.build()?
.alias("m"),
],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) AS m]]
TableScan: test
")
}
#[test]
fn with_aliases_delegates_distinct_handling() -> Result<()> {
let aliased = tagged("first_seen", DistinctHandling::Insensitive)
.with_aliases(["first_hit"]);
assert_eq!(aliased.distinct_handling(), DistinctHandling::Insensitive);
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.aggregate(
vec![col("a")],
vec![aliased.call(vec![col("b")]).distinct().build()?],
)?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Aggregate: groupBy=[[test.a]], aggr=[[first_seen(test.b) AS first_seen(DISTINCT test.b)]]
TableScan: test
")
}
#[test]
fn non_aggregate_plan_is_unchanged() -> Result<()> {
let table_scan = test_table_scan()?;
let plan = LogicalPlanBuilder::from(table_scan)
.filter(col("b").gt(lit(1u32)))?
.project(vec![col("a")])?
.build()?;
assert_optimized_plan_equal!(plan, @r"
Projection: test.a
Filter: test.b > UInt32(1)
TableScan: test
")
}
}