Apache DataFusion SQL Query Engine
Extract complex default impls from AggregateUDFImpl trait (#17391)
Piotr Findeisen8698d954e53d
diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rsindex b4ad838721..a6e5e36118 100644--- a/datafusion/expr/src/lib.rs+++ b/datafusion/expr/src/lib.rs@@ -105,8 +105,10 @@ pub use partition_evaluator::PartitionEvaluator;pub use sqlparser;pub use table_source::{TableProviderFilterPushDown, TableSource, TableType};pub use udaf::{- aggregate_doc_sections, AggregateUDF, AggregateUDFImpl, ReversedUDAF,- SetMonotonicity, StatisticsArgs,+ aggregate_doc_sections, udaf_default_display_name, udaf_default_human_display,+ udaf_default_return_field, udaf_default_schema_name,+ udaf_default_window_function_display_name, udaf_default_window_function_schema_name,+ AggregateUDF, AggregateUDFImpl, ReversedUDAF, SetMonotonicity, StatisticsArgs,};pub use udf::{scalar_doc_sections, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl,diff --git a/datafusion/expr/src/udaf.rs b/datafusion/expr/src/udaf.rsindex 9619d60a24..9b6e97bef9 100644--- a/datafusion/expr/src/udaf.rs+++ b/datafusion/expr/src/udaf.rs@@ -72,7 +72,7 @@ use crate::{Documentation, Signature};////// [the examples]: https://github.com/apache/datafusion/tree/main/datafusion-examples#single-process/// [aggregate function]: https://en.wikipedia.org/wiki/Aggregate_function-/// [`Accumulator`]: crate::Accumulator+/// [`Accumulator`]: Accumulator/// [`create_udaf`]: crate::expr_fn::create_udaf/// [`simple_udaf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/simple_udaf.rs/// [`advanced_udaf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/advanced_udaf.rs@@ -448,92 +448,14 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {////// Example of schema_name: count(DISTINCT column1) FILTER (WHERE column2 > 10) ORDER BY [..]fn schema_name(&self, params: &AggregateFunctionParams) -> Result<String> {- let AggregateFunctionParams {- args,- distinct,- filter,- order_by,- null_treatment,- } = params;-- // exclude the first function argument(= column) in ordered set aggregate function,- // because it is duplicated with the WITHIN GROUP clause in schema name.- let args = if self.is_ordered_set_aggregate() {- &args[1..]- } else {- &args[..]- };-- let mut schema_name = String::new();-- schema_name.write_fmt(format_args!(- "{}({}{})",- self.name(),- if *distinct { "DISTINCT " } else { "" },- schema_name_from_exprs_comma_separated_without_space(args)?- ))?;-- if let Some(null_treatment) = null_treatment {- schema_name.write_fmt(format_args!(" {null_treatment}"))?;- }-- if let Some(filter) = filter {- schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;- };-- if !order_by.is_empty() {- let clause = match self.is_ordered_set_aggregate() {- true => "WITHIN GROUP",- false => "ORDER BY",- };-- schema_name.write_fmt(format_args!(- " {} [{}]",- clause,- schema_name_from_sorts(order_by)?- ))?;- };-- Ok(schema_name)+ udaf_default_schema_name(self, params)}/// Returns a human readable expression.////// See [`Expr::human_display`] for details.fn human_display(&self, params: &AggregateFunctionParams) -> Result<String> {- let AggregateFunctionParams {- args,- distinct,- filter,- order_by,- null_treatment,- } = params;-- let mut schema_name = String::new();-- schema_name.write_fmt(format_args!(- "{}({}{})",- self.name(),- if *distinct { "DISTINCT " } else { "" },- ExprListDisplay::comma_separated(args.as_slice())- ))?;-- if let Some(null_treatment) = null_treatment {- schema_name.write_fmt(format_args!(" {null_treatment}"))?;- }-- if let Some(filter) = filter {- schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;- };-- if !order_by.is_empty() {- schema_name.write_fmt(format_args!(- " ORDER BY [{}]",- schema_name_from_sorts(order_by)?- ))?;- };-- Ok(schema_name)+ udaf_default_human_display(self, params)}/// Returns the name of the column this expression would create@@ -547,58 +469,7 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {&self,params: &WindowFunctionParams,) -> Result<String> {- let WindowFunctionParams {- args,- partition_by,- order_by,- window_frame,- filter,- null_treatment,- distinct,- } = params;-- let mut schema_name = String::new();-- // Inject DISTINCT into the schema name when requested- if *distinct {- schema_name.write_fmt(format_args!(- "{}(DISTINCT {})",- self.name(),- schema_name_from_exprs(args)?- ))?;- } else {- schema_name.write_fmt(format_args!(- "{}({})",- self.name(),- schema_name_from_exprs(args)?- ))?;- }-- if let Some(null_treatment) = null_treatment {- schema_name.write_fmt(format_args!(" {null_treatment}"))?;- }-- if let Some(filter) = filter {- schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;- }-- if !partition_by.is_empty() {- schema_name.write_fmt(format_args!(- " PARTITION BY [{}]",- schema_name_from_exprs(partition_by)?- ))?;- }-- if !order_by.is_empty() {- schema_name.write_fmt(format_args!(- " ORDER BY [{}]",- schema_name_from_sorts(order_by)?- ))?;- }-- schema_name.write_fmt(format_args!(" {window_frame}"))?;-- Ok(schema_name)+ udaf_default_window_function_schema_name(self, params)}/// Returns the user-defined display name of function, given the arguments@@ -608,41 +479,7 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {////// Defaults to `function_name([DISTINCT] column1, column2, ..) [null_treatment] [filter] [order_by [..]]`fn display_name(&self, params: &AggregateFunctionParams) -> Result<String> {- let AggregateFunctionParams {- args,- distinct,- filter,- order_by,- null_treatment,- } = params;-- let mut display_name = String::new();-- display_name.write_fmt(format_args!(- "{}({}{})",- self.name(),- if *distinct { "DISTINCT " } else { "" },- expr_vec_fmt!(args)- ))?;-- if let Some(nt) = null_treatment {- display_name.write_fmt(format_args!(" {nt}"))?;- }- if let Some(fe) = filter {- display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;- }- if !order_by.is_empty() {- display_name.write_fmt(format_args!(- " ORDER BY [{}]",- order_by- .iter()- .map(|o| format!("{o}"))- .collect::<Vec<String>>()- .join(", ")- ))?;- }-- Ok(display_name)+ udaf_default_display_name(self, params)}/// Returns the user-defined display name of function, given the arguments@@ -657,58 +494,7 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {&self,params: &WindowFunctionParams,) -> Result<String> {- let WindowFunctionParams {- args,- partition_by,- order_by,- window_frame,- filter,- null_treatment,- distinct,- } = params;-- let mut display_name = String::new();-- if *distinct {- display_name.write_fmt(format_args!(- "{}(DISTINCT {})",- self.name(),- expr_vec_fmt!(args)- ))?;- } else {- display_name.write_fmt(format_args!(- "{}({})",- self.name(),- expr_vec_fmt!(args)- ))?;- }-- if let Some(null_treatment) = null_treatment {- display_name.write_fmt(format_args!(" {null_treatment}"))?;- }-- if let Some(fe) = filter {- display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;- }-- if !partition_by.is_empty() {- display_name.write_fmt(format_args!(- " PARTITION BY [{}]",- expr_vec_fmt!(partition_by)- ))?;- }-- if !order_by.is_empty() {- display_name- .write_fmt(format_args!(" ORDER BY [{}]", expr_vec_fmt!(order_by)))?;- };-- display_name.write_fmt(format_args!(- " {} BETWEEN {} AND {}",- window_frame.units, window_frame.start_bound, window_frame.end_bound- ))?;-- Ok(display_name)+ udaf_default_window_function_display_name(self, params)}/// Returns the function's [`Signature`] for information about what input@@ -737,15 +523,7 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {/// their **types**./// 3. return types based on metadata within the fields of the inputsfn return_field(&self, arg_fields: &[FieldRef]) -> Result<FieldRef> {- let arg_types: Vec<_> =- arg_fields.iter().map(|f| f.data_type()).cloned().collect();- let data_type = self.return_type(&arg_types)?;-- Ok(Arc::new(Field::new(- self.name(),- data_type,- self.is_nullable(),- )))+ udaf_default_return_field(self, arg_fields)}/// Whether the aggregate function is nullable.@@ -831,7 +609,7 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {////// See [retract_batch] for more details.///- /// [retract_batch]: datafusion_expr_common::accumulator::Accumulator::retract_batch+ /// [retract_batch]: Accumulator::retract_batchfn create_sliding_accumulator(&self,args: AccumulatorArgs,@@ -888,7 +666,7 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {/// [None] if simplify is not defined or,////// Or, a closure with two arguments:- /// * 'aggregate_function': [crate::expr::AggregateFunction] for which simplified has been invoked+ /// * 'aggregate_function': [AggregateFunction] for which simplified has been invoked/// * 'info': [crate::simplify::SimplifyInfo]////// closure returns simplified [Expr] or an error.@@ -1001,6 +779,275 @@ impl PartialOrd for dyn AggregateUDFImpl {}}+/// Encapsulates default implementation of [`AggregateUDFImpl::schema_name`].+pub fn udaf_default_schema_name<F: AggregateUDFImpl + ?Sized>(+ func: &F,+ params: &AggregateFunctionParams,+) -> Result<String> {+ let AggregateFunctionParams {+ args,+ distinct,+ filter,+ order_by,+ null_treatment,+ } = params;++ // exclude the first function argument(= column) in ordered set aggregate function,+ // because it is duplicated with the WITHIN GROUP clause in schema name.+ let args = if func.is_ordered_set_aggregate() {+ &args[1..]+ } else {+ &args[..]+ };++ let mut schema_name = String::new();++ schema_name.write_fmt(format_args!(+ "{}({}{})",+ func.name(),+ if *distinct { "DISTINCT " } else { "" },+ schema_name_from_exprs_comma_separated_without_space(args)?+ ))?;++ if let Some(null_treatment) = null_treatment {+ schema_name.write_fmt(format_args!(" {null_treatment}"))?;+ }++ if let Some(filter) = filter {+ schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;+ };++ if !order_by.is_empty() {+ let clause = match func.is_ordered_set_aggregate() {+ true => "WITHIN GROUP",+ false => "ORDER BY",+ };++ schema_name.write_fmt(format_args!(+ " {} [{}]",+ clause,+ schema_name_from_sorts(order_by)?+ ))?;+ };++ Ok(schema_name)+}++/// Encapsulates default implementation of [`AggregateUDFImpl::human_display`].+pub fn udaf_default_human_display<F: AggregateUDFImpl + ?Sized>(+ func: &F,+ params: &AggregateFunctionParams,+) -> Result<String> {+ let AggregateFunctionParams {+ args,+ distinct,+ filter,+ order_by,+ null_treatment,+ } = params;++ let mut schema_name = String::new();++ schema_name.write_fmt(format_args!(+ "{}({}{})",+ func.name(),+ if *distinct { "DISTINCT " } else { "" },+ ExprListDisplay::comma_separated(args.as_slice())+ ))?;++ if let Some(null_treatment) = null_treatment {+ schema_name.write_fmt(format_args!(" {null_treatment}"))?;+ }++ if let Some(filter) = filter {+ schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;+ };++ if !order_by.is_empty() {+ schema_name.write_fmt(format_args!(+ " ORDER BY [{}]",+ schema_name_from_sorts(order_by)?+ ))?;+ };++ Ok(schema_name)+}++/// Encapsulates default implementation of [`AggregateUDFImpl::window_function_schema_name`].+pub fn udaf_default_window_function_schema_name<F: AggregateUDFImpl + ?Sized>(+ func: &F,+ params: &WindowFunctionParams,+) -> Result<String> {+ let WindowFunctionParams {+ args,+ partition_by,+ order_by,+ window_frame,+ filter,+ null_treatment,+ distinct,+ } = params;++ let mut schema_name = String::new();++ // Inject DISTINCT into the schema name when requested+ if *distinct {+ schema_name.write_fmt(format_args!(+ "{}(DISTINCT {})",+ func.name(),+ schema_name_from_exprs(args)?+ ))?;+ } else {+ schema_name.write_fmt(format_args!(+ "{}({})",+ func.name(),+ schema_name_from_exprs(args)?+ ))?;+ }++ if let Some(null_treatment) = null_treatment {+ schema_name.write_fmt(format_args!(" {null_treatment}"))?;+ }++ if let Some(filter) = filter {+ schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;+ }++ if !partition_by.is_empty() {+ schema_name.write_fmt(format_args!(+ " PARTITION BY [{}]",+ schema_name_from_exprs(partition_by)?+ ))?;+ }++ if !order_by.is_empty() {+ schema_name.write_fmt(format_args!(+ " ORDER BY [{}]",+ schema_name_from_sorts(order_by)?+ ))?;+ }++ schema_name.write_fmt(format_args!(" {window_frame}"))?;++ Ok(schema_name)+}++/// Encapsulates default implementation of [`AggregateUDFImpl::display_name`].+pub fn udaf_default_display_name<F: AggregateUDFImpl + ?Sized>(+ func: &F,+ params: &AggregateFunctionParams,+) -> Result<String> {+ let AggregateFunctionParams {+ args,+ distinct,+ filter,+ order_by,+ null_treatment,+ } = params;++ let mut display_name = String::new();++ display_name.write_fmt(format_args!(+ "{}({}{})",+ func.name(),+ if *distinct { "DISTINCT " } else { "" },+ expr_vec_fmt!(args)+ ))?;++ if let Some(nt) = null_treatment {+ display_name.write_fmt(format_args!(" {nt}"))?;+ }+ if let Some(fe) = filter {+ display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;+ }+ if !order_by.is_empty() {+ display_name.write_fmt(format_args!(+ " ORDER BY [{}]",+ order_by+ .iter()+ .map(|o| format!("{o}"))+ .collect::<Vec<String>>()+ .join(", ")+ ))?;+ }++ Ok(display_name)+}++/// Encapsulates default implementation of [`AggregateUDFImpl::window_function_display_name`].+pub fn udaf_default_window_function_display_name<F: AggregateUDFImpl + ?Sized>(+ func: &F,+ params: &WindowFunctionParams,+) -> Result<String> {+ let WindowFunctionParams {+ args,+ partition_by,+ order_by,+ window_frame,+ filter,+ null_treatment,+ distinct,+ } = params;++ let mut display_name = String::new();++ if *distinct {+ display_name.write_fmt(format_args!(+ "{}(DISTINCT {})",+ func.name(),+ expr_vec_fmt!(args)+ ))?;+ } else {+ display_name.write_fmt(format_args!(+ "{}({})",+ func.name(),+ expr_vec_fmt!(args)+ ))?;+ }++ if let Some(null_treatment) = null_treatment {+ display_name.write_fmt(format_args!(" {null_treatment}"))?;+ }++ if let Some(fe) = filter {+ display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;+ }++ if !partition_by.is_empty() {+ display_name.write_fmt(format_args!(+ " PARTITION BY [{}]",+ expr_vec_fmt!(partition_by)+ ))?;+ }++ if !order_by.is_empty() {+ display_name+ .write_fmt(format_args!(" ORDER BY [{}]", expr_vec_fmt!(order_by)))?;+ };++ display_name.write_fmt(format_args!(+ " {} BETWEEN {} AND {}",+ window_frame.units, window_frame.start_bound, window_frame.end_bound+ ))?;++ Ok(display_name)+}++/// Encapsulates default implementation of [`AggregateUDFImpl::return_field`].+pub fn udaf_default_return_field<F: AggregateUDFImpl + ?Sized>(+ func: &F,+ arg_fields: &[FieldRef],+) -> Result<FieldRef> {+ let arg_types: Vec<_> = arg_fields.iter().map(|f| f.data_type()).cloned().collect();+ let data_type = func.return_type(&arg_types)?;++ Ok(Arc::new(Field::new(+ func.name(),+ data_type,+ func.is_nullable(),+ )))+}+pub enum ReversedUDAF {/// The expression is the same as the original expression, like SUM, COUNTIdentical,