Apache DataFusion SQL Query Engine
Add new physical rule CombinePartialFinalAggregate (#5837)
mingmwang1600a307f272
diff --git a/datafusion/core/src/execution/context.rs b/datafusion/core/src/execution/context.rsindex 5114adec72..41076b69de 100644--- a/datafusion/core/src/execution/context.rs+++ b/datafusion/core/src/execution/context.rs@@ -110,6 +110,7 @@ use datafusion_sql::planner::object_name_to_table_reference;use uuid::Uuid;// backwards compatibility+use crate::physical_optimizer::combine_partial_final_agg::CombinePartialFinalAggregate;pub use datafusion_execution::config::SessionConfig;pub use datafusion_execution::TaskContext;@@ -1329,6 +1330,9 @@ impl SessionState {// Note that one should always run this rule after running the EnforceDistribution rule// as the latter may break local sorting requirements.Arc::new(EnforceSorting::new()),+ // The CombinePartialFinalAggregate rule should be applied after the EnforceDistribution+ // and EnforceSorting rules+ Arc::new(CombinePartialFinalAggregate::new()),// The CoalesceBatches rule will not influence the distribution and ordering of the// whole plan tree. Therefore, to avoid influencing other rules, it should run last.Arc::new(CoalesceBatches::new()),diff --git a/datafusion/core/src/physical_optimizer/combine_partial_final_agg.rs b/datafusion/core/src/physical_optimizer/combine_partial_final_agg.rsnew file mode 100644index 0000000000..0674b6aa31--- /dev/null+++ b/datafusion/core/src/physical_optimizer/combine_partial_final_agg.rs@@ -0,0 +1,434 @@+// 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.++//! CombinePartialFinalAggregate optimizer rule checks the adjacent Partial and Final AggregateExecs+//! and try to combine them if necessary+use crate::error::Result;+use crate::physical_optimizer::PhysicalOptimizerRule;+use crate::physical_plan::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy};+use crate::physical_plan::ExecutionPlan;+use datafusion_common::config::ConfigOptions;+use std::sync::Arc;++use datafusion_common::tree_node::{Transformed, TreeNode};+use datafusion_physical_expr::expressions::Column;+use datafusion_physical_expr::{AggregateExpr, PhysicalExpr};++/// CombinePartialFinalAggregate optimizer rule combines the adjacent Partial and Final AggregateExecs+/// into a Single AggregateExec if their grouping exprs and aggregate exprs equal.+///+/// This rule should be applied after the EnforceDistribution and EnforceSorting rules+///+#[derive(Default)]+pub struct CombinePartialFinalAggregate {}++impl CombinePartialFinalAggregate {+ #[allow(missing_docs)]+ pub fn new() -> Self {+ Self {}+ }+}++impl PhysicalOptimizerRule for CombinePartialFinalAggregate {+ fn optimize(+ &self,+ plan: Arc<dyn ExecutionPlan>,+ _config: &ConfigOptions,+ ) -> Result<Arc<dyn ExecutionPlan>> {+ plan.transform_down(&|plan| {+ let transformed = plan.as_any().downcast_ref::<AggregateExec>().and_then(+ |AggregateExec {+ mode: final_mode,+ input: final_input,+ group_by: final_group_by,+ aggr_expr: final_aggr_expr,+ filter_expr: final_filter_expr,+ ..+ }| {+ if matches!(+ final_mode,+ AggregateMode::Final | AggregateMode::FinalPartitioned+ ) {+ final_input+ .as_any()+ .downcast_ref::<AggregateExec>()+ .and_then(+ |AggregateExec {+ mode: input_mode,+ input: partial_input,+ group_by: input_group_by,+ aggr_expr: input_aggr_expr,+ filter_expr: input_filter_expr,+ input_schema,+ ..+ }| {+ if matches!(input_mode, AggregateMode::Partial)+ && can_combine(+ (+ final_group_by,+ final_aggr_expr,+ final_filter_expr,+ ),+ (+ input_group_by,+ input_aggr_expr,+ input_filter_expr,+ ),+ )+ {+ AggregateExec::try_new(+ AggregateMode::Single,+ input_group_by.clone(),+ input_aggr_expr.to_vec(),+ input_filter_expr.to_vec(),+ partial_input.clone(),+ input_schema.clone(),+ )+ .ok()+ .map(Arc::new)+ } else {+ None+ }+ },+ )+ } else {+ None+ }+ },+ );++ Ok(if let Some(transformed) = transformed {+ Transformed::Yes(transformed)+ } else {+ Transformed::No(plan)+ })+ })+ }++ fn name(&self) -> &str {+ "CombinePartialFinalAggregate"+ }++ fn schema_check(&self) -> bool {+ true+ }+}++type GroupExprsRef<'a> = (+ &'a PhysicalGroupBy,+ &'a [Arc<dyn AggregateExpr>],+ &'a [Option<Arc<dyn PhysicalExpr>>],+);++type GroupExprs = (+ PhysicalGroupBy,+ Vec<Arc<dyn AggregateExpr>>,+ Vec<Option<Arc<dyn PhysicalExpr>>>,+);++fn can_combine(final_agg: GroupExprsRef, partial_agg: GroupExprsRef) -> bool {+ let (final_group_by, final_aggr_expr, final_filter_expr) =+ normalize_group_exprs(final_agg);+ let (input_group_by, input_aggr_expr, input_filter_expr) =+ normalize_group_exprs(partial_agg);++ final_group_by.eq(&input_group_by)+ && final_aggr_expr.len() == input_aggr_expr.len()+ && final_aggr_expr+ .iter()+ .zip(input_aggr_expr.iter())+ .all(|(final_expr, partial_expr)| final_expr.eq(partial_expr))+ && final_filter_expr.len() == input_filter_expr.len()+ && final_filter_expr.iter().zip(input_filter_expr.iter()).all(+ |(final_expr, partial_expr)| match (final_expr, partial_expr) {+ (Some(l), Some(r)) => l.eq(r),+ (None, None) => true,+ _ => false,+ },+ )+}++// To compare the group expressions between the final and partial aggregations, need to discard all the column indexes and compare+fn normalize_group_exprs(group_exprs: GroupExprsRef) -> GroupExprs {+ let (group, agg, filter) = group_exprs;+ let new_group_expr = group+ .expr()+ .iter()+ .map(|(expr, name)| (discard_column_index(expr.clone()), name.clone()))+ .collect::<Vec<_>>();+ let new_group = PhysicalGroupBy::new(+ new_group_expr,+ group.null_expr().to_vec(),+ group.groups().to_vec(),+ );+ (new_group, agg.to_vec(), filter.to_vec())+}++fn discard_column_index(group_expr: Arc<dyn PhysicalExpr>) -> Arc<dyn PhysicalExpr> {+ group_expr+ .clone()+ .transform(&|expr| {+ let normalized_form: Option<Arc<dyn PhysicalExpr>> =+ match expr.as_any().downcast_ref::<Column>() {+ Some(column) => Some(Arc::new(Column::new(column.name(), 0))),+ None => None,+ };+ Ok(if let Some(normalized_form) = normalized_form {+ Transformed::Yes(normalized_form)+ } else {+ Transformed::No(expr)+ })+ })+ .unwrap_or(group_expr)+}++#[cfg(test)]+mod tests {+ use arrow::datatypes::{DataType, Field, Schema, SchemaRef};+ use datafusion_physical_expr::expressions::{col, Count, Sum};+ use datafusion_physical_expr::AggregateExpr;++ use super::*;+ use crate::datasource::listing::PartitionedFile;+ use crate::datasource::object_store::ObjectStoreUrl;+ use crate::physical_plan::aggregates::{+ AggregateExec, AggregateMode, PhysicalGroupBy,+ };+ use crate::physical_plan::expressions::lit;+ use crate::physical_plan::file_format::{FileScanConfig, ParquetExec};+ use crate::physical_plan::repartition::RepartitionExec;+ use crate::physical_plan::{displayable, Partitioning, Statistics};++ /// Runs the CombinePartialFinalAggregate optimizer and asserts the plan against the expected+ macro_rules! assert_optimized {+ ($EXPECTED_LINES: expr, $PLAN: expr) => {+ let expected_lines: Vec<&str> = $EXPECTED_LINES.iter().map(|s| *s).collect();++ // run optimizer+ let optimizer = CombinePartialFinalAggregate {};+ let config = ConfigOptions::new();+ let optimized = optimizer.optimize($PLAN, &config)?;+ // Now format correctly+ let plan = displayable(optimized.as_ref()).indent().to_string();+ let actual_lines = trim_plan_display(&plan);++ assert_eq!(+ &expected_lines, &actual_lines,+ "\n\nexpected:\n\n{:#?}\nactual:\n\n{:#?}\n\n",+ expected_lines, actual_lines+ );+ };+ }++ fn trim_plan_display(plan: &str) -> Vec<&str> {+ plan.split('\n')+ .map(|s| s.trim())+ .filter(|s| !s.is_empty())+ .collect()+ }++ fn schema() -> SchemaRef {+ Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int64, true),+ Field::new("b", DataType::Int64, true),+ Field::new("c", DataType::Int64, true),+ ]))+ }++ fn parquet_exec(schema: &SchemaRef) -> Arc<ParquetExec> {+ Arc::new(ParquetExec::new(+ FileScanConfig {+ object_store_url: ObjectStoreUrl::parse("test:///").unwrap(),+ file_schema: schema.clone(),+ file_groups: vec![vec![PartitionedFile::new("x".to_string(), 100)]],+ statistics: Statistics::default(),+ projection: None,+ limit: None,+ table_partition_cols: vec![],+ output_ordering: None,+ infinite_source: false,+ },+ None,+ None,+ ))+ }++ fn partial_aggregate_exec(+ input: Arc<dyn ExecutionPlan>,+ group_by: PhysicalGroupBy,+ aggr_expr: Vec<Arc<dyn AggregateExpr>>,+ ) -> Arc<dyn ExecutionPlan> {+ let schema = input.schema();+ Arc::new(+ AggregateExec::try_new(+ AggregateMode::Partial,+ group_by,+ aggr_expr,+ vec![],+ input,+ schema,+ )+ .unwrap(),+ )+ }++ fn final_aggregate_exec(+ input: Arc<dyn ExecutionPlan>,+ group_by: PhysicalGroupBy,+ aggr_expr: Vec<Arc<dyn AggregateExpr>>,+ ) -> Arc<dyn ExecutionPlan> {+ let schema = input.schema();+ Arc::new(+ AggregateExec::try_new(+ AggregateMode::Final,+ group_by,+ aggr_expr,+ vec![],+ input,+ schema,+ )+ .unwrap(),+ )+ }++ fn repartition_exec(input: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {+ Arc::new(+ RepartitionExec::try_new(input, Partitioning::RoundRobinBatch(10)).unwrap(),+ )+ }++ #[test]+ fn aggregations_not_combined() -> Result<()> {+ let schema = schema();++ let aggr_expr = vec![Arc::new(Count::new(+ lit(1i8),+ "COUNT(1)".to_string(),+ DataType::Int64,+ )) as _];+ let plan = final_aggregate_exec(+ repartition_exec(partial_aggregate_exec(+ parquet_exec(&schema),+ PhysicalGroupBy::default(),+ aggr_expr.clone(),+ )),+ PhysicalGroupBy::default(),+ aggr_expr,+ );+ // should not combine the Partial/Final AggregateExecs+ let expected = &[+ "AggregateExec: mode=Final, gby=[], aggr=[COUNT(1)]",+ "RepartitionExec: partitioning=RoundRobinBatch(10), input_partitions=1",+ "AggregateExec: mode=Partial, gby=[], aggr=[COUNT(1)]",+ "ParquetExec: limit=None, partitions={1 group: [[x]]}, projection=[a, b, c]",+ ];+ assert_optimized!(expected, plan);++ let aggr_expr1 = vec![Arc::new(Count::new(+ lit(1i8),+ "COUNT(1)".to_string(),+ DataType::Int64,+ )) as _];+ let aggr_expr2 = vec![Arc::new(Count::new(+ lit(1i8),+ "COUNT(2)".to_string(),+ DataType::Int64,+ )) as _];++ let plan = final_aggregate_exec(+ partial_aggregate_exec(+ parquet_exec(&schema),+ PhysicalGroupBy::default(),+ aggr_expr1,+ ),+ PhysicalGroupBy::default(),+ aggr_expr2,+ );+ // should not combine the Partial/Final AggregateExecs+ let expected = &[+ "AggregateExec: mode=Final, gby=[], aggr=[COUNT(2)]",+ "AggregateExec: mode=Partial, gby=[], aggr=[COUNT(1)]",+ "ParquetExec: limit=None, partitions={1 group: [[x]]}, projection=[a, b, c]",+ ];++ assert_optimized!(expected, plan);++ Ok(())+ }++ #[test]+ fn aggregations_combined() -> Result<()> {+ let schema = schema();+ let aggr_expr = vec![Arc::new(Count::new(+ lit(1i8),+ "COUNT(1)".to_string(),+ DataType::Int64,+ )) as _];++ let plan = final_aggregate_exec(+ partial_aggregate_exec(+ parquet_exec(&schema),+ PhysicalGroupBy::default(),+ aggr_expr.clone(),+ ),+ PhysicalGroupBy::default(),+ aggr_expr,+ );+ // should combine the Partial/Final AggregateExecs to tne Single AggregateExec+ let expected = &[+ "AggregateExec: mode=Single, gby=[], aggr=[COUNT(1)]",+ "ParquetExec: limit=None, partitions={1 group: [[x]]}, projection=[a, b, c]",+ ];++ assert_optimized!(expected, plan);+ Ok(())+ }++ #[test]+ fn aggregations_with_group_combined() -> Result<()> {+ let schema = schema();+ let aggr_expr = vec![Arc::new(Sum::new(+ col("b", &schema)?,+ "Sum(b)".to_string(),+ DataType::Int64,+ )) as _];++ let groups: Vec<(Arc<dyn PhysicalExpr>, String)> =+ vec![(col("c", &schema)?, "c".to_string())];++ let partial_group_by = PhysicalGroupBy::new_single(groups);+ let partial_agg = partial_aggregate_exec(+ parquet_exec(&schema),+ partial_group_by,+ aggr_expr.clone(),+ );++ let groups: Vec<(Arc<dyn PhysicalExpr>, String)> =+ vec![(col("c", &partial_agg.schema())?, "c".to_string())];+ let final_group_by = PhysicalGroupBy::new_single(groups);++ let plan = final_aggregate_exec(partial_agg, final_group_by, aggr_expr);+ // should combine the Partial/Final AggregateExecs to tne Single AggregateExec+ let expected = &[+ "AggregateExec: mode=Single, gby=[c@2 as c], aggr=[Sum(b)]",+ "ParquetExec: limit=None, partitions={1 group: [[x]]}, projection=[a, b, c]",+ ];++ assert_optimized!(expected, plan);+ Ok(())+ }+}diff --git a/datafusion/core/src/physical_optimizer/mod.rs b/datafusion/core/src/physical_optimizer/mod.rsindex 5111e55292..b4c019d62b 100644--- a/datafusion/core/src/physical_optimizer/mod.rs+++ b/datafusion/core/src/physical_optimizer/mod.rs@@ -20,6 +20,7 @@pub mod aggregate_statistics;pub mod coalesce_batches;+pub mod combine_partial_final_agg;pub mod dist_enforcement;pub mod global_sort_selection;pub mod join_selection;diff --git a/datafusion/core/src/physical_plan/aggregates/mod.rs b/datafusion/core/src/physical_plan/aggregates/mod.rsindex 3cc8fd5d7d..3ec9a6d712 100644--- a/datafusion/core/src/physical_plan/aggregates/mod.rs+++ b/datafusion/core/src/physical_plan/aggregates/mod.rs@@ -66,6 +66,10 @@ pub enum AggregateMode {/// with Hash repartitioning on the group keys. If a group key is/// duplicated, duplicate groups would be producedFinalPartitioned,+ /// Applies the entire logical aggregation operation in a single operator,+ /// as opposed to Partial / Final modes which apply the logical aggregation using+ /// two operators.+ Single,}/// Represents `GROUP BY` clause in the plan (including the more general GROUPING SET)@@ -148,6 +152,24 @@ impl PhysicalGroupBy {}}+impl PartialEq for PhysicalGroupBy {+ fn eq(&self, other: &PhysicalGroupBy) -> bool {+ self.expr.len() == other.expr.len()+ && self+ .expr+ .iter()+ .zip(other.expr.iter())+ .all(|((expr1, name1), (expr2, name2))| expr1.eq(expr2) && name1 == name2)+ && self.null_expr.len() == other.null_expr.len()+ && self+ .null_expr+ .iter()+ .zip(other.null_expr.iter())+ .all(|((expr1, name1), (expr2, name2))| expr1.eq(expr2) && name1 == name2)+ && self.groups == other.groups+ }+}+enum StreamType {AggregateStream(AggregateStream),GroupedHashAggregateStream(GroupedHashAggregateStream),@@ -328,8 +350,8 @@ impl ExecutionPlan for AggregateExec {/// Get the output partitioning of this planfn output_partitioning(&self) -> Partitioning {match &self.mode {- AggregateMode::Partial => {- // Partial Aggregation will not change the output partitioning but need to respect the Alias+ AggregateMode::Partial | AggregateMode::Single => {+ // Partial and Single Aggregation will not change the output partitioning but need to respect the Aliaslet input_partition = self.input.output_partitioning();match input_partition {Partitioning::Hash(exprs, part) => {@@ -372,7 +394,9 @@ impl ExecutionPlan for AggregateExec {fn required_input_distribution(&self) -> Vec<Distribution> {match &self.mode {- AggregateMode::Partial => vec![Distribution::UnspecifiedDistribution],+ AggregateMode::Partial | AggregateMode::Single => {+ vec![Distribution::UnspecifiedDistribution]+ }AggregateMode::FinalPartitioned => {vec![Distribution::HashPartitioned(self.output_group_expr())]}@@ -541,7 +565,9 @@ fn create_schema(fields.extend(expr.state_fields()?.iter().cloned())}}- AggregateMode::Final | AggregateMode::FinalPartitioned => {+ AggregateMode::Final+ | AggregateMode::FinalPartitioned+ | AggregateMode::Single => {// in final mode, the field with the final result of the accumulatorfor expr in aggr_expr {fields.push(expr.field()?)@@ -567,7 +593,7 @@ fn aggregate_expressions(col_idx_base: usize,) -> Result<Vec<Vec<Arc<dyn PhysicalExpr>>>> {match mode {- AggregateMode::Partial => Ok(aggr_expr+ AggregateMode::Partial | AggregateMode::Single => Ok(aggr_expr.iter().map(|agg| {let pre_cast_type = if let Some(Sum {@@ -665,7 +691,7 @@ fn create_row_accumulators(}/// returns a vector of ArrayRefs, where each entry corresponds to either the-/// final value (mode = Final) or states (mode = Partial)+/// final value (mode = Final, FinalPartitioned and Single) or states (mode = Partial)fn finalize_aggregation(accumulators: &[AccumulatorItem],mode: &AggregateMode,@@ -684,7 +710,9 @@ fn finalize_aggregation(.collect::<Result<Vec<_>>>()?;Ok(a.iter().flatten().cloned().collect::<Vec<_>>())}- AggregateMode::Final | AggregateMode::FinalPartitioned => {+ AggregateMode::Final+ | AggregateMode::FinalPartitioned+ | AggregateMode::Single => {// merge the state to the final valueaccumulators.iter()diff --git a/datafusion/core/src/physical_plan/aggregates/no_grouping.rs b/datafusion/core/src/physical_plan/aggregates/no_grouping.rsindex efeae8716d..101b157a36 100644--- a/datafusion/core/src/physical_plan/aggregates/no_grouping.rs+++ b/datafusion/core/src/physical_plan/aggregates/no_grouping.rs@@ -75,7 +75,7 @@ impl AggregateStream {) -> Result<Self> {let aggregate_expressions = aggregate_expressions(&aggr_expr, &mode, 0)?;let filter_expressions = match mode {- AggregateMode::Partial => filter_expr,+ AggregateMode::Partial | AggregateMode::Single => filter_expr,AggregateMode::Final | AggregateMode::FinalPartitioned => {vec![None; aggr_expr.len()]}@@ -215,7 +215,9 @@ fn aggregate_batch(// 1.4let size_pre = accum.size();let res = match mode {- AggregateMode::Partial => accum.update_batch(values),+ AggregateMode::Partial | AggregateMode::Single => {+ accum.update_batch(values)+ }AggregateMode::Final | AggregateMode::FinalPartitioned => {accum.merge_batch(values)}diff --git a/datafusion/core/src/physical_plan/aggregates/row_hash.rs b/datafusion/core/src/physical_plan/aggregates/row_hash.rsindex 3cc2442543..9a75da02fb 100644--- a/datafusion/core/src/physical_plan/aggregates/row_hash.rs+++ b/datafusion/core/src/physical_plan/aggregates/row_hash.rs@@ -155,7 +155,7 @@ impl GroupedHashAggregateStream {let all_aggregate_expressions =aggregates::aggregate_expressions(&aggr_expr, &mode, start_idx)?;let filter_expressions = match mode {- AggregateMode::Partial => filter_expr,+ AggregateMode::Partial | AggregateMode::Single => filter_expr,AggregateMode::Final | AggregateMode::FinalPartitioned => {vec![None; aggr_expr.len()]}@@ -447,7 +447,7 @@ impl GroupedHashAggregateStream {state_accessor.point_to(0, group_state.aggregation_buffer.as_mut_slice());match self.mode {- AggregateMode::Partial => {+ AggregateMode::Partial | AggregateMode::Single => {accumulator.update_batch(&values, &mut state_accessor)}AggregateMode::FinalPartitioned | AggregateMode::Final => {@@ -470,7 +470,9 @@ impl GroupedHashAggregateStream {)?;let size_pre = accumulator.size();let res = match self.mode {- AggregateMode::Partial => accumulator.update_batch(&values),+ AggregateMode::Partial | AggregateMode::Single => {+ accumulator.update_batch(&values)+ }AggregateMode::FinalPartitioned | AggregateMode::Final => {// note: the aggregation here is over states, not values, thus the mergeaccumulator.merge_batch(&values)@@ -632,7 +634,9 @@ impl GroupedHashAggregateStream {AggregateMode::Partial => {read_as_batch(&state_buffers, &self.row_aggr_schema, RowType::WordAligned)}- AggregateMode::Final | AggregateMode::FinalPartitioned => {+ AggregateMode::Final+ | AggregateMode::FinalPartitioned+ | AggregateMode::Single => {let mut results = vec![];for (idx, acc) in self.row_accumulators.iter().enumerate() {let mut state_accessor =@@ -674,15 +678,15 @@ impl GroupedHashAggregateStream {.expect("Unexpected accumulator state in hash aggregate")}),),- AggregateMode::Final | AggregateMode::FinalPartitioned => {- ScalarValue::iter_to_array(group_state_chunk.iter().map(- |group_state| {- group_state.accumulator_set[idx].evaluate().expect(- "Unexpected accumulator state in hash aggregate",- )- },- ))- }+ AggregateMode::Final+ | AggregateMode::FinalPartitioned+ | AggregateMode::Single => ScalarValue::iter_to_array(+ group_state_chunk.iter().map(|group_state| {+ group_state.accumulator_set[idx]+ .evaluate()+ .expect("Unexpected accumulator state in hash aggregate")+ }),+ ),}?;// Cast output if needed (e.g. for types like Dictionary where// the intermediate GroupByScalar type was not the same as thediff --git a/datafusion/core/src/physical_plan/udaf.rs b/datafusion/core/src/physical_plan/udaf.rsindex 6f55b31e49..cbbb851865 100644--- a/datafusion/core/src/physical_plan/udaf.rs+++ b/datafusion/core/src/physical_plan/udaf.rs@@ -31,6 +31,7 @@ use crate::error::Result;use crate::physical_plan::PhysicalExpr;pub use datafusion_expr::AggregateUDF;+use datafusion_physical_expr::aggregate::utils::down_cast_any_ref;use std::sync::Arc;/// Creates a physical expression of the UDAF, that includes all necessary type coercion.@@ -102,3 +103,22 @@ impl AggregateExpr for AggregateFunctionExpr {&self.name}}++impl PartialEq<dyn Any> for AggregateFunctionExpr {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.fun == x.fun+ && self.args.len() == x.args.len()+ && self+ .args+ .iter()+ .zip(x.args.iter())+ .all(|(this_arg, other_arg)| this_arg.eq(other_arg))+ })+ .unwrap_or(false)+ }+}diff --git a/datafusion/core/tests/sql/joins.rs b/datafusion/core/tests/sql/joins.rsindex 245f257adb..3213ae3e05 100644--- a/datafusion/core/tests/sql/joins.rs+++ b/datafusion/core/tests/sql/joins.rs@@ -1772,6 +1772,171 @@ async fn right_semi_join() -> Result<()> {Ok(())}+#[tokio::test]+async fn join_and_aggregate_on_same_key() -> Result<()> {+ let ctx = create_join_context("t1_id", "t2_id", true)?;+ let sql = "select distinct(t1.t1_id) from t1 inner join t2 on t1.t1_id = t2.t2_id";++ // assert logical plan+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(&("explain ".to_owned() + sql)).await.expect(&msg);+ let plan = dataframe.into_optimized_plan().unwrap();++ let expected = vec![+ "Explain [plan_type:Utf8, plan:Utf8]",+ " Aggregate: groupBy=[[t1.t1_id]], aggr=[[]] [t1_id:UInt32;N]",+ " Projection: t1.t1_id [t1_id:UInt32;N]",+ " Inner Join: t1.t1_id = t2.t2_id [t1_id:UInt32;N, t2_id:UInt32;N]",+ " TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",+ " TableScan: t2 projection=[t2_id] [t2_id:UInt32;N]",+ ];++ let formatted = plan.display_indent_schema().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ let msg = format!("Creating physical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let physical_plan = dataframe.create_physical_plan().await?;+ let expected =+ vec![+ "AggregateExec: mode=Single, gby=[t1_id@0 as t1_id], aggr=[]",+ " ProjectionExec: expr=[t1_id@0 as t1_id]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " HashJoinExec: mode=Partitioned, join_type=Inner, on=[(Column { name: \"t1_id\", index: 0 }, Column { name: \"t2_id\", index: 0 })]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " RepartitionExec: partitioning=Hash([Column { name: \"t1_id\", index: 0 }], 2), input_partitions=2",+ " RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1",+ " MemoryExec: partitions=1, partition_sizes=[1]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " RepartitionExec: partitioning=Hash([Column { name: \"t2_id\", index: 0 }], 2), input_partitions=2",+ " RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1",+ " MemoryExec: partitions=1, partition_sizes=[1]",+ ];++ let formatted = displayable(physical_plan.as_ref()).indent().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ let sql = "select count(*) from (select * from t1 inner join t2 on t1.t1_id = t2.t2_id) group by t1_id";++ // assert logical plan+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(&("explain ".to_owned() + sql)).await.expect(&msg);+ let plan = dataframe.into_optimized_plan().unwrap();++ let expected = vec![+ "Explain [plan_type:Utf8, plan:Utf8]",+ " Projection: COUNT(UInt8(1)) [COUNT(UInt8(1)):Int64;N]",+ " Aggregate: groupBy=[[t1.t1_id]], aggr=[[COUNT(UInt8(1))]] [t1_id:UInt32;N, COUNT(UInt8(1)):Int64;N]",+ " Projection: t1.t1_id [t1_id:UInt32;N]",+ " Inner Join: t1.t1_id = t2.t2_id [t1_id:UInt32;N, t2_id:UInt32;N]",+ " TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",+ " TableScan: t2 projection=[t2_id] [t2_id:UInt32;N]",+ ];++ let formatted = plan.display_indent_schema().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ let msg = format!("Creating physical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let physical_plan = dataframe.create_physical_plan().await?;+ let expected =+ vec![+ "ProjectionExec: expr=[COUNT(UInt8(1))@1 as COUNT(UInt8(1))]",+ " AggregateExec: mode=Single, gby=[t1_id@0 as t1_id], aggr=[COUNT(UInt8(1))]",+ " ProjectionExec: expr=[t1_id@0 as t1_id]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " HashJoinExec: mode=Partitioned, join_type=Inner, on=[(Column { name: \"t1_id\", index: 0 }, Column { name: \"t2_id\", index: 0 })]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " RepartitionExec: partitioning=Hash([Column { name: \"t1_id\", index: 0 }], 2), input_partitions=2",+ " RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1",+ " MemoryExec: partitions=1, partition_sizes=[1]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " RepartitionExec: partitioning=Hash([Column { name: \"t2_id\", index: 0 }], 2), input_partitions=2",+ " RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1",+ " MemoryExec: partitions=1, partition_sizes=[1]",+ ];++ let formatted = displayable(physical_plan.as_ref()).indent().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ let sql =+ "select count(distinct t1.t1_id) from t1 inner join t2 on t1.t1_id = t2.t2_id";++ // assert logical plan+ let msg = format!("Creating logical plan for '{sql}'");+ let dataframe = ctx.sql(&("explain ".to_owned() + sql)).await.expect(&msg);+ let plan = dataframe.into_optimized_plan().unwrap();++ let expected = vec![+ "Explain [plan_type:Utf8, plan:Utf8]",+ " Projection: COUNT(alias1) AS COUNT(DISTINCT t1.t1_id) [COUNT(DISTINCT t1.t1_id):Int64;N]",+ " Aggregate: groupBy=[[]], aggr=[[COUNT(alias1)]] [COUNT(alias1):Int64;N]",+ " Aggregate: groupBy=[[t1.t1_id AS alias1]], aggr=[[]] [alias1:UInt32;N]",+ " Projection: t1.t1_id [t1_id:UInt32;N]",+ " Inner Join: t1.t1_id = t2.t2_id [t1_id:UInt32;N, t2_id:UInt32;N]",+ " TableScan: t1 projection=[t1_id] [t1_id:UInt32;N]",+ " TableScan: t2 projection=[t2_id] [t2_id:UInt32;N]",+ ];++ let formatted = plan.display_indent_schema().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ // the Partial and FinalPartitioned Aggregate are not combined to Single Aggregate due to group by exprs are different+ // TODO improve ReplaceDistinctWithAggregate rule to avoid unnecessary alias Cast+ let msg = format!("Creating physical plan for '{sql}'");+ let dataframe = ctx.sql(sql).await.expect(&msg);+ let physical_plan = dataframe.create_physical_plan().await?;+ let expected =+ vec![+ "ProjectionExec: expr=[COUNT(alias1)@0 as COUNT(DISTINCT t1.t1_id)]",+ " AggregateExec: mode=Final, gby=[], aggr=[COUNT(alias1)]",+ " CoalescePartitionsExec",+ " AggregateExec: mode=Partial, gby=[], aggr=[COUNT(alias1)]",+ " AggregateExec: mode=FinalPartitioned, gby=[alias1@0 as alias1], aggr=[]",+ " AggregateExec: mode=Partial, gby=[t1_id@0 as alias1], aggr=[]",+ " ProjectionExec: expr=[t1_id@0 as t1_id]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " HashJoinExec: mode=Partitioned, join_type=Inner, on=[(Column { name: \"t1_id\", index: 0 }, Column { name: \"t2_id\", index: 0 })]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " RepartitionExec: partitioning=Hash([Column { name: \"t1_id\", index: 0 }], 2), input_partitions=2",+ " RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1",+ " MemoryExec: partitions=1, partition_sizes=[1]",+ " CoalesceBatchesExec: target_batch_size=4096",+ " RepartitionExec: partitioning=Hash([Column { name: \"t2_id\", index: 0 }], 2), input_partitions=2",+ " RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1",+ " MemoryExec: partitions=1, partition_sizes=[1]",+ ];++ let formatted = displayable(physical_plan.as_ref()).indent().to_string();+ let actual: Vec<&str> = formatted.trim().lines().collect();+ assert_eq!(+ expected, actual,+ "\n\nexpected:\n\n{expected:#?}\nactual:\n\n{actual:#?}\n\n"+ );++ Ok(())+}+#[tokio::test]async fn reduce_cross_join_with_expr_join_key_all() -> Result<()> {let ctx = create_join_context("t1_id", "t2_id", false)?;diff --git a/datafusion/core/tests/sqllogictests/test_files/window.slt b/datafusion/core/tests/sqllogictests/test_files/window.sltindex 8781308219..2213c95ec7 100644--- a/datafusion/core/tests/sqllogictests/test_files/window.slt+++ b/datafusion/core/tests/sqllogictests/test_files/window.slt@@ -358,22 +358,21 @@ physical_planSortPreservingMergeExec: [b@0 ASC NULLS LAST]SortExec: expr=[b@0 ASC NULLS LAST]ProjectionExec: expr=[b@0 as b, MAX(d.a)@1 as max_a, MAX(d.seq)@2 as MAX(d.seq)]- AggregateExec: mode=FinalPartitioned, gby=[b@0 as b], aggr=[MAX(d.a), MAX(d.seq)]- AggregateExec: mode=Partial, gby=[b@2 as b], aggr=[MAX(d.a), MAX(d.seq)]- ProjectionExec: expr=[ROW_NUMBER() PARTITION BY [s.b] ORDER BY [s.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as seq, a@0 as a, b@1 as b]- BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }]- SortExec: expr=[b@1 ASC NULLS LAST,a@0 ASC NULLS LAST]- CoalesceBatchesExec: target_batch_size=8192- RepartitionExec: partitioning=Hash([Column { name: "b", index: 1 }], 4), input_partitions=4- UnionExec- ProjectionExec: expr=[1 as a, aa as b]- EmptyExec: produce_one_row=true- ProjectionExec: expr=[3 as a, aa as b]- EmptyExec: produce_one_row=true- ProjectionExec: expr=[5 as a, bb as b]- EmptyExec: produce_one_row=true- ProjectionExec: expr=[7 as a, bb as b]- EmptyExec: produce_one_row=true+ AggregateExec: mode=Single, gby=[b@2 as b], aggr=[MAX(d.a), MAX(d.seq)]+ ProjectionExec: expr=[ROW_NUMBER() PARTITION BY [s.b] ORDER BY [s.a ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as seq, a@0 as a, b@1 as b]+ BoundedWindowAggExec: wdw=[ROW_NUMBER(): Ok(Field { name: "ROW_NUMBER()", data_type: UInt64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int64(NULL)), end_bound: CurrentRow }]+ SortExec: expr=[b@1 ASC NULLS LAST,a@0 ASC NULLS LAST]+ CoalesceBatchesExec: target_batch_size=8192+ RepartitionExec: partitioning=Hash([Column { name: "b", index: 1 }], 4), input_partitions=4+ UnionExec+ ProjectionExec: expr=[1 as a, aa as b]+ EmptyExec: produce_one_row=true+ ProjectionExec: expr=[3 as a, aa as b]+ EmptyExec: produce_one_row=true+ ProjectionExec: expr=[5 as a, bb as b]+ EmptyExec: produce_one_row=true+ ProjectionExec: expr=[7 as a, bb as b]+ EmptyExec: produce_one_row=true# check actual resultdiff --git a/datafusion/physical-expr/src/aggregate/approx_distinct.rs b/datafusion/physical-expr/src/aggregate/approx_distinct.rsindex 73fa7f79df..b8922e1992 100644--- a/datafusion/physical-expr/src/aggregate/approx_distinct.rs+++ b/datafusion/physical-expr/src/aggregate/approx_distinct.rs@@ -18,6 +18,7 @@//! Defines physical expressions that can evaluated at runtime during query executionuse super::hyperloglog::HyperLogLog;+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};use arrow::array::{@@ -114,6 +115,19 @@ impl AggregateExpr for ApproxDistinct {}}+impl PartialEq<dyn Any> for ApproxDistinct {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.input_data_type == x.input_data_type+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]struct BinaryHLLAccumulator<T>wherediff --git a/datafusion/physical-expr/src/aggregate/approx_median.rs b/datafusion/physical-expr/src/aggregate/approx_median.rsindex 3befd7a818..cbbfef5a89 100644--- a/datafusion/physical-expr/src/aggregate/approx_median.rs+++ b/datafusion/physical-expr/src/aggregate/approx_median.rs@@ -17,6 +17,7 @@//! Defines physical expressions for APPROX_MEDIAN that can be evaluated MEDIAN at runtime during query execution+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::{lit, ApproxPercentileCont};use crate::{AggregateExpr, PhysicalExpr};use arrow::{datatypes::DataType, datatypes::Field};@@ -82,3 +83,17 @@ impl AggregateExpr for ApproxMedian {&self.name}}++impl PartialEq<dyn Any> for ApproxMedian {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.expr.eq(&x.expr)+ && self.approx_percentile == x.approx_percentile+ })+ .unwrap_or(false)+ }+}diff --git a/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rs b/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rsindex fcb8e914ff..f0a44cc97a 100644--- a/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rs+++ b/datafusion/physical-expr/src/aggregate/approx_percentile_cont.rs@@ -17,6 +17,7 @@use crate::aggregate::tdigest::TryIntoF64;use crate::aggregate::tdigest::{TDigest, DEFAULT_MAX_SIZE};+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::{format_state_name, Literal};use crate::{AggregateExpr, PhysicalExpr};use arrow::{@@ -114,6 +115,21 @@ impl ApproxPercentileCont {}}+impl PartialEq for ApproxPercentileCont {+ fn eq(&self, other: &ApproxPercentileCont) -> bool {+ self.name == other.name+ && self.input_data_type == other.input_data_type+ && self.percentile == other.percentile+ && self.tdigest_max_size == other.tdigest_max_size+ && self.expr.len() == other.expr.len()+ && self+ .expr+ .iter()+ .zip(other.expr.iter())+ .all(|(this, other)| this.eq(other))+ }+}+fn validate_input_percentile_expr(expr: &Arc<dyn PhysicalExpr>) -> Result<f64> {// Extract the desired percentile literallet lit = expr@@ -232,6 +248,15 @@ impl AggregateExpr for ApproxPercentileCont {}}+impl PartialEq<dyn Any> for ApproxPercentileCont {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| self.eq(x))+ .unwrap_or(false)+ }+}+#[derive(Debug)]pub struct ApproxPercentileAccumulator {digest: TDigest,diff --git a/datafusion/physical-expr/src/aggregate/approx_percentile_cont_with_weight.rs b/datafusion/physical-expr/src/aggregate/approx_percentile_cont_with_weight.rsindex 71fb3d242a..ee5ef7228f 100644--- a/datafusion/physical-expr/src/aggregate/approx_percentile_cont_with_weight.rs+++ b/datafusion/physical-expr/src/aggregate/approx_percentile_cont_with_weight.rs@@ -28,6 +28,7 @@ use datafusion_common::Result;use datafusion_common::ScalarValue;use datafusion_expr::Accumulator;+use crate::aggregate::utils::down_cast_any_ref;use std::{any::Any, sync::Arc};/// APPROX_PERCENTILE_CONT_WITH_WEIGTH aggregate expression@@ -100,6 +101,20 @@ impl AggregateExpr for ApproxPercentileContWithWeight {}}+impl PartialEq<dyn Any> for ApproxPercentileContWithWeight {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.approx_percentile_cont == x.approx_percentile_cont+ && self.column_expr.eq(&x.column_expr)+ && self.weight_expr.eq(&x.weight_expr)+ && self.percentile_expr.eq(&x.percentile_expr)+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]pub struct ApproxPercentileWithWeightAccumulator {approx_percentile_cont_accumulator: ApproxPercentileAccumulator,diff --git a/datafusion/physical-expr/src/aggregate/array_agg.rs b/datafusion/physical-expr/src/aggregate/array_agg.rsindex 35f6caa643..ebf24750cb 100644--- a/datafusion/physical-expr/src/aggregate/array_agg.rs+++ b/datafusion/physical-expr/src/aggregate/array_agg.rs@@ -17,6 +17,7 @@//! Defines physical expressions that can evaluated at runtime during query execution+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};use arrow::array::ArrayRef;@@ -86,6 +87,19 @@ impl AggregateExpr for ArrayAgg {}}+impl PartialEq<dyn Any> for ArrayAgg {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.input_data_type == x.input_data_type+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]pub(crate) struct ArrayAggAccumulator {values: Vec<ScalarValue>,diff --git a/datafusion/physical-expr/src/aggregate/array_agg_distinct.rs b/datafusion/physical-expr/src/aggregate/array_agg_distinct.rsindex d292e8baca..2d7a6e5b0e 100644--- a/datafusion/physical-expr/src/aggregate/array_agg_distinct.rs+++ b/datafusion/physical-expr/src/aggregate/array_agg_distinct.rs@@ -25,6 +25,7 @@ use std::sync::Arc;use arrow::array::{Array, ArrayRef};use std::collections::HashSet;+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};use datafusion_common::Result;@@ -95,6 +96,19 @@ impl AggregateExpr for DistinctArrayAgg {}}+impl PartialEq<dyn Any> for DistinctArrayAgg {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.input_data_type == x.input_data_type+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]struct DistinctArrayAggAccumulator {values: HashSet<ScalarValue>,diff --git a/datafusion/physical-expr/src/aggregate/average.rs b/datafusion/physical-expr/src/aggregate/average.rsindex eaf30ea10f..7888b8b17f 100644--- a/datafusion/physical-expr/src/aggregate/average.rs+++ b/datafusion/physical-expr/src/aggregate/average.rs@@ -27,6 +27,7 @@ use crate::aggregate::row_accumulator::{use crate::aggregate::sum;use crate::aggregate::sum::sum_batch;use crate::aggregate::utils::calculate_result_decimal_for_avg;+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};use arrow::compute;@@ -159,6 +160,20 @@ impl AggregateExpr for Avg {}}+impl PartialEq<dyn Any> for Avg {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.sum_data_type == x.sum_data_type+ && self.rt_data_type == x.rt_data_type+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+/// An accumulator to compute the average#[derive(Debug)]pub struct AvgAccumulator {diff --git a/datafusion/physical-expr/src/aggregate/correlation.rs b/datafusion/physical-expr/src/aggregate/correlation.rsindex 1bed3fe03f..475bfa4ce0 100644--- a/datafusion/physical-expr/src/aggregate/correlation.rs+++ b/datafusion/physical-expr/src/aggregate/correlation.rs@@ -20,6 +20,7 @@use crate::aggregate::covariance::CovarianceAccumulator;use crate::aggregate::stats::StatsType;use crate::aggregate::stddev::StddevAccumulator;+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};use arrow::{@@ -117,6 +118,17 @@ impl AggregateExpr for Correlation {}}+impl PartialEq<dyn Any> for Correlation {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name && self.expr1.eq(&x.expr1) && self.expr2.eq(&x.expr2)+ })+ .unwrap_or(false)+ }+}+/// An accumulator to compute correlation#[derive(Debug)]pub struct CorrelationAccumulator {diff --git a/datafusion/physical-expr/src/aggregate/count.rs b/datafusion/physical-expr/src/aggregate/count.rsindex ae581b5c1a..c00520516a 100644--- a/datafusion/physical-expr/src/aggregate/count.rs+++ b/datafusion/physical-expr/src/aggregate/count.rs@@ -23,6 +23,7 @@ use std::ops::BitAnd;use std::sync::Arc;use crate::aggregate::row_accumulator::RowAccumulator;+use crate::aggregate::utils::down_cast_any_ref;use crate::{AggregateExpr, PhysicalExpr};use arrow::array::{Array, Int64Array};use arrow::compute;@@ -152,6 +153,25 @@ impl AggregateExpr for Count {}}+impl PartialEq<dyn Any> for Count {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.nullable == x.nullable+ && self.exprs.len() == x.exprs.len()+ && self+ .exprs+ .iter()+ .zip(x.exprs.iter())+ .all(|(expr1, expr2)| expr1.eq(expr2))+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]struct CountAccumulator {count: i64,@@ -250,8 +270,8 @@ impl RowAccumulator for CountRowAccumulator {#[cfg(test)]mod tests {use super::*;- use crate::expressions::col;use crate::expressions::tests::aggregate;+ use crate::expressions::{col, lit};use crate::generic_test_op;use arrow::record_batch::RecordBatch;use arrow::{array::*, datatypes::*};@@ -341,4 +361,30 @@ mod tests {assert_eq!(expected, actual);Ok(())}++ #[test]+ fn count_eq() -> Result<()> {+ let count = Count::new(lit(1i8), "COUNT(1)".to_string(), DataType::Int64);+ let arc_count: Arc<dyn AggregateExpr> = Arc::new(Count::new(+ lit(1i8),+ "COUNT(1)".to_string(),+ DataType::Int64,+ ));+ let box_count: Box<dyn AggregateExpr> = Box::new(Count::new(+ lit(1i8),+ "COUNT(1)".to_string(),+ DataType::Int64,+ ));+ let count2 = Count::new(lit(1i8), "COUNT(2)".to_string(), DataType::Int64);++ assert!(arc_count.eq(&box_count));+ assert!(box_count.eq(&arc_count));+ assert!(arc_count.eq(&count));+ assert!(count.eq(&box_count));+ assert!(count.eq(&arc_count));++ assert!(count2.ne(&arc_count));++ Ok(())+ }}diff --git a/datafusion/physical-expr/src/aggregate/count_distinct.rs b/datafusion/physical-expr/src/aggregate/count_distinct.rsindex be62dcea6c..94e6c08283 100644--- a/datafusion/physical-expr/src/aggregate/count_distinct.rs+++ b/datafusion/physical-expr/src/aggregate/count_distinct.rs@@ -24,6 +24,7 @@ use ahash::RandomState;use arrow::array::{Array, ArrayRef};use std::collections::HashSet;+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};use datafusion_common::ScalarValue;@@ -92,6 +93,19 @@ impl AggregateExpr for DistinctCount {}}+impl PartialEq<dyn Any> for DistinctCount {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.state_data_type == x.state_data_type+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]struct DistinctCountAccumulator {values: HashSet<DistinctScalarValues, RandomState>,diff --git a/datafusion/physical-expr/src/aggregate/covariance.rs b/datafusion/physical-expr/src/aggregate/covariance.rsindex f0625aef7e..5e589d4e39 100644--- a/datafusion/physical-expr/src/aggregate/covariance.rs+++ b/datafusion/physical-expr/src/aggregate/covariance.rs@@ -33,6 +33,7 @@ use datafusion_common::{DataFusionError, Result};use datafusion_expr::Accumulator;use crate::aggregate::stats::StatsType;+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;/// COVAR and COVAR_SAMP aggregate expression@@ -117,6 +118,17 @@ impl AggregateExpr for Covariance {}}+impl PartialEq<dyn Any> for Covariance {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name && self.expr1.eq(&x.expr1) && self.expr2.eq(&x.expr2)+ })+ .unwrap_or(false)+ }+}+impl CovariancePop {/// Create a new COVAR_POP aggregate functionpub fn new(@@ -185,6 +197,17 @@ impl AggregateExpr for CovariancePop {}}+impl PartialEq<dyn Any> for CovariancePop {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name && self.expr1.eq(&x.expr1) && self.expr2.eq(&x.expr2)+ })+ .unwrap_or(false)+ }+}+/// An accumulator to compute covariance/// The algrithm used is an online implementation and numerically stable. It is derived from the following paper/// for calculating variance:diff --git a/datafusion/physical-expr/src/aggregate/grouping.rs b/datafusion/physical-expr/src/aggregate/grouping.rsindex 9ddd17c035..7ba303960e 100644--- a/datafusion/physical-expr/src/aggregate/grouping.rs+++ b/datafusion/physical-expr/src/aggregate/grouping.rs@@ -20,6 +20,7 @@use std::any::Any;use std::sync::Arc;+use crate::aggregate::utils::down_cast_any_ref;use crate::{AggregateExpr, PhysicalExpr};use arrow::datatypes::DataType;use arrow::datatypes::Field;@@ -91,3 +92,17 @@ impl AggregateExpr for Grouping {&self.name}}++impl PartialEq<dyn Any> for Grouping {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.nullable == x.nullable+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}diff --git a/datafusion/physical-expr/src/aggregate/median.rs b/datafusion/physical-expr/src/aggregate/median.rsindex e42e91c3a2..62114d624c 100644--- a/datafusion/physical-expr/src/aggregate/median.rs+++ b/datafusion/physical-expr/src/aggregate/median.rs@@ -17,6 +17,7 @@//! # Median+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};use arrow::array::{Array, ArrayRef, UInt32Array};@@ -90,6 +91,19 @@ impl AggregateExpr for Median {}}+impl PartialEq<dyn Any> for Median {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]/// The median accumulator accumulates the raw input values/// as `ScalarValue`sdiff --git a/datafusion/physical-expr/src/aggregate/min_max.rs b/datafusion/physical-expr/src/aggregate/min_max.rsindex 8a9d39a15f..4cda3779ba 100644--- a/datafusion/physical-expr/src/aggregate/min_max.rs+++ b/datafusion/physical-expr/src/aggregate/min_max.rs@@ -42,6 +42,7 @@ use datafusion_expr::Accumulator;use crate::aggregate::row_accumulator::{is_row_accumulator_support_dtype, RowAccumulator,};+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use arrow::array::Array;use arrow::array::Decimal128Array;@@ -147,6 +148,20 @@ impl AggregateExpr for Max {}}+impl PartialEq<dyn Any> for Max {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.nullable == x.nullable+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+// Statically-typed version of min/max(array) -> ScalarValue for string types.macro_rules! typed_min_max_batch_string {($VALUES:expr, $ARRAYTYPE:ident, $SCALAR:ident, $OP:ident) => {{@@ -737,6 +752,20 @@ impl AggregateExpr for Min {}}+impl PartialEq<dyn Any> for Min {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.nullable == x.nullable+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+/// An accumulator to compute the minimum value#[derive(Debug)]pub struct MinAccumulator {diff --git a/datafusion/physical-expr/src/aggregate/mod.rs b/datafusion/physical-expr/src/aggregate/mod.rsindex c42a5c03b3..691b708162 100644--- a/datafusion/physical-expr/src/aggregate/mod.rs+++ b/datafusion/physical-expr/src/aggregate/mod.rs@@ -56,7 +56,10 @@ pub(crate) mod variance;/// * knows how to create its accumulator/// * knows its accumulator's state's field/// * knows the expressions from whose its accumulator will receive values-pub trait AggregateExpr: Send + Sync + Debug {+///+/// The aggregate expressions implement this trait also need to implement the [PartialEq<dyn Any>]+/// This allows comparing the equality between the trait objects+pub trait AggregateExpr: Send + Sync + Debug + PartialEq<dyn Any> {/// Returns the aggregate expression as [`Any`](std::any::Any) so that it can be/// downcast to a specific implementation.fn as_any(&self) -> &dyn Any;diff --git a/datafusion/physical-expr/src/aggregate/stddev.rs b/datafusion/physical-expr/src/aggregate/stddev.rsindex dab84b14ab..e1b9b9ae23 100644--- a/datafusion/physical-expr/src/aggregate/stddev.rs+++ b/datafusion/physical-expr/src/aggregate/stddev.rs@@ -21,6 +21,7 @@ use std::any::Any;use std::sync::Arc;use crate::aggregate::stats::StatsType;+use crate::aggregate::utils::down_cast_any_ref;use crate::aggregate::variance::VarianceAccumulator;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};@@ -102,6 +103,15 @@ impl AggregateExpr for Stddev {}}+impl PartialEq<dyn Any> for Stddev {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| self.name == x.name && self.expr.eq(&x.expr))+ .unwrap_or(false)+ }+}+impl StddevPop {/// Create a new STDDEV aggregate functionpub fn new(@@ -160,6 +170,16 @@ impl AggregateExpr for StddevPop {&self.name}}++impl PartialEq<dyn Any> for StddevPop {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| self.name == x.name && self.expr.eq(&x.expr))+ .unwrap_or(false)+ }+}+/// An accumulator to compute the average#[derive(Debug)]pub struct StddevAccumulator {diff --git a/datafusion/physical-expr/src/aggregate/sum.rs b/datafusion/physical-expr/src/aggregate/sum.rsindex 0e302f332f..f8d4d303ea 100644--- a/datafusion/physical-expr/src/aggregate/sum.rs+++ b/datafusion/physical-expr/src/aggregate/sum.rs@@ -37,6 +37,7 @@ use datafusion_expr::Accumulator;use crate::aggregate::row_accumulator::{is_row_accumulator_support_dtype, RowAccumulator,};+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use arrow::array::Array;use arrow::array::Decimal128Array;@@ -153,6 +154,20 @@ impl AggregateExpr for Sum {}}+impl PartialEq<dyn Any> for Sum {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.nullable == x.nullable+ && self.expr.eq(&x.expr)+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]struct SumAccumulator {sum: ScalarValue,diff --git a/datafusion/physical-expr/src/aggregate/sum_distinct.rs b/datafusion/physical-expr/src/aggregate/sum_distinct.rsindex f1815d05a3..73f74df967 100644--- a/datafusion/physical-expr/src/aggregate/sum_distinct.rs+++ b/datafusion/physical-expr/src/aggregate/sum_distinct.rs@@ -25,6 +25,7 @@ use ahash::RandomState;use arrow::array::{Array, ArrayRef};use std::collections::HashSet;+use crate::aggregate::utils::down_cast_any_ref;use crate::{AggregateExpr, PhysicalExpr};use datafusion_common::ScalarValue;use datafusion_common::{DataFusionError, Result};@@ -87,6 +88,24 @@ impl AggregateExpr for DistinctSum {}}+impl PartialEq<dyn Any> for DistinctSum {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| {+ self.name == x.name+ && self.data_type == x.data_type+ && self.exprs.len() == x.exprs.len()+ && self+ .exprs+ .iter()+ .zip(x.exprs.iter())+ .all(|(this, other)| this.eq(other))+ })+ .unwrap_or(false)+ }+}+#[derive(Debug)]struct DistinctSumAccumulator {hash_values: HashSet<ScalarValue, RandomState>,diff --git a/datafusion/physical-expr/src/aggregate/utils.rs b/datafusion/physical-expr/src/aggregate/utils.rsindex 16fd8fd6c8..feabbd9cdc 100644--- a/datafusion/physical-expr/src/aggregate/utils.rs+++ b/datafusion/physical-expr/src/aggregate/utils.rs@@ -17,11 +17,14 @@//! Utilities used in aggregates+use crate::AggregateExpr;use arrow::array::ArrayRef;use arrow::datatypes::{MAX_DECIMAL_FOR_EACH_PRECISION, MIN_DECIMAL_FOR_EACH_PRECISION};use arrow_schema::DataType;use datafusion_common::{DataFusionError, Result, ScalarValue};use datafusion_expr::Accumulator;+use std::any::Any;+use std::sync::Arc;/// Convert scalar values from an accumulator into arrays.pub fn get_accum_scalar_values_as_arrays(@@ -79,3 +82,21 @@ pub fn calculate_result_decimal_for_avg())),}}++/// Downcast the [`Box<dyn AggregateExpr>`] or [`Arc<dyn AggregateExpr>`] and return+/// the inner trait object as [`Any`](std::any::Any) so that it can be downcast to a specific implementation.+/// This method is used when implementing the [`PartialEq<dyn Any>'] for aggregation expressions and allows+/// comparing the equality between the trait objects.+pub fn down_cast_any_ref(any: &dyn Any) -> &dyn Any {+ if any.is::<Arc<dyn AggregateExpr>>() {+ any.downcast_ref::<Arc<dyn AggregateExpr>>()+ .unwrap()+ .as_any()+ } else if any.is::<Box<dyn AggregateExpr>>() {+ any.downcast_ref::<Box<dyn AggregateExpr>>()+ .unwrap()+ .as_any()+ } else {+ any+ }+}diff --git a/datafusion/physical-expr/src/aggregate/variance.rs b/datafusion/physical-expr/src/aggregate/variance.rsindex 3aa1d9bf1c..a720dd833a 100644--- a/datafusion/physical-expr/src/aggregate/variance.rs+++ b/datafusion/physical-expr/src/aggregate/variance.rs@@ -21,6 +21,7 @@ use std::any::Any;use std::sync::Arc;use crate::aggregate::stats::StatsType;+use crate::aggregate::utils::down_cast_any_ref;use crate::expressions::format_state_name;use crate::{AggregateExpr, PhysicalExpr};use arrow::array::Float64Array;@@ -107,6 +108,15 @@ impl AggregateExpr for Variance {}}+impl PartialEq<dyn Any> for Variance {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| self.name == x.name && self.expr.eq(&x.expr))+ .unwrap_or(false)+ }+}+impl VariancePop {/// Create a new VAR_POP aggregate functionpub fn new(@@ -170,6 +180,15 @@ impl AggregateExpr for VariancePop {}}+impl PartialEq<dyn Any> for VariancePop {+ fn eq(&self, other: &dyn Any) -> bool {+ down_cast_any_ref(other)+ .downcast_ref::<Self>()+ .map(|x| self.name == x.name && self.expr.eq(&x.expr))+ .unwrap_or(false)+ }+}+/// An accumulator to compute variance/// The algrithm used is an online implementation and numerically stable. It is based on this paper:/// Welford, B. P. (1962). "Note on a method for calculating corrected sums of squares and products".diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.protoindex c4b3ac2114..4bbd5a0417 100644--- a/datafusion/proto/proto/datafusion.proto+++ b/datafusion/proto/proto/datafusion.proto@@ -1249,6 +1249,7 @@ enum AggregateMode {PARTIAL = 0;FINAL = 1;FINAL_PARTITIONED = 2;+ SINGLE = 3;}message WindowAggExecNode {diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rsindex 105591a000..9e49eb2f09 100644--- a/datafusion/proto/src/generated/pbjson.rs+++ b/datafusion/proto/src/generated/pbjson.rs@@ -530,6 +530,7 @@ impl serde::Serialize for AggregateMode {Self::Partial => "PARTIAL",Self::Final => "FINAL",Self::FinalPartitioned => "FINAL_PARTITIONED",+ Self::Single => "SINGLE",};serializer.serialize_str(variant)}@@ -544,6 +545,7 @@ impl<'de> serde::Deserialize<'de> for AggregateMode {"PARTIAL","FINAL","FINAL_PARTITIONED",+ "SINGLE",];struct GeneratedVisitor;@@ -589,6 +591,7 @@ impl<'de> serde::Deserialize<'de> for AggregateMode {"PARTIAL" => Ok(AggregateMode::Partial),"FINAL" => Ok(AggregateMode::Final),"FINAL_PARTITIONED" => Ok(AggregateMode::FinalPartitioned),+ "SINGLE" => Ok(AggregateMode::Single),_ => Err(serde::de::Error::unknown_variant(value, FIELDS)),}}diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rsindex ebdd14b2f3..54857f1414 100644--- a/datafusion/proto/src/generated/prost.rs+++ b/datafusion/proto/src/generated/prost.rs@@ -2658,6 +2658,7 @@ pub enum AggregateMode {Partial = 0,Final = 1,FinalPartitioned = 2,+ Single = 3,}impl AggregateMode {/// String value of the enum field names used in the ProtoBuf definition.@@ -2669,6 +2670,7 @@ impl AggregateMode {AggregateMode::Partial => "PARTIAL",AggregateMode::Final => "FINAL",AggregateMode::FinalPartitioned => "FINAL_PARTITIONED",+ AggregateMode::Single => "SINGLE",}}/// Creates an enum from field names used in the ProtoBuf definition.@@ -2677,6 +2679,7 @@ impl AggregateMode {"PARTIAL" => Some(Self::Partial),"FINAL" => Some(Self::Final),"FINAL_PARTITIONED" => Some(Self::FinalPartitioned),+ "SINGLE" => Some(Self::Single),_ => None,}}diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rsindex ff13bbfb8f..381073dec0 100644--- a/datafusion/proto/src/physical_plan/mod.rs+++ b/datafusion/proto/src/physical_plan/mod.rs@@ -357,6 +357,7 @@ impl AsExecutionPlan for PhysicalPlanNode {protobuf::AggregateMode::FinalPartitioned => {AggregateMode::FinalPartitioned}+ protobuf::AggregateMode::Single => AggregateMode::Single,};let num_expr = hash_agg.group_expr.len();@@ -903,6 +904,7 @@ impl AsExecutionPlan for PhysicalPlanNode {AggregateMode::FinalPartitioned => {protobuf::AggregateMode::FinalPartitioned}+ AggregateMode::Single => protobuf::AggregateMode::Single,};let input_schema = exec.input_schema();let input = protobuf::PhysicalPlanNode::try_from_physical_plan(