datafusion_expr/
udaf.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! [`AggregateUDF`]: User Defined Aggregate Functions
19
20use std::any::Any;
21use std::cmp::Ordering;
22use std::fmt::{self, Debug, Formatter, Write};
23use std::hash::{Hash, Hasher};
24use std::sync::Arc;
25use std::vec;
26
27use arrow::datatypes::{DataType, Field, FieldRef};
28
29use datafusion_common::{exec_err, not_impl_err, Result, ScalarValue, Statistics};
30use datafusion_expr_common::dyn_eq::{DynEq, DynHash};
31use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
32
33use crate::expr::{
34    schema_name_from_exprs, schema_name_from_exprs_comma_separated_without_space,
35    schema_name_from_sorts, AggregateFunction, AggregateFunctionParams, ExprListDisplay,
36    WindowFunctionParams,
37};
38use crate::function::{
39    AccumulatorArgs, AggregateFunctionSimplification, StateFieldsArgs,
40};
41use crate::groups_accumulator::GroupsAccumulator;
42use crate::udf_eq::UdfEq;
43use crate::utils::format_state_name;
44use crate::utils::AggregateOrderSensitivity;
45use crate::{expr_vec_fmt, Accumulator, Expr};
46use crate::{Documentation, Signature};
47
48/// Logical representation of a user-defined [aggregate function] (UDAF).
49///
50/// An aggregate function combines the values from multiple input rows
51/// into a single output "aggregate" (summary) row. It is different
52/// from a scalar function because it is stateful across batches. User
53/// defined aggregate functions can be used as normal SQL aggregate
54/// functions (`GROUP BY` clause) as well as window functions (`OVER`
55/// clause).
56///
57/// `AggregateUDF` provides DataFusion the information needed to plan and call
58/// aggregate functions, including name, type information, and a factory
59/// function to create an [`Accumulator`] instance, to perform the actual
60/// aggregation.
61///
62/// For more information, please see [the examples]:
63///
64/// 1. For simple use cases, use [`create_udaf`] (examples in [`simple_udaf.rs`]).
65///
66/// 2. For advanced use cases, use [`AggregateUDFImpl`] which provides full API
67///    access (examples in [`advanced_udaf.rs`]).
68///
69/// # API Note
70/// This is a separate struct from `AggregateUDFImpl` to maintain backwards
71/// compatibility with the older API.
72///
73/// [the examples]: https://github.com/apache/datafusion/tree/main/datafusion-examples#single-process
74/// [aggregate function]: https://en.wikipedia.org/wiki/Aggregate_function
75/// [`Accumulator`]: crate::Accumulator
76/// [`create_udaf`]: crate::expr_fn::create_udaf
77/// [`simple_udaf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/simple_udaf.rs
78/// [`advanced_udaf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/advanced_udaf.rs
79#[derive(Debug, Clone, PartialOrd)]
80pub struct AggregateUDF {
81    inner: Arc<dyn AggregateUDFImpl>,
82}
83
84impl PartialEq for AggregateUDF {
85    fn eq(&self, other: &Self) -> bool {
86        self.inner.dyn_eq(other.inner.as_any())
87    }
88}
89
90impl Eq for AggregateUDF {}
91
92impl Hash for AggregateUDF {
93    fn hash<H: Hasher>(&self, state: &mut H) {
94        self.inner.dyn_hash(state)
95    }
96}
97
98impl fmt::Display for AggregateUDF {
99    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
100        write!(f, "{}", self.name())
101    }
102}
103
104/// Arguments passed to [`AggregateUDFImpl::value_from_stats`]
105#[derive(Debug)]
106pub struct StatisticsArgs<'a> {
107    /// The statistics of the aggregate input
108    pub statistics: &'a Statistics,
109    /// The resolved return type of the aggregate function
110    pub return_type: &'a DataType,
111    /// Whether the aggregate function is distinct.
112    ///
113    /// ```sql
114    /// SELECT COUNT(DISTINCT column1) FROM t;
115    /// ```
116    pub is_distinct: bool,
117    /// The physical expression of arguments the aggregate function takes.
118    pub exprs: &'a [Arc<dyn PhysicalExpr>],
119}
120
121impl AggregateUDF {
122    /// Create a new `AggregateUDF` from a `[AggregateUDFImpl]` trait object
123    ///
124    /// Note this is the same as using the `From` impl (`AggregateUDF::from`)
125    pub fn new_from_impl<F>(fun: F) -> AggregateUDF
126    where
127        F: AggregateUDFImpl + 'static,
128    {
129        Self::new_from_shared_impl(Arc::new(fun))
130    }
131
132    /// Create a new `AggregateUDF` from a `[AggregateUDFImpl]` trait object
133    pub fn new_from_shared_impl(fun: Arc<dyn AggregateUDFImpl>) -> AggregateUDF {
134        Self { inner: fun }
135    }
136
137    /// Return the underlying [`AggregateUDFImpl`] trait object for this function
138    pub fn inner(&self) -> &Arc<dyn AggregateUDFImpl> {
139        &self.inner
140    }
141
142    /// Adds additional names that can be used to invoke this function, in
143    /// addition to `name`
144    ///
145    /// If you implement [`AggregateUDFImpl`] directly you should return aliases directly.
146    pub fn with_aliases(self, aliases: impl IntoIterator<Item = &'static str>) -> Self {
147        Self::new_from_impl(AliasedAggregateUDFImpl::new(
148            Arc::clone(&self.inner),
149            aliases,
150        ))
151    }
152
153    /// Creates an [`Expr`] that calls the aggregate function.
154    ///
155    /// This utility allows using the UDAF without requiring access to
156    /// the registry, such as with the DataFrame API.
157    pub fn call(&self, args: Vec<Expr>) -> Expr {
158        Expr::AggregateFunction(AggregateFunction::new_udf(
159            Arc::new(self.clone()),
160            args,
161            false,
162            None,
163            vec![],
164            None,
165        ))
166    }
167
168    /// Returns this function's name
169    ///
170    /// See [`AggregateUDFImpl::name`] for more details.
171    pub fn name(&self) -> &str {
172        self.inner.name()
173    }
174
175    /// Returns the aliases for this function.
176    pub fn aliases(&self) -> &[String] {
177        self.inner.aliases()
178    }
179
180    /// See [`AggregateUDFImpl::schema_name`] for more details.
181    pub fn schema_name(&self, params: &AggregateFunctionParams) -> Result<String> {
182        self.inner.schema_name(params)
183    }
184
185    /// Returns a human readable expression.
186    ///
187    /// See [`Expr::human_display`] for details.
188    pub fn human_display(&self, params: &AggregateFunctionParams) -> Result<String> {
189        self.inner.human_display(params)
190    }
191
192    pub fn window_function_schema_name(
193        &self,
194        params: &WindowFunctionParams,
195    ) -> Result<String> {
196        self.inner.window_function_schema_name(params)
197    }
198
199    /// See [`AggregateUDFImpl::display_name`] for more details.
200    pub fn display_name(&self, params: &AggregateFunctionParams) -> Result<String> {
201        self.inner.display_name(params)
202    }
203
204    pub fn window_function_display_name(
205        &self,
206        params: &WindowFunctionParams,
207    ) -> Result<String> {
208        self.inner.window_function_display_name(params)
209    }
210
211    pub fn is_nullable(&self) -> bool {
212        self.inner.is_nullable()
213    }
214
215    /// Returns this function's signature (what input types are accepted)
216    ///
217    /// See [`AggregateUDFImpl::signature`] for more details.
218    pub fn signature(&self) -> &Signature {
219        self.inner.signature()
220    }
221
222    /// Return the type of the function given its input types
223    ///
224    /// See [`AggregateUDFImpl::return_type`] for more details.
225    pub fn return_type(&self, args: &[DataType]) -> Result<DataType> {
226        self.inner.return_type(args)
227    }
228
229    /// Return the field of the function given its input fields
230    ///
231    /// See [`AggregateUDFImpl::return_field`] for more details.
232    pub fn return_field(&self, args: &[FieldRef]) -> Result<FieldRef> {
233        self.inner.return_field(args)
234    }
235
236    /// Return an accumulator the given aggregate, given its return datatype
237    pub fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
238        self.inner.accumulator(acc_args)
239    }
240
241    /// Return the fields used to store the intermediate state for this aggregator, given
242    /// the name of the aggregate, value type and ordering fields. See [`AggregateUDFImpl::state_fields`]
243    /// for more details.
244    ///
245    /// This is used to support multi-phase aggregations
246    pub fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
247        self.inner.state_fields(args)
248    }
249
250    /// See [`AggregateUDFImpl::groups_accumulator_supported`] for more details.
251    pub fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool {
252        self.inner.groups_accumulator_supported(args)
253    }
254
255    /// See [`AggregateUDFImpl::create_groups_accumulator`] for more details.
256    pub fn create_groups_accumulator(
257        &self,
258        args: AccumulatorArgs,
259    ) -> Result<Box<dyn GroupsAccumulator>> {
260        self.inner.create_groups_accumulator(args)
261    }
262
263    pub fn create_sliding_accumulator(
264        &self,
265        args: AccumulatorArgs,
266    ) -> Result<Box<dyn Accumulator>> {
267        self.inner.create_sliding_accumulator(args)
268    }
269
270    pub fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
271        self.inner.coerce_types(arg_types)
272    }
273
274    /// See [`AggregateUDFImpl::with_beneficial_ordering`] for more details.
275    pub fn with_beneficial_ordering(
276        self,
277        beneficial_ordering: bool,
278    ) -> Result<Option<AggregateUDF>> {
279        self.inner
280            .with_beneficial_ordering(beneficial_ordering)
281            .map(|updated_udf| updated_udf.map(|udf| Self { inner: udf }))
282    }
283
284    /// Gets the order sensitivity of the UDF. See [`AggregateOrderSensitivity`]
285    /// for possible options.
286    pub fn order_sensitivity(&self) -> AggregateOrderSensitivity {
287        self.inner.order_sensitivity()
288    }
289
290    /// Reserves the `AggregateUDF` (e.g. returns the `AggregateUDF` that will
291    /// generate same result with this `AggregateUDF` when iterated in reverse
292    /// order, and `None` if there is no such `AggregateUDF`).
293    pub fn reverse_udf(&self) -> ReversedUDAF {
294        self.inner.reverse_expr()
295    }
296
297    /// Do the function rewrite
298    ///
299    /// See [`AggregateUDFImpl::simplify`] for more details.
300    pub fn simplify(&self) -> Option<AggregateFunctionSimplification> {
301        self.inner.simplify()
302    }
303
304    /// Returns true if the function is max, false if the function is min
305    /// None in all other cases, used in certain optimizations for
306    /// or aggregate
307    pub fn is_descending(&self) -> Option<bool> {
308        self.inner.is_descending()
309    }
310
311    /// Return the value of this aggregate function if it can be determined
312    /// entirely from statistics and arguments.
313    ///
314    /// See [`AggregateUDFImpl::value_from_stats`] for more details.
315    pub fn value_from_stats(
316        &self,
317        statistics_args: &StatisticsArgs,
318    ) -> Option<ScalarValue> {
319        self.inner.value_from_stats(statistics_args)
320    }
321
322    /// See [`AggregateUDFImpl::default_value`] for more details.
323    pub fn default_value(&self, data_type: &DataType) -> Result<ScalarValue> {
324        self.inner.default_value(data_type)
325    }
326
327    /// See [`AggregateUDFImpl::supports_null_handling_clause`] for more details.
328    pub fn supports_null_handling_clause(&self) -> bool {
329        self.inner.supports_null_handling_clause()
330    }
331
332    /// See [`AggregateUDFImpl::is_ordered_set_aggregate`] for more details.
333    pub fn is_ordered_set_aggregate(&self) -> bool {
334        self.inner.is_ordered_set_aggregate()
335    }
336
337    /// Returns the documentation for this Aggregate UDF.
338    ///
339    /// Documentation can be accessed programmatically as well as
340    /// generating publicly facing documentation.
341    pub fn documentation(&self) -> Option<&Documentation> {
342        self.inner.documentation()
343    }
344}
345
346impl<F> From<F> for AggregateUDF
347where
348    F: AggregateUDFImpl + Send + Sync + 'static,
349{
350    fn from(fun: F) -> Self {
351        Self::new_from_impl(fun)
352    }
353}
354
355/// Trait for implementing [`AggregateUDF`].
356///
357/// This trait exposes the full API for implementing user defined aggregate functions and
358/// can be used to implement any function.
359///
360/// See [`advanced_udaf.rs`] for a full example with complete implementation and
361/// [`AggregateUDF`] for other available options.
362///
363/// [`advanced_udaf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/advanced_udaf.rs
364///
365/// # Basic Example
366/// ```
367/// # use std::any::Any;
368/// # use std::sync::{Arc, LazyLock};
369/// # use arrow::datatypes::{DataType, FieldRef};
370/// # use datafusion_common::{DataFusionError, plan_err, Result};
371/// # use datafusion_expr::{col, ColumnarValue, Signature, Volatility, Expr, Documentation};
372/// # use datafusion_expr::{AggregateUDFImpl, AggregateUDF, Accumulator, function::{AccumulatorArgs, StateFieldsArgs}};
373/// # use datafusion_expr::window_doc_sections::DOC_SECTION_AGGREGATE;
374/// # use arrow::datatypes::Schema;
375/// # use arrow::datatypes::Field;
376///
377/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
378/// struct GeoMeanUdf {
379///   signature: Signature,
380/// }
381///
382/// impl GeoMeanUdf {
383///   fn new() -> Self {
384///     Self {
385///       signature: Signature::uniform(1, vec![DataType::Float64], Volatility::Immutable),
386///      }
387///   }
388/// }
389///
390/// static DOCUMENTATION: LazyLock<Documentation> = LazyLock::new(|| {
391///         Documentation::builder(DOC_SECTION_AGGREGATE, "calculates a geometric mean", "geo_mean(2.0)")
392///             .with_argument("arg1", "The Float64 number for the geometric mean")
393///             .build()
394///     });
395///
396/// fn get_doc() -> &'static Documentation {
397///     &DOCUMENTATION
398/// }
399///
400/// /// Implement the AggregateUDFImpl trait for GeoMeanUdf
401/// impl AggregateUDFImpl for GeoMeanUdf {
402///    fn as_any(&self) -> &dyn Any { self }
403///    fn name(&self) -> &str { "geo_mean" }
404///    fn signature(&self) -> &Signature { &self.signature }
405///    fn return_type(&self, args: &[DataType]) -> Result<DataType> {
406///      if !matches!(args.get(0), Some(&DataType::Float64)) {
407///        return plan_err!("geo_mean only accepts Float64 arguments");
408///      }
409///      Ok(DataType::Float64)
410///    }
411///    // This is the accumulator factory; DataFusion uses it to create new accumulators.
412///    fn accumulator(&self, _acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { unimplemented!() }
413///    fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
414///        Ok(vec![
415///             Arc::new(args.return_field.as_ref().clone().with_name("value")),
416///             Arc::new(Field::new("ordering", DataType::UInt32, true))
417///        ])
418///    }
419///    fn documentation(&self) -> Option<&Documentation> {
420///        Some(get_doc())
421///    }
422/// }
423///
424/// // Create a new AggregateUDF from the implementation
425/// let geometric_mean = AggregateUDF::from(GeoMeanUdf::new());
426///
427/// // Call the function `geo_mean(col)`
428/// let expr = geometric_mean.call(vec![col("a")]);
429/// ```
430pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync {
431    /// Returns this object as an [`Any`] trait object
432    fn as_any(&self) -> &dyn Any;
433
434    /// Returns this function's name
435    fn name(&self) -> &str;
436
437    /// Returns any aliases (alternate names) for this function.
438    ///
439    /// Note: `aliases` should only include names other than [`Self::name`].
440    /// Defaults to `[]` (no aliases)
441    fn aliases(&self) -> &[String] {
442        &[]
443    }
444
445    /// Returns the name of the column this expression would create
446    ///
447    /// See [`Expr::schema_name`] for details
448    ///
449    /// Example of schema_name: count(DISTINCT column1) FILTER (WHERE column2 > 10) ORDER BY [..]
450    fn schema_name(&self, params: &AggregateFunctionParams) -> Result<String> {
451        let AggregateFunctionParams {
452            args,
453            distinct,
454            filter,
455            order_by,
456            null_treatment,
457        } = params;
458
459        // exclude the first function argument(= column) in ordered set aggregate function,
460        // because it is duplicated with the WITHIN GROUP clause in schema name.
461        let args = if self.is_ordered_set_aggregate() {
462            &args[1..]
463        } else {
464            &args[..]
465        };
466
467        let mut schema_name = String::new();
468
469        schema_name.write_fmt(format_args!(
470            "{}({}{})",
471            self.name(),
472            if *distinct { "DISTINCT " } else { "" },
473            schema_name_from_exprs_comma_separated_without_space(args)?
474        ))?;
475
476        if let Some(null_treatment) = null_treatment {
477            schema_name.write_fmt(format_args!(" {null_treatment}"))?;
478        }
479
480        if let Some(filter) = filter {
481            schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;
482        };
483
484        if !order_by.is_empty() {
485            let clause = match self.is_ordered_set_aggregate() {
486                true => "WITHIN GROUP",
487                false => "ORDER BY",
488            };
489
490            schema_name.write_fmt(format_args!(
491                " {} [{}]",
492                clause,
493                schema_name_from_sorts(order_by)?
494            ))?;
495        };
496
497        Ok(schema_name)
498    }
499
500    /// Returns a human readable expression.
501    ///
502    /// See [`Expr::human_display`] for details.
503    fn human_display(&self, params: &AggregateFunctionParams) -> Result<String> {
504        let AggregateFunctionParams {
505            args,
506            distinct,
507            filter,
508            order_by,
509            null_treatment,
510        } = params;
511
512        let mut schema_name = String::new();
513
514        schema_name.write_fmt(format_args!(
515            "{}({}{})",
516            self.name(),
517            if *distinct { "DISTINCT " } else { "" },
518            ExprListDisplay::comma_separated(args.as_slice())
519        ))?;
520
521        if let Some(null_treatment) = null_treatment {
522            schema_name.write_fmt(format_args!(" {null_treatment}"))?;
523        }
524
525        if let Some(filter) = filter {
526            schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;
527        };
528
529        if !order_by.is_empty() {
530            schema_name.write_fmt(format_args!(
531                " ORDER BY [{}]",
532                schema_name_from_sorts(order_by)?
533            ))?;
534        };
535
536        Ok(schema_name)
537    }
538
539    /// Returns the name of the column this expression would create
540    ///
541    /// See [`Expr::schema_name`] for details
542    ///
543    /// Different from `schema_name` in that it is used for window aggregate function
544    ///
545    /// Example of schema_name: count(DISTINCT column1) FILTER (WHERE column2 > 10) [PARTITION BY [..]] [ORDER BY [..]]
546    fn window_function_schema_name(
547        &self,
548        params: &WindowFunctionParams,
549    ) -> Result<String> {
550        let WindowFunctionParams {
551            args,
552            partition_by,
553            order_by,
554            window_frame,
555            filter,
556            null_treatment,
557            distinct,
558        } = params;
559
560        let mut schema_name = String::new();
561
562        // Inject DISTINCT into the schema name when requested
563        if *distinct {
564            schema_name.write_fmt(format_args!(
565                "{}(DISTINCT {})",
566                self.name(),
567                schema_name_from_exprs(args)?
568            ))?;
569        } else {
570            schema_name.write_fmt(format_args!(
571                "{}({})",
572                self.name(),
573                schema_name_from_exprs(args)?
574            ))?;
575        }
576
577        if let Some(null_treatment) = null_treatment {
578            schema_name.write_fmt(format_args!(" {null_treatment}"))?;
579        }
580
581        if let Some(filter) = filter {
582            schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;
583        }
584
585        if !partition_by.is_empty() {
586            schema_name.write_fmt(format_args!(
587                " PARTITION BY [{}]",
588                schema_name_from_exprs(partition_by)?
589            ))?;
590        }
591
592        if !order_by.is_empty() {
593            schema_name.write_fmt(format_args!(
594                " ORDER BY [{}]",
595                schema_name_from_sorts(order_by)?
596            ))?;
597        }
598
599        schema_name.write_fmt(format_args!(" {window_frame}"))?;
600
601        Ok(schema_name)
602    }
603
604    /// Returns the user-defined display name of function, given the arguments
605    ///
606    /// This can be used to customize the output column name generated by this
607    /// function.
608    ///
609    /// Defaults to `function_name([DISTINCT] column1, column2, ..) [null_treatment] [filter] [order_by [..]]`
610    fn display_name(&self, params: &AggregateFunctionParams) -> Result<String> {
611        let AggregateFunctionParams {
612            args,
613            distinct,
614            filter,
615            order_by,
616            null_treatment,
617        } = params;
618
619        let mut display_name = String::new();
620
621        display_name.write_fmt(format_args!(
622            "{}({}{})",
623            self.name(),
624            if *distinct { "DISTINCT " } else { "" },
625            expr_vec_fmt!(args)
626        ))?;
627
628        if let Some(nt) = null_treatment {
629            display_name.write_fmt(format_args!(" {nt}"))?;
630        }
631        if let Some(fe) = filter {
632            display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;
633        }
634        if !order_by.is_empty() {
635            display_name.write_fmt(format_args!(
636                " ORDER BY [{}]",
637                order_by
638                    .iter()
639                    .map(|o| format!("{o}"))
640                    .collect::<Vec<String>>()
641                    .join(", ")
642            ))?;
643        }
644
645        Ok(display_name)
646    }
647
648    /// Returns the user-defined display name of function, given the arguments
649    ///
650    /// This can be used to customize the output column name generated by this
651    /// function.
652    ///
653    /// Different from `display_name` in that it is used for window aggregate function
654    ///
655    /// Defaults to `function_name([DISTINCT] column1, column2, ..) [null_treatment] [partition by [..]] [order_by [..]]`
656    fn window_function_display_name(
657        &self,
658        params: &WindowFunctionParams,
659    ) -> Result<String> {
660        let WindowFunctionParams {
661            args,
662            partition_by,
663            order_by,
664            window_frame,
665            filter,
666            null_treatment,
667            distinct,
668        } = params;
669
670        let mut display_name = String::new();
671
672        if *distinct {
673            display_name.write_fmt(format_args!(
674                "{}(DISTINCT {})",
675                self.name(),
676                expr_vec_fmt!(args)
677            ))?;
678        } else {
679            display_name.write_fmt(format_args!(
680                "{}({})",
681                self.name(),
682                expr_vec_fmt!(args)
683            ))?;
684        }
685
686        if let Some(null_treatment) = null_treatment {
687            display_name.write_fmt(format_args!(" {null_treatment}"))?;
688        }
689
690        if let Some(fe) = filter {
691            display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;
692        }
693
694        if !partition_by.is_empty() {
695            display_name.write_fmt(format_args!(
696                " PARTITION BY [{}]",
697                expr_vec_fmt!(partition_by)
698            ))?;
699        }
700
701        if !order_by.is_empty() {
702            display_name
703                .write_fmt(format_args!(" ORDER BY [{}]", expr_vec_fmt!(order_by)))?;
704        };
705
706        display_name.write_fmt(format_args!(
707            " {} BETWEEN {} AND {}",
708            window_frame.units, window_frame.start_bound, window_frame.end_bound
709        ))?;
710
711        Ok(display_name)
712    }
713
714    /// Returns the function's [`Signature`] for information about what input
715    /// types are accepted and the function's Volatility.
716    fn signature(&self) -> &Signature;
717
718    /// What [`DataType`] will be returned by this function, given the types of
719    /// the arguments
720    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType>;
721
722    /// What type will be returned by this function, given the arguments?
723    ///
724    /// By default, this function calls [`Self::return_type`] with the
725    /// types of each argument.
726    ///
727    /// # Notes
728    ///
729    /// Most UDFs should implement [`Self::return_type`] and not this
730    /// function as the output type for most functions only depends on the types
731    /// of their inputs (e.g. `sum(f64)` is always `f64`).
732    ///
733    /// This function can be used for more advanced cases such as:
734    ///
735    /// 1. specifying nullability
736    /// 2. return types based on the **values** of the arguments (rather than
737    ///    their **types**.
738    /// 3. return types based on metadata within the fields of the inputs
739    fn return_field(&self, arg_fields: &[FieldRef]) -> Result<FieldRef> {
740        let arg_types: Vec<_> =
741            arg_fields.iter().map(|f| f.data_type()).cloned().collect();
742        let data_type = self.return_type(&arg_types)?;
743
744        Ok(Arc::new(Field::new(
745            self.name(),
746            data_type,
747            self.is_nullable(),
748        )))
749    }
750
751    /// Whether the aggregate function is nullable.
752    ///
753    /// Nullable means that the function could return `null` for any inputs.
754    /// For example, aggregate functions like `COUNT` always return a non null value
755    /// but others like `MIN` will return `NULL` if there is nullable input.
756    /// Note that if the function is declared as *not* nullable, make sure the [`AggregateUDFImpl::default_value`] is `non-null`
757    fn is_nullable(&self) -> bool {
758        true
759    }
760
761    /// Return a new [`Accumulator`] that aggregates values for a specific
762    /// group during query execution.
763    ///
764    /// acc_args: [`AccumulatorArgs`] contains information about how the
765    /// aggregate function was called.
766    fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>>;
767
768    /// Return the fields used to store the intermediate state of this accumulator.
769    ///
770    /// See [`Accumulator::state`] for background information.
771    ///
772    /// args:  [`StateFieldsArgs`] contains arguments passed to the
773    /// aggregate function's accumulator.
774    ///
775    /// # Notes:
776    ///
777    /// The default implementation returns a single state field named `name`
778    /// with the same type as `value_type`. This is suitable for aggregates such
779    /// as `SUM` or `MIN` where partial state can be combined by applying the
780    /// same aggregate.
781    ///
782    /// For aggregates such as `AVG` where the partial state is more complex
783    /// (e.g. a COUNT and a SUM), this method is used to define the additional
784    /// fields.
785    ///
786    /// The name of the fields must be unique within the query and thus should
787    /// be derived from `name`. See [`format_state_name`] for a utility function
788    /// to generate a unique name.
789    fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
790        let fields = vec![args
791            .return_field
792            .as_ref()
793            .clone()
794            .with_name(format_state_name(args.name, "value"))];
795
796        Ok(fields
797            .into_iter()
798            .map(Arc::new)
799            .chain(args.ordering_fields.to_vec())
800            .collect())
801    }
802
803    /// If the aggregate expression has a specialized
804    /// [`GroupsAccumulator`] implementation. If this returns true,
805    /// `[Self::create_groups_accumulator]` will be called.
806    ///
807    /// # Notes
808    ///
809    /// Even if this function returns true, DataFusion will still use
810    /// [`Self::accumulator`] for certain queries, such as when this aggregate is
811    /// used as a window function or when there no GROUP BY columns in the
812    /// query.
813    fn groups_accumulator_supported(&self, _args: AccumulatorArgs) -> bool {
814        false
815    }
816
817    /// Return a specialized [`GroupsAccumulator`] that manages state
818    /// for all groups.
819    ///
820    /// For maximum performance, a [`GroupsAccumulator`] should be
821    /// implemented in addition to [`Accumulator`].
822    fn create_groups_accumulator(
823        &self,
824        _args: AccumulatorArgs,
825    ) -> Result<Box<dyn GroupsAccumulator>> {
826        not_impl_err!("GroupsAccumulator hasn't been implemented for {self:?} yet")
827    }
828
829    /// Sliding accumulator is an alternative accumulator that can be used for
830    /// window functions. It has retract method to revert the previous update.
831    ///
832    /// See [retract_batch] for more details.
833    ///
834    /// [retract_batch]: datafusion_expr_common::accumulator::Accumulator::retract_batch
835    fn create_sliding_accumulator(
836        &self,
837        args: AccumulatorArgs,
838    ) -> Result<Box<dyn Accumulator>> {
839        self.accumulator(args)
840    }
841
842    /// Sets the indicator whether ordering requirements of the AggregateUDFImpl is
843    /// satisfied by its input. If this is not the case, UDFs with order
844    /// sensitivity `AggregateOrderSensitivity::Beneficial` can still produce
845    /// the correct result with possibly more work internally.
846    ///
847    /// # Returns
848    ///
849    /// Returns `Ok(Some(updated_udf))` if the process completes successfully.
850    /// If the expression can benefit from existing input ordering, but does
851    /// not implement the method, returns an error. Order insensitive and hard
852    /// requirement aggregators return `Ok(None)`.
853    fn with_beneficial_ordering(
854        self: Arc<Self>,
855        _beneficial_ordering: bool,
856    ) -> Result<Option<Arc<dyn AggregateUDFImpl>>> {
857        if self.order_sensitivity().is_beneficial() {
858            return exec_err!(
859                "Should implement with satisfied for aggregator :{:?}",
860                self.name()
861            );
862        }
863        Ok(None)
864    }
865
866    /// Gets the order sensitivity of the UDF. See [`AggregateOrderSensitivity`]
867    /// for possible options.
868    fn order_sensitivity(&self) -> AggregateOrderSensitivity {
869        // We have hard ordering requirements by default, meaning that order
870        // sensitive UDFs need their input orderings to satisfy their ordering
871        // requirements to generate correct results.
872        AggregateOrderSensitivity::HardRequirement
873    }
874
875    /// Optionally apply per-UDaF simplification / rewrite rules.
876    ///
877    /// This can be used to apply function specific simplification rules during
878    /// optimization (e.g. `arrow_cast` --> `Expr::Cast`). The default
879    /// implementation does nothing.
880    ///
881    /// Note that DataFusion handles simplifying arguments and  "constant
882    /// folding" (replacing a function call with constant arguments such as
883    /// `my_add(1,2) --> 3` ). Thus, there is no need to implement such
884    /// optimizations manually for specific UDFs.
885    ///
886    /// # Returns
887    ///
888    /// [None] if simplify is not defined or,
889    ///
890    /// Or, a closure with two arguments:
891    /// * 'aggregate_function': [crate::expr::AggregateFunction] for which simplified has been invoked
892    /// * 'info': [crate::simplify::SimplifyInfo]
893    ///
894    /// closure returns simplified [Expr] or an error.
895    ///
896    fn simplify(&self) -> Option<AggregateFunctionSimplification> {
897        None
898    }
899
900    /// Returns the reverse expression of the aggregate function.
901    fn reverse_expr(&self) -> ReversedUDAF {
902        ReversedUDAF::NotSupported
903    }
904
905    /// Coerce arguments of a function call to types that the function can evaluate.
906    ///
907    /// This function is only called if [`AggregateUDFImpl::signature`] returns [`crate::TypeSignature::UserDefined`]. Most
908    /// UDAFs should return one of the other variants of `TypeSignature` which handle common
909    /// cases
910    ///
911    /// See the [type coercion module](crate::type_coercion)
912    /// documentation for more details on type coercion
913    ///
914    /// For example, if your function requires a floating point arguments, but the user calls
915    /// it like `my_func(1::int)` (aka with `1` as an integer), coerce_types could return `[DataType::Float64]`
916    /// to ensure the argument was cast to `1::double`
917    ///
918    /// # Parameters
919    /// * `arg_types`: The argument types of the arguments  this function with
920    ///
921    /// # Return value
922    /// A Vec the same length as `arg_types`. DataFusion will `CAST` the function call
923    /// arguments to these specific types.
924    fn coerce_types(&self, _arg_types: &[DataType]) -> Result<Vec<DataType>> {
925        not_impl_err!("Function {} does not implement coerce_types", self.name())
926    }
927
928    /// If this function is max, return true
929    /// If the function is min, return false
930    /// Otherwise return None (the default)
931    ///
932    ///
933    /// Note: this is used to use special aggregate implementations in certain conditions
934    fn is_descending(&self) -> Option<bool> {
935        None
936    }
937
938    /// Return the value of this aggregate function if it can be determined
939    /// entirely from statistics and arguments.
940    ///
941    /// Using a [`ScalarValue`] rather than a runtime computation can significantly
942    /// improving query performance.
943    ///
944    /// For example, if the minimum value of column `x` is known to be `42` from
945    /// statistics, then the aggregate `MIN(x)` should return `Some(ScalarValue(42))`
946    fn value_from_stats(&self, _statistics_args: &StatisticsArgs) -> Option<ScalarValue> {
947        None
948    }
949
950    /// Returns default value of the function given the input is all `null`.
951    ///
952    /// Most of the aggregate function return Null if input is Null,
953    /// while `count` returns 0 if input is Null
954    fn default_value(&self, data_type: &DataType) -> Result<ScalarValue> {
955        ScalarValue::try_from(data_type)
956    }
957
958    /// If this function supports `[IGNORE NULLS | RESPECT NULLS]` clause, return true
959    /// If the function does not, return false
960    fn supports_null_handling_clause(&self) -> bool {
961        true
962    }
963
964    /// If this function is ordered-set aggregate function, return true
965    /// If the function is not, return false
966    fn is_ordered_set_aggregate(&self) -> bool {
967        false
968    }
969
970    /// Returns the documentation for this Aggregate UDF.
971    ///
972    /// Documentation can be accessed programmatically as well as
973    /// generating publicly facing documentation.
974    fn documentation(&self) -> Option<&Documentation> {
975        None
976    }
977
978    /// Indicates whether the aggregation function is monotonic as a set
979    /// function. See [`SetMonotonicity`] for details.
980    fn set_monotonicity(&self, _data_type: &DataType) -> SetMonotonicity {
981        SetMonotonicity::NotMonotonic
982    }
983}
984
985impl PartialEq for dyn AggregateUDFImpl {
986    fn eq(&self, other: &Self) -> bool {
987        self.dyn_eq(other.as_any())
988    }
989}
990
991// TODO (https://github.com/apache/datafusion/issues/17064) PartialOrd is not consistent with PartialEq for `dyn AggregateUDFImpl` and it should be
992// Manual implementation of `PartialOrd`
993// There might be some wackiness with it, but this is based on the impl of eq for AggregateUDFImpl
994// https://users.rust-lang.org/t/how-to-compare-two-trait-objects-for-equality/88063/5
995impl PartialOrd for dyn AggregateUDFImpl {
996    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
997        match self.name().partial_cmp(other.name()) {
998            Some(Ordering::Equal) => self.signature().partial_cmp(other.signature()),
999            cmp => cmp,
1000        }
1001    }
1002}
1003
1004pub enum ReversedUDAF {
1005    /// The expression is the same as the original expression, like SUM, COUNT
1006    Identical,
1007    /// The expression does not support reverse calculation
1008    NotSupported,
1009    /// The expression is different from the original expression
1010    Reversed(Arc<AggregateUDF>),
1011}
1012
1013/// AggregateUDF that adds an alias to the underlying function. It is better to
1014/// implement [`AggregateUDFImpl`], which supports aliases, directly if possible.
1015#[derive(Debug, PartialEq, Eq, Hash)]
1016struct AliasedAggregateUDFImpl {
1017    inner: UdfEq<Arc<dyn AggregateUDFImpl>>,
1018    aliases: Vec<String>,
1019}
1020
1021impl AliasedAggregateUDFImpl {
1022    pub fn new(
1023        inner: Arc<dyn AggregateUDFImpl>,
1024        new_aliases: impl IntoIterator<Item = &'static str>,
1025    ) -> Self {
1026        let mut aliases = inner.aliases().to_vec();
1027        aliases.extend(new_aliases.into_iter().map(|s| s.to_string()));
1028
1029        Self {
1030            inner: inner.into(),
1031            aliases,
1032        }
1033    }
1034}
1035
1036#[warn(clippy::missing_trait_methods)] // Delegates, so it should implement every single trait method
1037impl AggregateUDFImpl for AliasedAggregateUDFImpl {
1038    fn as_any(&self) -> &dyn Any {
1039        self
1040    }
1041
1042    fn name(&self) -> &str {
1043        self.inner.name()
1044    }
1045
1046    fn signature(&self) -> &Signature {
1047        self.inner.signature()
1048    }
1049
1050    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
1051        self.inner.return_type(arg_types)
1052    }
1053
1054    fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
1055        self.inner.accumulator(acc_args)
1056    }
1057
1058    fn aliases(&self) -> &[String] {
1059        &self.aliases
1060    }
1061
1062    fn schema_name(&self, params: &AggregateFunctionParams) -> Result<String> {
1063        self.inner.schema_name(params)
1064    }
1065
1066    fn human_display(&self, params: &AggregateFunctionParams) -> Result<String> {
1067        self.inner.human_display(params)
1068    }
1069
1070    fn window_function_schema_name(
1071        &self,
1072        params: &WindowFunctionParams,
1073    ) -> Result<String> {
1074        self.inner.window_function_schema_name(params)
1075    }
1076
1077    fn display_name(&self, params: &AggregateFunctionParams) -> Result<String> {
1078        self.inner.display_name(params)
1079    }
1080
1081    fn window_function_display_name(
1082        &self,
1083        params: &WindowFunctionParams,
1084    ) -> Result<String> {
1085        self.inner.window_function_display_name(params)
1086    }
1087
1088    fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
1089        self.inner.state_fields(args)
1090    }
1091
1092    fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool {
1093        self.inner.groups_accumulator_supported(args)
1094    }
1095
1096    fn create_groups_accumulator(
1097        &self,
1098        args: AccumulatorArgs,
1099    ) -> Result<Box<dyn GroupsAccumulator>> {
1100        self.inner.create_groups_accumulator(args)
1101    }
1102
1103    fn create_sliding_accumulator(
1104        &self,
1105        args: AccumulatorArgs,
1106    ) -> Result<Box<dyn Accumulator>> {
1107        self.inner.accumulator(args)
1108    }
1109
1110    fn with_beneficial_ordering(
1111        self: Arc<Self>,
1112        beneficial_ordering: bool,
1113    ) -> Result<Option<Arc<dyn AggregateUDFImpl>>> {
1114        Arc::clone(&self.inner)
1115            .with_beneficial_ordering(beneficial_ordering)
1116            .map(|udf| {
1117                udf.map(|udf| {
1118                    Arc::new(AliasedAggregateUDFImpl {
1119                        inner: udf.into(),
1120                        aliases: self.aliases.clone(),
1121                    }) as Arc<dyn AggregateUDFImpl>
1122                })
1123            })
1124    }
1125
1126    fn order_sensitivity(&self) -> AggregateOrderSensitivity {
1127        self.inner.order_sensitivity()
1128    }
1129
1130    fn simplify(&self) -> Option<AggregateFunctionSimplification> {
1131        self.inner.simplify()
1132    }
1133
1134    fn reverse_expr(&self) -> ReversedUDAF {
1135        self.inner.reverse_expr()
1136    }
1137
1138    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
1139        self.inner.coerce_types(arg_types)
1140    }
1141
1142    fn return_field(&self, arg_fields: &[FieldRef]) -> Result<FieldRef> {
1143        self.inner.return_field(arg_fields)
1144    }
1145
1146    fn is_nullable(&self) -> bool {
1147        self.inner.is_nullable()
1148    }
1149
1150    fn is_descending(&self) -> Option<bool> {
1151        self.inner.is_descending()
1152    }
1153
1154    fn value_from_stats(&self, statistics_args: &StatisticsArgs) -> Option<ScalarValue> {
1155        self.inner.value_from_stats(statistics_args)
1156    }
1157
1158    fn default_value(&self, data_type: &DataType) -> Result<ScalarValue> {
1159        self.inner.default_value(data_type)
1160    }
1161
1162    fn supports_null_handling_clause(&self) -> bool {
1163        self.inner.supports_null_handling_clause()
1164    }
1165
1166    fn is_ordered_set_aggregate(&self) -> bool {
1167        self.inner.is_ordered_set_aggregate()
1168    }
1169
1170    fn set_monotonicity(&self, data_type: &DataType) -> SetMonotonicity {
1171        self.inner.set_monotonicity(data_type)
1172    }
1173
1174    fn documentation(&self) -> Option<&Documentation> {
1175        self.inner.documentation()
1176    }
1177}
1178
1179// Aggregate UDF doc sections for use in public documentation
1180pub mod aggregate_doc_sections {
1181    use crate::DocSection;
1182
1183    pub fn doc_sections() -> Vec<DocSection> {
1184        vec![
1185            DOC_SECTION_GENERAL,
1186            DOC_SECTION_STATISTICAL,
1187            DOC_SECTION_APPROXIMATE,
1188        ]
1189    }
1190
1191    pub const DOC_SECTION_GENERAL: DocSection = DocSection {
1192        include: true,
1193        label: "General Functions",
1194        description: None,
1195    };
1196
1197    pub const DOC_SECTION_STATISTICAL: DocSection = DocSection {
1198        include: true,
1199        label: "Statistical Functions",
1200        description: None,
1201    };
1202
1203    pub const DOC_SECTION_APPROXIMATE: DocSection = DocSection {
1204        include: true,
1205        label: "Approximate Functions",
1206        description: None,
1207    };
1208}
1209
1210/// Indicates whether an aggregation function is monotonic as a set
1211/// function. A set function is monotonically increasing if its value
1212/// increases as its argument grows (as a set). Formally, `f` is a
1213/// monotonically increasing set function if `f(S) >= f(T)` whenever `S`
1214/// is a superset of `T`.
1215///
1216/// For example `COUNT` and `MAX` are monotonically increasing as their
1217/// values always increase (or stay the same) as new values are seen. On
1218/// the other hand, `MIN` is monotonically decreasing as its value always
1219/// decreases or stays the same as new values are seen.
1220#[derive(Debug, Clone, PartialEq)]
1221pub enum SetMonotonicity {
1222    /// Aggregate value increases or stays the same as the input set grows.
1223    Increasing,
1224    /// Aggregate value decreases or stays the same as the input set grows.
1225    Decreasing,
1226    /// Aggregate value may increase, decrease, or stay the same as the input
1227    /// set grows.
1228    NotMonotonic,
1229}
1230
1231#[cfg(test)]
1232mod test {
1233    use crate::{AggregateUDF, AggregateUDFImpl};
1234    use arrow::datatypes::{DataType, FieldRef};
1235    use datafusion_common::Result;
1236    use datafusion_expr_common::accumulator::Accumulator;
1237    use datafusion_expr_common::signature::{Signature, Volatility};
1238    use datafusion_functions_aggregate_common::accumulator::{
1239        AccumulatorArgs, StateFieldsArgs,
1240    };
1241    use std::any::Any;
1242    use std::cmp::Ordering;
1243    use std::hash::{DefaultHasher, Hash, Hasher};
1244
1245    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1246    struct AMeanUdf {
1247        signature: Signature,
1248    }
1249
1250    impl AMeanUdf {
1251        fn new() -> Self {
1252            Self {
1253                signature: Signature::uniform(
1254                    1,
1255                    vec![DataType::Float64],
1256                    Volatility::Immutable,
1257                ),
1258            }
1259        }
1260    }
1261
1262    impl AggregateUDFImpl for AMeanUdf {
1263        fn as_any(&self) -> &dyn Any {
1264            self
1265        }
1266        fn name(&self) -> &str {
1267            "a"
1268        }
1269        fn signature(&self) -> &Signature {
1270            &self.signature
1271        }
1272        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
1273            unimplemented!()
1274        }
1275        fn accumulator(
1276            &self,
1277            _acc_args: AccumulatorArgs,
1278        ) -> Result<Box<dyn Accumulator>> {
1279            unimplemented!()
1280        }
1281        fn state_fields(&self, _args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
1282            unimplemented!()
1283        }
1284    }
1285
1286    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1287    struct BMeanUdf {
1288        signature: Signature,
1289    }
1290    impl BMeanUdf {
1291        fn new() -> Self {
1292            Self {
1293                signature: Signature::uniform(
1294                    1,
1295                    vec![DataType::Float64],
1296                    Volatility::Immutable,
1297                ),
1298            }
1299        }
1300    }
1301
1302    impl AggregateUDFImpl for BMeanUdf {
1303        fn as_any(&self) -> &dyn Any {
1304            self
1305        }
1306        fn name(&self) -> &str {
1307            "b"
1308        }
1309        fn signature(&self) -> &Signature {
1310            &self.signature
1311        }
1312        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
1313            unimplemented!()
1314        }
1315        fn accumulator(
1316            &self,
1317            _acc_args: AccumulatorArgs,
1318        ) -> Result<Box<dyn Accumulator>> {
1319            unimplemented!()
1320        }
1321        fn state_fields(&self, _args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
1322            unimplemented!()
1323        }
1324    }
1325
1326    #[test]
1327    fn test_partial_eq() {
1328        let a1 = AggregateUDF::from(AMeanUdf::new());
1329        let a2 = AggregateUDF::from(AMeanUdf::new());
1330        let eq = a1 == a2;
1331        assert!(eq);
1332        assert_eq!(a1, a2);
1333        assert_eq!(hash(a1), hash(a2));
1334    }
1335
1336    #[test]
1337    fn test_partial_ord() {
1338        // Test validates that partial ord is defined for AggregateUDF using the name and signature,
1339        // not intended to exhaustively test all possibilities
1340        let a1 = AggregateUDF::from(AMeanUdf::new());
1341        let a2 = AggregateUDF::from(AMeanUdf::new());
1342        assert_eq!(a1.partial_cmp(&a2), Some(Ordering::Equal));
1343
1344        let b1 = AggregateUDF::from(BMeanUdf::new());
1345        assert!(a1 < b1);
1346        assert!(!(a1 == b1));
1347    }
1348
1349    fn hash<T: Hash>(value: T) -> u64 {
1350        let hasher = &mut DefaultHasher::new();
1351        value.hash(hasher);
1352        hasher.finish()
1353    }
1354}