Skip to main content

datafusion_expr/
udaf.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`AggregateUDF`]: User Defined Aggregate Functions
6
7use std::any::Any;
8use std::cmp::Ordering;
9use std::fmt::{self, Debug, Formatter, Write};
10use std::hash::{Hash, Hasher};
11use std::sync::Arc;
12use std::vec;
13
14use arrow::datatypes::{DataType, Field, FieldRef};
15
16use datafusion_common::{Result, ScalarValue, Statistics, exec_err, not_impl_err};
17use datafusion_expr_common::dyn_eq::{DynEq, DynHash};
18use datafusion_expr_common::operator::Operator;
19use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
20
21use crate::expr::{
22    AggregateFunction, AggregateFunctionParams, ExprListDisplay, WindowFunctionParams,
23    schema_name_from_exprs, schema_name_from_exprs_comma_separated_without_space,
24    schema_name_from_sorts,
25};
26use crate::function::{
27    AccumulatorArgs, AggregateFunctionSimplification, StateFieldsArgs,
28};
29use crate::groups_accumulator::GroupsAccumulator;
30use crate::udf_eq::UdfEq;
31use crate::utils::{AggregateOrderSensitivity, format_state_name, ordering_state_fields};
32use crate::{Accumulator, Expr, expr_vec_fmt};
33use crate::{Documentation, Signature};
34
35/// Logical representation of a user-defined [aggregate function] (UDAF).
36///
37/// An aggregate function combines the values from multiple input rows
38/// into a single output "aggregate" (summary) row. It is different
39/// from a scalar function because it is stateful across batches. User
40/// defined aggregate functions can be used as normal SQL aggregate
41/// functions (`GROUP BY` clause) as well as window functions (`OVER`
42/// clause).
43///
44/// `AggregateUDF` provides DataFusion the information needed to plan and call
45/// aggregate functions, including name, type information, and a factory
46/// function to create an [`Accumulator`] instance, to perform the actual
47/// aggregation.
48///
49/// For more information, please see [the examples]:
50///
51/// 1. For simple use cases, use [`create_udaf`] (examples in [`simple_udaf.rs`]).
52///
53/// 2. For advanced use cases, use [`AggregateUDFImpl`] which provides full API
54///    access (examples in [`advanced_udaf.rs`]).
55///
56/// # API Note
57/// This is a separate struct from `AggregateUDFImpl` to maintain backwards
58/// compatibility with the older API.
59///
60/// [the examples]: https://github.com/apache/datafusion/tree/main/datafusion-examples#single-process
61/// [aggregate function]: https://en.wikipedia.org/wiki/Aggregate_function
62/// [`Accumulator`]: Accumulator
63/// [`create_udaf`]: crate::expr_fn::create_udaf
64/// [`simple_udaf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/udf/simple_udaf.rs
65/// [`advanced_udaf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/udf/advanced_udaf.rs
66#[derive(Debug, Clone, PartialOrd)]
67pub struct AggregateUDF {
68    inner: Arc<dyn AggregateUDFImpl>,
69}
70
71impl PartialEq for AggregateUDF {
72    fn eq(&self, other: &Self) -> bool {
73        self.inner.dyn_eq(other.inner.as_ref() as &dyn Any)
74    }
75}
76
77impl Eq for AggregateUDF {}
78
79impl Hash for AggregateUDF {
80    fn hash<H: Hasher>(&self, state: &mut H) {
81        self.inner.dyn_hash(state)
82    }
83}
84
85impl fmt::Display for AggregateUDF {
86    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
87        write!(f, "{}", self.name())
88    }
89}
90
91/// Arguments passed to [`AggregateUDFImpl::value_from_stats`]
92#[derive(Debug)]
93pub struct StatisticsArgs<'a> {
94    /// The statistics of the aggregate input
95    pub statistics: &'a Statistics,
96    /// The resolved return type of the aggregate function
97    pub return_type: &'a DataType,
98    /// Whether the aggregate function is distinct.
99    ///
100    /// ```sql
101    /// SELECT COUNT(DISTINCT column1) FROM t;
102    /// ```
103    pub is_distinct: bool,
104    /// The physical expression of arguments the aggregate function takes.
105    pub exprs: &'a [Arc<dyn PhysicalExpr>],
106}
107
108impl AggregateUDF {
109    /// Create a new `AggregateUDF` from a `[AggregateUDFImpl]` trait object
110    ///
111    /// Note this is the same as using the `From` impl (`AggregateUDF::from`)
112    pub fn new_from_impl<F>(fun: F) -> AggregateUDF
113    where
114        F: AggregateUDFImpl + 'static,
115    {
116        Self::new_from_shared_impl(Arc::new(fun))
117    }
118
119    /// Create a new `AggregateUDF` from a `[AggregateUDFImpl]` trait object
120    pub fn new_from_shared_impl(fun: Arc<dyn AggregateUDFImpl>) -> AggregateUDF {
121        Self { inner: fun }
122    }
123
124    /// Return the underlying [`AggregateUDFImpl`] trait object for this function
125    pub fn inner(&self) -> &Arc<dyn AggregateUDFImpl> {
126        &self.inner
127    }
128
129    /// Adds additional names that can be used to invoke this function, in
130    /// addition to `name`
131    ///
132    /// If you implement [`AggregateUDFImpl`] directly you should return aliases directly.
133    pub fn with_aliases(self, aliases: impl IntoIterator<Item = &'static str>) -> Self {
134        Self::new_from_impl(AliasedAggregateUDFImpl::new(
135            Arc::clone(&self.inner),
136            aliases,
137        ))
138    }
139
140    /// Creates an [`Expr`] that calls the aggregate function.
141    ///
142    /// This utility allows using the UDAF without requiring access to
143    /// the registry, such as with the DataFrame API.
144    pub fn call(&self, args: Vec<Expr>) -> Expr {
145        Expr::AggregateFunction(AggregateFunction::new_udf(
146            Arc::new(self.clone()),
147            args,
148            false,
149            None,
150            vec![],
151            None,
152        ))
153    }
154
155    /// Returns this function's name
156    ///
157    /// See [`AggregateUDFImpl::name`] for more details.
158    pub fn name(&self) -> &str {
159        self.inner.name()
160    }
161
162    /// Returns the aliases for this function.
163    pub fn aliases(&self) -> &[String] {
164        self.inner.aliases()
165    }
166
167    /// See [`AggregateUDFImpl::schema_name`] for more details.
168    pub fn schema_name(&self, params: &AggregateFunctionParams) -> Result<String> {
169        self.inner.schema_name(params)
170    }
171
172    /// Returns a human readable expression.
173    ///
174    /// See [`Expr::human_display`] for details.
175    pub fn human_display(&self, params: &AggregateFunctionParams) -> Result<String> {
176        self.inner.human_display(params)
177    }
178
179    pub fn window_function_schema_name(
180        &self,
181        params: &WindowFunctionParams,
182    ) -> Result<String> {
183        self.inner.window_function_schema_name(params)
184    }
185
186    /// See [`AggregateUDFImpl::display_name`] for more details.
187    pub fn display_name(&self, params: &AggregateFunctionParams) -> Result<String> {
188        self.inner.display_name(params)
189    }
190
191    pub fn window_function_display_name(
192        &self,
193        params: &WindowFunctionParams,
194    ) -> Result<String> {
195        self.inner.window_function_display_name(params)
196    }
197
198    #[deprecated(since = "56.0.0", note = "Use `AggregateUDF::return_field` instead.")]
199    pub fn is_nullable(&self) -> bool {
200        #[expect(deprecated)]
201        self.inner.is_nullable()
202    }
203
204    /// Returns this function's signature (what input types are accepted)
205    ///
206    /// See [`AggregateUDFImpl::signature`] for more details.
207    pub fn signature(&self) -> &Signature {
208        self.inner.signature()
209    }
210
211    /// Return the type of the function given its input types
212    ///
213    /// See [`AggregateUDFImpl::return_type`] for more details.
214    pub fn return_type(&self, args: &[DataType]) -> Result<DataType> {
215        self.inner.return_type(args)
216    }
217
218    /// Return the field of the function given its input fields
219    ///
220    /// See [`AggregateUDFImpl::return_field`] for more details.
221    pub fn return_field(&self, args: &[FieldRef]) -> Result<FieldRef> {
222        self.inner.return_field(args)
223    }
224
225    /// Return an accumulator the given aggregate, given its return datatype
226    pub fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
227        self.inner.accumulator(acc_args)
228    }
229
230    /// Return the fields used to store the intermediate state for this aggregator, given
231    /// the name of the aggregate, value type and ordering fields. See [`AggregateUDFImpl::state_fields`]
232    /// for more details.
233    ///
234    /// This is used to support multi-phase aggregations
235    pub fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
236        self.inner.state_fields(args)
237    }
238
239    /// See [`AggregateUDFImpl::groups_accumulator_supported`] for more details.
240    pub fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool {
241        self.inner.groups_accumulator_supported(args)
242    }
243
244    /// See [`AggregateUDFImpl::groups_accumulator_supported_for_types`] for more details.
245    pub fn groups_accumulator_supported_for_types(
246        &self,
247        arg_types: &[DataType],
248        is_distinct: bool,
249    ) -> Option<bool> {
250        self.inner
251            .groups_accumulator_supported_for_types(arg_types, is_distinct)
252    }
253
254    /// See [`AggregateUDFImpl::create_groups_accumulator`] for more details.
255    pub fn create_groups_accumulator(
256        &self,
257        args: AccumulatorArgs,
258    ) -> Result<Box<dyn GroupsAccumulator>> {
259        self.inner.create_groups_accumulator(args)
260    }
261
262    pub fn create_sliding_accumulator(
263        &self,
264        args: AccumulatorArgs,
265    ) -> Result<Box<dyn Accumulator>> {
266        self.inner.create_sliding_accumulator(args)
267    }
268
269    pub fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
270        self.inner.coerce_types(arg_types)
271    }
272
273    /// See [`AggregateUDFImpl::with_beneficial_ordering`] for more details.
274    pub fn with_beneficial_ordering(
275        self,
276        beneficial_ordering: bool,
277    ) -> Result<Option<AggregateUDF>> {
278        self.inner
279            .with_beneficial_ordering(beneficial_ordering)
280            .map(|updated_udf| updated_udf.map(|udf| Self { inner: udf }))
281    }
282
283    /// Gets the order sensitivity of the UDF. See [`AggregateOrderSensitivity`]
284    /// for possible options.
285    pub fn order_sensitivity(&self) -> AggregateOrderSensitivity {
286        self.inner.order_sensitivity()
287    }
288
289    /// Reserves the `AggregateUDF` (e.g. returns the `AggregateUDF` that will
290    /// generate same result with this `AggregateUDF` when iterated in reverse
291    /// order, and `None` if there is no such `AggregateUDF`).
292    pub fn reverse_udf(&self) -> ReversedUDAF {
293        self.inner.reverse_expr()
294    }
295
296    /// Returns this aggregate function's simplification hook, if any.
297    ///
298    /// See [`AggregateUDFImpl::simplify`] for more details.
299    pub fn simplify(&self) -> Option<AggregateFunctionSimplification> {
300        self.inner.simplify()
301    }
302
303    /// Rewrite aggregate to have simpler arguments
304    ///
305    /// See  [`AggregateUDFImpl::simplify_expr_op_literal`] for more details
306    pub fn simplify_expr_op_literal(
307        &self,
308        agg_function: &AggregateFunction,
309        arg: &Expr,
310        op: Operator,
311        lit: &Expr,
312        arg_is_left: bool,
313    ) -> Result<Option<Expr>> {
314        self.inner
315            .simplify_expr_op_literal(agg_function, arg, op, lit, arg_is_left)
316    }
317
318    /// Returns true if the function is max, false if the function is min
319    /// None in all other cases, used in certain optimizations for
320    /// or aggregate
321    pub fn is_descending(&self) -> Option<bool> {
322        self.inner.is_descending()
323    }
324
325    /// Return the value of this aggregate function if it can be determined
326    /// entirely from statistics and arguments.
327    ///
328    /// See [`AggregateUDFImpl::value_from_stats`] for more details.
329    pub fn value_from_stats(
330        &self,
331        statistics_args: &StatisticsArgs,
332    ) -> Option<ScalarValue> {
333        self.inner.value_from_stats(statistics_args)
334    }
335
336    /// See [`AggregateUDFImpl::default_value`] for more details.
337    pub fn default_value(&self, data_type: &DataType) -> Result<ScalarValue> {
338        self.inner.default_value(data_type)
339    }
340
341    /// See [`AggregateUDFImpl::supports_null_handling_clause`] for more details.
342    pub fn supports_null_handling_clause(&self) -> bool {
343        self.inner.supports_null_handling_clause()
344    }
345
346    /// See [`AggregateUDFImpl::supports_within_group_clause`] for more details.
347    pub fn supports_within_group_clause(&self) -> bool {
348        self.inner.supports_within_group_clause()
349    }
350
351    /// See [`AggregateUDFImpl::distinct_handling`] for more details.
352    pub fn distinct_handling(&self) -> DistinctHandling {
353        self.inner.distinct_handling()
354    }
355
356    /// Returns the documentation for this Aggregate UDF.
357    ///
358    /// Documentation can be accessed programmatically as well as
359    /// generating publicly facing documentation.
360    pub fn documentation(&self) -> Option<&Documentation> {
361        self.inner.documentation()
362    }
363}
364
365impl<F> From<F> for AggregateUDF
366where
367    F: AggregateUDFImpl + Send + Sync + 'static,
368{
369    fn from(fun: F) -> Self {
370        Self::new_from_impl(fun)
371    }
372}
373
374/// Trait for implementing [`AggregateUDF`].
375///
376/// This trait exposes the full API for implementing user defined aggregate functions and
377/// can be used to implement any function.
378///
379/// See [`advanced_udaf.rs`] for a full example with complete implementation and
380/// [`AggregateUDF`] for other available options.
381///
382/// [`advanced_udaf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/udf/advanced_udaf.rs
383///
384/// # Basic Example
385/// ```
386/// # use std::any::Any;
387/// # use std::sync::{Arc, LazyLock};
388/// # use arrow::datatypes::{DataType, FieldRef};
389/// # use datafusion_common::{DataFusionError, plan_err, Result};
390/// # use datafusion_expr::{col, ColumnarValue, Signature, Volatility, Expr, Documentation};
391/// # use datafusion_expr::{AggregateUDFImpl, AggregateUDF, Accumulator, function::{AccumulatorArgs, StateFieldsArgs}};
392/// # use datafusion_expr::window_doc_sections::DOC_SECTION_AGGREGATE;
393/// # use arrow::datatypes::Schema;
394/// # use arrow::datatypes::Field;
395///
396/// #[derive(Debug, Clone, PartialEq, Eq, Hash)]
397/// struct GeoMeanUdf {
398///   signature: Signature,
399/// }
400///
401/// impl GeoMeanUdf {
402///   fn new() -> Self {
403///     Self {
404///       signature: Signature::uniform(1, vec![DataType::Float64], Volatility::Immutable),
405///      }
406///   }
407/// }
408///
409/// static DOCUMENTATION: LazyLock<Documentation> = LazyLock::new(|| {
410///         Documentation::builder(DOC_SECTION_AGGREGATE, "calculates a geometric mean", "geo_mean(2.0)")
411///             .with_argument("arg1", "The Float64 number for the geometric mean")
412///             .build()
413///     });
414///
415/// fn get_doc() -> &'static Documentation {
416///     &DOCUMENTATION
417/// }
418///
419/// /// Implement the AggregateUDFImpl trait for GeoMeanUdf
420/// impl AggregateUDFImpl for GeoMeanUdf {
421///    fn name(&self) -> &str { "geo_mean" }
422///    fn signature(&self) -> &Signature { &self.signature }
423///    fn return_type(&self, args: &[DataType]) -> Result<DataType> {
424///      if !matches!(args.get(0), Some(&DataType::Float64)) {
425///        return plan_err!("geo_mean only accepts Float64 arguments");
426///      }
427///      Ok(DataType::Float64)
428///    }
429///    // This is the accumulator factory; DataFusion uses it to create new accumulators.
430///    fn accumulator(&self, _acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { unimplemented!() }
431///    fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
432///        Ok(vec![
433///             Arc::new(args.return_field.as_ref().clone().with_name("value")),
434///             Arc::new(Field::new("ordering", DataType::UInt32, true))
435///        ])
436///    }
437///    fn documentation(&self) -> Option<&Documentation> {
438///        Some(get_doc())
439///    }
440/// }
441///
442/// // Create a new AggregateUDF from the implementation
443/// let geometric_mean = AggregateUDF::from(GeoMeanUdf::new());
444///
445/// // Call the function `geo_mean(col)`
446/// let expr = geometric_mean.call(vec![col("a")]);
447/// ```
448pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync + Any {
449    /// Returns this function's name
450    fn name(&self) -> &str;
451
452    /// Returns any aliases (alternate names) for this function.
453    ///
454    /// Note: `aliases` should only include names other than [`Self::name`].
455    /// Defaults to `[]` (no aliases)
456    fn aliases(&self) -> &[String] {
457        &[]
458    }
459
460    /// Returns the name of the column this expression would create
461    ///
462    /// See [`Expr::schema_name`] for details
463    ///
464    /// Example of schema_name: count(DISTINCT column1) FILTER (WHERE column2 > 10) ORDER BY [..]
465    ///
466    /// The default implementation is provided by [`UdafSchemaNameBuilder`]
467    fn schema_name(&self, params: &AggregateFunctionParams) -> Result<String> {
468        UdafSchemaNameBuilder::new(self.name(), params)
469            .with_supports_within_group_clause(self.supports_within_group_clause())
470            .build()
471    }
472
473    /// Returns a human readable expression.
474    ///
475    /// See [`Expr::human_display`] for details.
476    ///
477    /// The default implementation is provided by [`UdafHumanDisplayBuilder`]
478    fn human_display(&self, params: &AggregateFunctionParams) -> Result<String> {
479        UdafHumanDisplayBuilder::new(self.name(), params).build()
480    }
481
482    /// Returns the name of the column this expression would create
483    ///
484    /// See [`Expr::schema_name`] for details
485    ///
486    /// Different from `schema_name` in that it is used for window aggregate function
487    ///
488    /// Example of schema_name: count(DISTINCT column1) FILTER (WHERE column2 > 10) [PARTITION BY [..]] [ORDER BY [..]]
489    ///
490    /// The default implementation is provided by [`UdafWindowFunctionSchemaNameBuilder`]
491    fn window_function_schema_name(
492        &self,
493        params: &WindowFunctionParams,
494    ) -> Result<String> {
495        UdafWindowFunctionSchemaNameBuilder::new(self.name(), params).build()
496    }
497
498    /// Returns the user-defined display name of function, given the arguments
499    ///
500    /// This can be used to customize the output column name generated by this
501    /// function.
502    ///
503    /// Defaults to `function_name([DISTINCT] column1, column2, ..) [null_treatment] [filter] [order_by [..]]`
504    ///
505    /// The default implementation is provided by [`UdafDisplayNameBuilder`]
506    fn display_name(&self, params: &AggregateFunctionParams) -> Result<String> {
507        UdafDisplayNameBuilder::new(self.name(), params).build()
508    }
509
510    /// Returns the user-defined display name of function, given the arguments
511    ///
512    /// This can be used to customize the output column name generated by this
513    /// function.
514    ///
515    /// Different from `display_name` in that it is used for window aggregate function
516    ///
517    /// Defaults to `function_name([DISTINCT] column1, column2, ..) [null_treatment] [partition by [..]] [order_by [..]]`
518    ///
519    /// The default implementation is provided by [`UdafWindowFunctionDisplayNameBuilder`]
520    fn window_function_display_name(
521        &self,
522        params: &WindowFunctionParams,
523    ) -> Result<String> {
524        UdafWindowFunctionDisplayNameBuilder::new(self.name(), params).build()
525    }
526
527    /// Returns the function's [`Signature`] for information about what input
528    /// types are accepted and the function's Volatility.
529    fn signature(&self) -> &Signature;
530
531    /// What [`DataType`] will be returned by this function, given the types of
532    /// the arguments
533    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType>;
534
535    /// What type will be returned by this function, given the arguments?
536    ///
537    /// By default, this function calls [`Self::return_type`] with the
538    /// types of each argument.
539    ///
540    /// # Notes
541    ///
542    /// Most UDFs should implement [`Self::return_type`] and not this
543    /// function as the output type for most functions only depends on the types
544    /// of their inputs (e.g. `sum(f64)` is always `f64`).
545    ///
546    /// This function can be used for more advanced cases such as:
547    ///
548    /// 1. specifying nullability
549    /// 2. return types based on the **values** of the arguments (rather than
550    ///    their **types**.
551    /// 3. return types based on metadata within the fields of the inputs
552    fn return_field(&self, arg_fields: &[FieldRef]) -> Result<FieldRef> {
553        udaf_default_return_field(self, arg_fields)
554    }
555
556    /// Whether the aggregate function is nullable.
557    ///
558    /// Nullable means that the function could return `null` for any inputs.
559    /// For example, aggregate functions like `COUNT` always return a non null value
560    /// but others like `MIN` will return `NULL` if there is nullable input.
561    /// Note that if the function is declared as *not* nullable, make sure the [`AggregateUDFImpl::default_value`] is `non-null`
562    #[deprecated(since = "56.0.0", note = "Use `return_field` instead.")]
563    fn is_nullable(&self) -> bool {
564        true
565    }
566
567    /// Return a new [`Accumulator`] that aggregates values for a specific
568    /// group during query execution.
569    ///
570    /// acc_args: [`AccumulatorArgs`] contains information about how the
571    /// aggregate function was called.
572    fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>>;
573
574    /// Return the fields used to store the intermediate state of this accumulator.
575    ///
576    /// See [`Accumulator::state`] for background information.
577    ///
578    /// args:  [`StateFieldsArgs`] contains arguments passed to the
579    /// aggregate function's accumulator.
580    ///
581    /// # Notes:
582    ///
583    /// The default implementation returns a single state field named `name`
584    /// with the same type as `value_type`. This is suitable for aggregates such
585    /// as `SUM` or `MIN` where partial state can be combined by applying the
586    /// same aggregate.
587    ///
588    /// For aggregates such as `AVG` where the partial state is more complex
589    /// (e.g. a COUNT and a SUM), this method is used to define the additional
590    /// fields.
591    ///
592    /// The name of the fields must be unique within the query and thus should
593    /// be derived from `name`. See [`format_state_name`] for a utility function
594    /// to generate a unique name.
595    fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
596        let fields = vec![
597            args.return_field
598                .as_ref()
599                .clone()
600                .with_name(format_state_name(args.name, "value")),
601        ];
602
603        Ok(fields
604            .into_iter()
605            .map(Arc::new)
606            .chain(ordering_state_fields(args.name, args.ordering_fields))
607            .collect())
608    }
609
610    /// If the aggregate expression has a specialized
611    /// [`GroupsAccumulator`] implementation. If this returns true,
612    /// `[Self::create_groups_accumulator]` will be called.
613    ///
614    /// # Notes
615    ///
616    /// Even if this function returns true, DataFusion will still use
617    /// [`Self::accumulator`] for certain queries, such as when this aggregate is
618    /// used as a window function or when there no GROUP BY columns in the
619    /// query.
620    fn groups_accumulator_supported(&self, _args: AccumulatorArgs) -> bool {
621        false
622    }
623
624    /// The same question as [`Self::groups_accumulator_supported`], asked with
625    /// only the information a logical plan carries.
626    ///
627    /// Physical planning has an [`AccumulatorArgs`] to ask with; an optimizer
628    /// rule does not. This is how a logical caller learns whether a call would
629    /// get a specialized [`GroupsAccumulator`] or fall back to one boxed
630    /// [`Accumulator`] per group in `GroupsAccumulatorAdapter`, whose per-group
631    /// state can be orders of magnitude larger.
632    ///
633    /// An implementation whose answer is decided by the argument types and
634    /// `DISTINCT` alone should override this and have
635    /// [`Self::groups_accumulator_supported`] call it, so the two cannot
636    /// disagree. One whose answer needs more than that should leave the `None`
637    /// default.
638    ///
639    /// `None` means unanswered, not "no": a caller must not read it as either
640    /// `Some(true)` or `Some(false)`, since both readings are wrong for some
641    /// implementation that returns it.
642    fn groups_accumulator_supported_for_types(
643        &self,
644        _arg_types: &[DataType],
645        _is_distinct: bool,
646    ) -> Option<bool> {
647        None
648    }
649
650    /// Return a specialized [`GroupsAccumulator`] that manages state
651    /// for all groups.
652    ///
653    /// For maximum performance, a [`GroupsAccumulator`] should be
654    /// implemented in addition to [`Accumulator`].
655    fn create_groups_accumulator(
656        &self,
657        _args: AccumulatorArgs,
658    ) -> Result<Box<dyn GroupsAccumulator>> {
659        not_impl_err!("GroupsAccumulator hasn't been implemented for {self:?} yet")
660    }
661
662    /// Sliding accumulator is an alternative accumulator that can be used for
663    /// window functions. It has retract method to revert the previous update.
664    ///
665    /// See [retract_batch] for more details.
666    ///
667    /// [retract_batch]: Accumulator::retract_batch
668    fn create_sliding_accumulator(
669        &self,
670        args: AccumulatorArgs,
671    ) -> Result<Box<dyn Accumulator>> {
672        self.accumulator(args)
673    }
674
675    /// Sets the indicator whether ordering requirements of the AggregateUDFImpl is
676    /// satisfied by its input. If this is not the case, UDFs with order
677    /// sensitivity `AggregateOrderSensitivity::Beneficial` can still produce
678    /// the correct result with possibly more work internally.
679    ///
680    /// # Returns
681    ///
682    /// Returns `Ok(Some(updated_udf))` if the process completes successfully.
683    /// If the expression can benefit from existing input ordering, but does
684    /// not implement the method, returns an error. Order insensitive and hard
685    /// requirement aggregators return `Ok(None)`.
686    fn with_beneficial_ordering(
687        self: Arc<Self>,
688        _beneficial_ordering: bool,
689    ) -> Result<Option<Arc<dyn AggregateUDFImpl>>> {
690        if self.order_sensitivity().is_beneficial() {
691            return exec_err!(
692                "Should implement with satisfied for aggregator :{:?}",
693                self.name()
694            );
695        }
696        Ok(None)
697    }
698
699    /// Gets the order sensitivity of the UDF. See [`AggregateOrderSensitivity`]
700    /// for possible options.
701    fn order_sensitivity(&self) -> AggregateOrderSensitivity {
702        // We have hard ordering requirements by default, meaning that order
703        // sensitive UDFs need their input orderings to satisfy their ordering
704        // requirements to generate correct results.
705        AggregateOrderSensitivity::HardRequirement
706    }
707
708    /// Returns an optional hook for simplifying this user-defined aggregate.
709    ///
710    /// Use this hook to apply function-specific rewrites during optimization.
711    /// The default implementation returns `None`.
712    ///
713    /// For example, `percentile_cont(x, 0.0)` and `percentile_cont(x, 1.0)` can
714    /// be rewritten to `MIN(x)` or `MAX(x)` depending on the `ORDER BY`
715    /// direction.
716    ///
717    /// DataFusion already simplifies arguments and performs constant folding
718    /// (for example, `my_add(1, 2) -> 3`). For nested expressions, the optimizer
719    /// runs simplification in multiple passes, so arguments are typically
720    /// simplified before this hook is invoked. As a result, UDF implementations
721    /// usually do not need to handle argument simplification themselves.
722    ///
723    /// See configuration `datafusion.optimizer.max_passes` for details on how many
724    /// optimization passes may be applied.
725    ///
726    /// # Returns
727    ///
728    /// `None` if simplify is not defined.
729    ///
730    /// Or, a closure ([`AggregateFunctionSimplification`]) invoked with:
731    /// * `aggregate_function`: [AggregateFunction] with already simplified
732    ///   arguments
733    /// * `info`: [crate::simplify::SimplifyContext]
734    ///
735    /// The closure returns a simplified [Expr] or an error.
736    ///
737    /// # Notes
738    ///
739    /// The returned expression must have the same schema as the original
740    /// expression, including both the data type and nullability. For example,
741    /// if the original expression is nullable, the returned expression must
742    /// also be nullable, otherwise it may lead to schema verification errors
743    /// later in query planning.
744    fn simplify(&self) -> Option<AggregateFunctionSimplification> {
745        None
746    }
747
748    /// Rewrite the aggregate to have simpler arguments
749    ///
750    /// This query pattern is not common in most real workloads, and most
751    /// aggregate implementations can safely ignore it. This API is included in
752    /// DataFusion because it is important for ClickBench Q29. See backstory
753    /// on <https://github.com/apache/datafusion/issues/15524>
754    ///
755    /// # Rewrite Overview
756    ///
757    /// The idea is to rewrite multiple aggregates with "complex arguments" into
758    /// ones with simpler arguments that can be optimized by common subexpression
759    /// elimination (CSE). At a high level the rewrite looks like
760    ///
761    /// * `Aggregate(SUM(x + 1), SUM(x + 2), ...)`
762    ///
763    /// Into
764    ///
765    /// * `Aggregate(SUM(x) + 1 * COUNT(x), SUM(x) + 2 * COUNT(x), ...)`
766    ///
767    /// While this rewrite may seem worse (slower) than the original as it
768    /// computes *more* aggregate expressions, the common subexpression
769    /// elimination (CSE) can then reduce the number of distinct aggregates the
770    /// query actually needs to compute with a rewrite like
771    ///
772    /// * `Projection(_A + 1*_B, _A + 2*_B)`
773    /// * `  Aggregate(_A = SUM(x), _B = COUNT(x))`
774    ///
775    /// This optimization is extremely important for ClickBench Q29, which has 90
776    /// such expressions for some reason, and so this optimization results in
777    /// only two aggregates being needed. The DataFusion optimizer will invoke
778    /// this method when it detects multiple aggregates in a query that share
779    /// arguments of the form `<arg> <op> <literal>`.
780    ///
781    /// # API
782    ///
783    /// If `agg_function` supports the rewrite, it should return a semantically
784    /// equivalent expression (likely with more aggregate expressions, but
785    /// simpler arguments)
786    ///
787    /// This is only called when:
788    /// 1. There are no "special" aggregate params (filters, null handling, etc)
789    /// 2. Aggregate functions with exactly one [`Expr`] argument
790    /// 3. There are no volatile expressions
791    ///
792    /// Arguments
793    /// * `agg_function`: the original aggregate function detected with complex
794    ///   arguments.
795    /// * `arg`: The common argument shared across multiple aggregates (e.g. `x`
796    ///   in the example above)
797    /// * `op`: the operator between the common argument and the literal (e.g.
798    ///   `+` in `x + 1` or `1 + x`)
799    /// * `lit`: the literal argument (e.g. `1` or `2` in the example above)
800    /// * `arg_is_left`: whether the common argument is on the left or right of
801    ///   the operator (e.g. `true` for `x + 1` and false for `1 + x`)
802    ///
803    /// The default implementation returns `None`, which is what most aggregates
804    /// should do.
805    fn simplify_expr_op_literal(
806        &self,
807        _agg_function: &AggregateFunction,
808        _arg: &Expr,
809        _op: Operator,
810        _lit: &Expr,
811        _arg_is_left: bool,
812    ) -> Result<Option<Expr>> {
813        Ok(None)
814    }
815
816    /// Returns the reverse expression of the aggregate function.
817    fn reverse_expr(&self) -> ReversedUDAF {
818        ReversedUDAF::NotSupported
819    }
820
821    /// Coerce arguments of a function call to types that the function can evaluate.
822    ///
823    /// This function is only called if [`AggregateUDFImpl::signature`] returns [`crate::TypeSignature::UserDefined`]. Most
824    /// UDAFs should return one of the other variants of `TypeSignature` which handle common
825    /// cases
826    ///
827    /// See the [type coercion module](crate::type_coercion)
828    /// documentation for more details on type coercion
829    ///
830    /// For example, if your function requires a floating point arguments, but the user calls
831    /// it like `my_func(1::int)` (aka with `1` as an integer), coerce_types could return `[DataType::Float64]`
832    /// to ensure the argument was cast to `1::double`
833    ///
834    /// # Parameters
835    /// * `arg_types`: The argument types of the arguments  this function with
836    ///
837    /// # Return value
838    /// A Vec the same length as `arg_types`. DataFusion will `CAST` the function call
839    /// arguments to these specific types.
840    fn coerce_types(&self, _arg_types: &[DataType]) -> Result<Vec<DataType>> {
841        not_impl_err!("Function {} does not implement coerce_types", self.name())
842    }
843
844    /// If this function is max, return true
845    /// If the function is min, return false
846    /// Otherwise return None (the default)
847    ///
848    ///
849    /// Note: this is used to use special aggregate implementations in certain conditions
850    fn is_descending(&self) -> Option<bool> {
851        None
852    }
853
854    /// Return the value of this aggregate function if it can be determined
855    /// entirely from statistics and arguments.
856    ///
857    /// Using a [`ScalarValue`] rather than a runtime computation can significantly
858    /// improving query performance.
859    ///
860    /// For example, if the minimum value of column `x` is known to be `42` from
861    /// statistics, then the aggregate `MIN(x)` should return `Some(ScalarValue(42))`
862    fn value_from_stats(&self, _statistics_args: &StatisticsArgs) -> Option<ScalarValue> {
863        None
864    }
865
866    /// Returns default value of the function given the input is all `null`.
867    ///
868    /// Most of the aggregate function return Null if input is Null,
869    /// while `count` returns 0 if input is Null
870    fn default_value(&self, data_type: &DataType) -> Result<ScalarValue> {
871        ScalarValue::try_from(data_type)
872    }
873
874    /// If this function supports `[IGNORE NULLS | RESPECT NULLS]` SQL clause,
875    /// return `true`. Otherwise, return `false` which will cause an error to be
876    /// raised during SQL parsing if these clauses are detected for this function.
877    ///
878    /// Functions which implement this as `true` are expected to handle the resulting
879    /// null handling config present in [`AccumulatorArgs`], `ignore_nulls`.
880    fn supports_null_handling_clause(&self) -> bool {
881        false
882    }
883
884    /// If this function supports the `WITHIN GROUP (ORDER BY column [ASC|DESC])`
885    /// SQL syntax, return `true`. Otherwise, return `false` (default) which will
886    /// cause an error when parsing SQL where this syntax is detected for this
887    /// function.
888    ///
889    /// This function should return `true` for ordered-set aggregate functions
890    /// only.
891    ///
892    /// # Ordered-set aggregate functions
893    ///
894    /// Ordered-set aggregate functions allow specifying a sort order that affects
895    /// how the function calculates its result, unlike other aggregate functions
896    /// like `sum` or `count`. For example, `percentile_cont` is an ordered-set
897    /// aggregate function that calculates the exact percentile value from a list
898    /// of values; the output of calculating the `0.75` percentile depends on if
899    /// you're calculating on an ascending or descending list of values.
900    ///
901    /// An example of how an ordered-set aggregate function is called with the
902    /// `WITHIN GROUP` SQL syntax:
903    ///
904    /// ```sql
905    /// -- Ascending
906    /// SELECT percentile_cont(0.75) WITHIN GROUP (ORDER BY c1 ASC) FROM table;
907    /// -- Default ordering is ascending if not explicitly specified
908    /// SELECT percentile_cont(0.75) WITHIN GROUP (ORDER BY c1) FROM table;
909    /// -- Descending
910    /// SELECT percentile_cont(0.75) WITHIN GROUP (ORDER BY c1 DESC) FROM table;
911    /// ```
912    ///
913    /// This calculates the `0.75` percentile of the column `c1` from `table`,
914    /// according to the specific ordering. The column specified in the `WITHIN GROUP`
915    /// ordering clause is taken as the column to calculate values on; specifying
916    /// the `WITHIN GROUP` clause is optional so these queries are equivalent:
917    ///
918    /// ```sql
919    /// -- If no WITHIN GROUP is specified then default ordering is implementation
920    /// -- dependent; in this case ascending for percentile_cont
921    /// SELECT percentile_cont(c1, 0.75) FROM table;
922    /// SELECT percentile_cont(0.75) WITHIN GROUP (ORDER BY c1 ASC) FROM table;
923    /// ```
924    ///
925    /// Aggregate UDFs can define their default ordering if the function is called
926    /// without the `WITHIN GROUP` clause, though a default of ascending is the
927    /// standard practice.
928    ///
929    /// Ordered-set aggregate function implementations are responsible for handling
930    /// the input sort order themselves (e.g. `percentile_cont` must buffer and
931    /// sort the values internally). That is, DataFusion does not introduce any
932    /// kind of sort into the plan for these functions with this syntax.
933    fn supports_within_group_clause(&self) -> bool {
934        false
935    }
936
937    /// How this function treats the `DISTINCT` modifier.
938    ///
939    /// Return [`DistinctHandling::Insensitive`] for duplicate-insensitive
940    /// functions so that `f(DISTINCT x)` is planned as `f(x)`.
941    ///
942    /// Return [`DistinctHandling::Unsupported`] if the accumulator does not
943    /// implement `DISTINCT`, that is, it does not read `is_distinct`, or it
944    /// rejects `DISTINCT` with an error. The planner then has to deduplicate
945    /// the input or reject the query. Nothing reads this variant yet:
946    /// rejecting such queries at planning time is a follow-up change.
947    fn distinct_handling(&self) -> DistinctHandling {
948        DistinctHandling::Sensitive
949    }
950
951    /// Returns the documentation for this Aggregate UDF.
952    ///
953    /// Documentation can be accessed programmatically as well as
954    /// generating publicly facing documentation.
955    fn documentation(&self) -> Option<&Documentation> {
956        None
957    }
958
959    /// Indicates whether the aggregation function is monotonic as a set
960    /// function. See [`SetMonotonicity`] for details.
961    fn set_monotonicity(&self, _data_type: &DataType) -> SetMonotonicity {
962        SetMonotonicity::NotMonotonic
963    }
964}
965
966impl dyn AggregateUDFImpl {
967    /// Returns `true` if the implementation is of type `T`.
968    ///
969    /// Works correctly when called on `Arc<dyn AggregateUDFImpl>` via auto-deref.
970    pub fn is<T: AggregateUDFImpl>(&self) -> bool {
971        (self as &dyn Any).is::<T>()
972    }
973
974    /// Attempts to downcast to a concrete type `T`, returning `None` if the
975    /// implementation is not of that type.
976    ///
977    /// Works correctly when called on `Arc<dyn AggregateUDFImpl>` via auto-deref,
978    /// unlike `(&arc as &dyn Any).downcast_ref::<T>()` which would attempt to
979    /// downcast the `Arc` itself.
980    pub fn downcast_ref<T: AggregateUDFImpl>(&self) -> Option<&T> {
981        (self as &dyn Any).downcast_ref()
982    }
983}
984
985impl PartialEq for dyn AggregateUDFImpl {
986    fn eq(&self, other: &Self) -> bool {
987        self.dyn_eq(other)
988    }
989}
990
991impl PartialOrd for dyn AggregateUDFImpl {
992    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
993        match self.name().partial_cmp(other.name()) {
994            Some(Ordering::Equal) => self.signature().partial_cmp(other.signature()),
995            cmp => cmp,
996        }
997        // TODO (https://github.com/apache/datafusion/issues/17477) avoid recomparing all fields
998        .filter(|cmp| *cmp != Ordering::Equal || self == other)
999    }
1000}
1001
1002/// Builds the default implementation of [`AggregateUDFImpl::schema_name`].
1003///
1004/// # Example
1005/// ```
1006/// # use datafusion_expr::col;
1007/// # use datafusion_expr::expr::{AggregateFunctionParams, Sort};
1008/// # use datafusion_expr::UdafSchemaNameBuilder;
1009/// # let params = AggregateFunctionParams {
1010/// #     args: vec![col("x")],
1011/// #     distinct: true,
1012/// #     filter: None,
1013/// #     order_by: vec![Sort::new(col("y"), true, false)],
1014/// #     null_treatment: None,
1015/// # };
1016/// let schema_name = UdafSchemaNameBuilder::new("my_udaf", &params)
1017///     .with_supports_within_group_clause(false)
1018///     .build()
1019///     .unwrap();
1020/// assert_eq!(schema_name, "my_udaf(DISTINCT x) ORDER BY [y ASC NULLS LAST]");
1021/// ```
1022#[derive(Debug)]
1023pub struct UdafSchemaNameBuilder<'a> {
1024    name: &'a str,
1025    params: &'a AggregateFunctionParams,
1026    supports_within_group_clause: bool,
1027}
1028
1029impl<'a> UdafSchemaNameBuilder<'a> {
1030    /// Create a new builder for the function named `name`
1031    /// (the result of [`AggregateUDFImpl::name`])
1032    pub fn new(name: &'a str, params: &'a AggregateFunctionParams) -> Self {
1033        Self {
1034            name,
1035            params,
1036            supports_within_group_clause: false,
1037        }
1038    }
1039
1040    /// Set whether the function supports the `WITHIN GROUP` clause
1041    /// (the result of [`AggregateUDFImpl::supports_within_group_clause`]).
1042    /// Defaults to `false`.
1043    pub fn with_supports_within_group_clause(
1044        mut self,
1045        supports_within_group_clause: bool,
1046    ) -> Self {
1047        self.supports_within_group_clause = supports_within_group_clause;
1048        self
1049    }
1050
1051    /// Build the schema name
1052    pub fn build(self) -> Result<String> {
1053        let Self {
1054            name,
1055            params,
1056            supports_within_group_clause,
1057        } = self;
1058
1059        let AggregateFunctionParams {
1060            args,
1061            distinct,
1062            filter,
1063            order_by,
1064            null_treatment,
1065        } = params;
1066
1067        // exclude the first function argument(= column) in ordered set aggregate function,
1068        // because it is duplicated with the WITHIN GROUP clause in schema name.
1069        let args = if supports_within_group_clause && !order_by.is_empty() {
1070            &args[1..]
1071        } else {
1072            &args[..]
1073        };
1074
1075        let mut schema_name = String::new();
1076
1077        schema_name.write_fmt(format_args!(
1078            "{}({}{})",
1079            name,
1080            if *distinct { "DISTINCT " } else { "" },
1081            schema_name_from_exprs_comma_separated_without_space(args)?
1082        ))?;
1083
1084        if let Some(null_treatment) = null_treatment {
1085            schema_name.write_fmt(format_args!(" {null_treatment}"))?;
1086        }
1087
1088        if let Some(filter) = filter {
1089            schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;
1090        }
1091
1092        if !order_by.is_empty() {
1093            let clause = match supports_within_group_clause {
1094                true => "WITHIN GROUP",
1095                false => "ORDER BY",
1096            };
1097
1098            schema_name.write_fmt(format_args!(
1099                " {} [{}]",
1100                clause,
1101                schema_name_from_sorts(order_by)?
1102            ))?;
1103        }
1104
1105        Ok(schema_name)
1106    }
1107}
1108
1109/// Encapsulates default implementation of [`AggregateUDFImpl::schema_name`].
1110#[deprecated(since = "56.0.0", note = "use `UdafSchemaNameBuilder` instead")]
1111pub fn udaf_default_schema_name<F: AggregateUDFImpl + ?Sized>(
1112    func: &F,
1113    params: &AggregateFunctionParams,
1114) -> Result<String> {
1115    UdafSchemaNameBuilder::new(func.name(), params)
1116        .with_supports_within_group_clause(func.supports_within_group_clause())
1117        .build()
1118}
1119
1120/// Builds the default implementation of [`AggregateUDFImpl::human_display`].
1121///
1122/// # Example
1123/// ```
1124/// # use datafusion_expr::col;
1125/// # use datafusion_expr::expr::AggregateFunctionParams;
1126/// # use datafusion_expr::UdafHumanDisplayBuilder;
1127/// # let params = AggregateFunctionParams {
1128/// #     args: vec![col("x")],
1129/// #     distinct: false,
1130/// #     filter: Some(Box::new(col("y").gt(col("z")))),
1131/// #     order_by: vec![],
1132/// #     null_treatment: None,
1133/// # };
1134/// let human_display = UdafHumanDisplayBuilder::new("my_udaf", &params)
1135///     .build()
1136///     .unwrap();
1137/// assert_eq!(human_display, "my_udaf(x) FILTER (WHERE y > z)");
1138/// ```
1139#[derive(Debug)]
1140pub struct UdafHumanDisplayBuilder<'a> {
1141    name: &'a str,
1142    params: &'a AggregateFunctionParams,
1143}
1144
1145impl<'a> UdafHumanDisplayBuilder<'a> {
1146    /// Create a new builder for the function named `name`
1147    /// (the result of [`AggregateUDFImpl::name`])
1148    pub fn new(name: &'a str, params: &'a AggregateFunctionParams) -> Self {
1149        Self { name, params }
1150    }
1151
1152    /// Build the human readable display
1153    pub fn build(self) -> Result<String> {
1154        let Self { name, params } = self;
1155
1156        let AggregateFunctionParams {
1157            args,
1158            distinct,
1159            filter,
1160            order_by,
1161            null_treatment,
1162        } = params;
1163
1164        let mut schema_name = String::new();
1165
1166        schema_name.write_fmt(format_args!(
1167            "{}({}{})",
1168            name,
1169            if *distinct { "DISTINCT " } else { "" },
1170            ExprListDisplay::comma_separated(args.as_slice())
1171        ))?;
1172
1173        if let Some(null_treatment) = null_treatment {
1174            schema_name.write_fmt(format_args!(" {null_treatment}"))?;
1175        }
1176
1177        if let Some(filter) = filter {
1178            schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;
1179        }
1180
1181        if !order_by.is_empty() {
1182            schema_name.write_fmt(format_args!(
1183                " ORDER BY [{}]",
1184                schema_name_from_sorts(order_by)?
1185            ))?;
1186        }
1187
1188        Ok(schema_name)
1189    }
1190}
1191
1192/// Encapsulates default implementation of [`AggregateUDFImpl::human_display`].
1193#[deprecated(since = "56.0.0", note = "use `UdafHumanDisplayBuilder` instead")]
1194pub fn udaf_default_human_display<F: AggregateUDFImpl + ?Sized>(
1195    func: &F,
1196    params: &AggregateFunctionParams,
1197) -> Result<String> {
1198    UdafHumanDisplayBuilder::new(func.name(), params).build()
1199}
1200
1201/// Builds the default implementation of [`AggregateUDFImpl::window_function_schema_name`].
1202///
1203/// # Example
1204/// ```
1205/// # use datafusion_expr::{col, WindowFrame};
1206/// # use datafusion_expr::expr::WindowFunctionParams;
1207/// # use datafusion_expr::UdafWindowFunctionSchemaNameBuilder;
1208/// # let params = WindowFunctionParams {
1209/// #     args: vec![col("x")],
1210/// #     partition_by: vec![col("y")],
1211/// #     order_by: vec![],
1212/// #     window_frame: WindowFrame::new(None),
1213/// #     filter: None,
1214/// #     null_treatment: None,
1215/// #     distinct: false,
1216/// # };
1217/// let schema_name = UdafWindowFunctionSchemaNameBuilder::new("my_udaf", &params)
1218///     .build()
1219///     .unwrap();
1220/// assert_eq!(
1221///     schema_name,
1222///     "my_udaf(x) PARTITION BY [y] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING"
1223/// );
1224/// ```
1225#[derive(Debug)]
1226pub struct UdafWindowFunctionSchemaNameBuilder<'a> {
1227    name: &'a str,
1228    params: &'a WindowFunctionParams,
1229}
1230
1231impl<'a> UdafWindowFunctionSchemaNameBuilder<'a> {
1232    /// Create a new builder for the function named `name`
1233    /// (the result of [`AggregateUDFImpl::name`])
1234    pub fn new(name: &'a str, params: &'a WindowFunctionParams) -> Self {
1235        Self { name, params }
1236    }
1237
1238    /// Build the schema name
1239    pub fn build(self) -> Result<String> {
1240        let Self { name, params } = self;
1241
1242        let WindowFunctionParams {
1243            args,
1244            partition_by,
1245            order_by,
1246            window_frame,
1247            filter,
1248            null_treatment,
1249            distinct,
1250        } = params;
1251
1252        let mut schema_name = String::new();
1253
1254        // Inject DISTINCT into the schema name when requested
1255        if *distinct {
1256            schema_name.write_fmt(format_args!(
1257                "{}(DISTINCT {})",
1258                name,
1259                schema_name_from_exprs(args)?
1260            ))?;
1261        } else {
1262            schema_name.write_fmt(format_args!(
1263                "{}({})",
1264                name,
1265                schema_name_from_exprs(args)?
1266            ))?;
1267        }
1268
1269        if let Some(null_treatment) = null_treatment {
1270            schema_name.write_fmt(format_args!(" {null_treatment}"))?;
1271        }
1272
1273        if let Some(filter) = filter {
1274            schema_name.write_fmt(format_args!(" FILTER (WHERE {filter})"))?;
1275        }
1276
1277        if !partition_by.is_empty() {
1278            schema_name.write_fmt(format_args!(
1279                " PARTITION BY [{}]",
1280                schema_name_from_exprs(partition_by)?
1281            ))?;
1282        }
1283
1284        if !order_by.is_empty() {
1285            schema_name.write_fmt(format_args!(
1286                " ORDER BY [{}]",
1287                schema_name_from_sorts(order_by)?
1288            ))?;
1289        }
1290
1291        schema_name.write_fmt(format_args!(" {window_frame}"))?;
1292
1293        Ok(schema_name)
1294    }
1295}
1296
1297/// Encapsulates default implementation of [`AggregateUDFImpl::window_function_schema_name`].
1298#[deprecated(
1299    since = "56.0.0",
1300    note = "use `UdafWindowFunctionSchemaNameBuilder` instead"
1301)]
1302pub fn udaf_default_window_function_schema_name<F: AggregateUDFImpl + ?Sized>(
1303    func: &F,
1304    params: &WindowFunctionParams,
1305) -> Result<String> {
1306    UdafWindowFunctionSchemaNameBuilder::new(func.name(), params).build()
1307}
1308
1309/// Builds the default implementation of [`AggregateUDFImpl::display_name`].
1310///
1311/// # Example
1312/// ```
1313/// # use datafusion_expr::col;
1314/// # use datafusion_expr::expr::AggregateFunctionParams;
1315/// # use datafusion_expr::UdafDisplayNameBuilder;
1316/// # let params = AggregateFunctionParams {
1317/// #     args: vec![col("x")],
1318/// #     distinct: false,
1319/// #     filter: None,
1320/// #     order_by: vec![],
1321/// #     null_treatment: None,
1322/// # };
1323/// let display_name = UdafDisplayNameBuilder::new("my_udaf", &params)
1324///     .build()
1325///     .unwrap();
1326/// assert_eq!(display_name, "my_udaf(x)");
1327/// ```
1328#[derive(Debug)]
1329pub struct UdafDisplayNameBuilder<'a> {
1330    name: &'a str,
1331    params: &'a AggregateFunctionParams,
1332}
1333
1334impl<'a> UdafDisplayNameBuilder<'a> {
1335    /// Create a new builder for the function named `name`
1336    /// (the result of [`AggregateUDFImpl::name`])
1337    pub fn new(name: &'a str, params: &'a AggregateFunctionParams) -> Self {
1338        Self { name, params }
1339    }
1340
1341    /// Build the display name
1342    pub fn build(self) -> Result<String> {
1343        let Self { name, params } = self;
1344
1345        let AggregateFunctionParams {
1346            args,
1347            distinct,
1348            filter,
1349            order_by,
1350            null_treatment,
1351        } = params;
1352
1353        let mut display_name = String::new();
1354
1355        display_name.write_fmt(format_args!(
1356            "{}({}{})",
1357            name,
1358            if *distinct { "DISTINCT " } else { "" },
1359            expr_vec_fmt!(args)
1360        ))?;
1361
1362        if let Some(nt) = null_treatment {
1363            display_name.write_fmt(format_args!(" {nt}"))?;
1364        }
1365        if let Some(fe) = filter {
1366            display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;
1367        }
1368        if !order_by.is_empty() {
1369            display_name.write_fmt(format_args!(
1370                " ORDER BY [{}]",
1371                order_by
1372                    .iter()
1373                    .map(|o| format!("{o}"))
1374                    .collect::<Vec<String>>()
1375                    .join(", ")
1376            ))?;
1377        }
1378
1379        Ok(display_name)
1380    }
1381}
1382
1383/// Encapsulates default implementation of [`AggregateUDFImpl::display_name`].
1384#[deprecated(since = "56.0.0", note = "use `UdafDisplayNameBuilder` instead")]
1385pub fn udaf_default_display_name<F: AggregateUDFImpl + ?Sized>(
1386    func: &F,
1387    params: &AggregateFunctionParams,
1388) -> Result<String> {
1389    UdafDisplayNameBuilder::new(func.name(), params).build()
1390}
1391
1392/// Builds the default implementation of [`AggregateUDFImpl::window_function_display_name`].
1393///
1394/// # Example
1395/// ```
1396/// # use datafusion_expr::{col, WindowFrame};
1397/// # use datafusion_expr::expr::WindowFunctionParams;
1398/// # use datafusion_expr::UdafWindowFunctionDisplayNameBuilder;
1399/// # let params = WindowFunctionParams {
1400/// #     args: vec![col("x")],
1401/// #     partition_by: vec![col("y")],
1402/// #     order_by: vec![],
1403/// #     window_frame: WindowFrame::new(None),
1404/// #     filter: None,
1405/// #     null_treatment: None,
1406/// #     distinct: false,
1407/// # };
1408/// let display_name = UdafWindowFunctionDisplayNameBuilder::new("my_udaf", &params)
1409///     .build()
1410///     .unwrap();
1411/// assert_eq!(
1412///     display_name,
1413///     "my_udaf(x) PARTITION BY [y] ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING"
1414/// );
1415/// ```
1416#[derive(Debug)]
1417pub struct UdafWindowFunctionDisplayNameBuilder<'a> {
1418    name: &'a str,
1419    params: &'a WindowFunctionParams,
1420}
1421
1422impl<'a> UdafWindowFunctionDisplayNameBuilder<'a> {
1423    /// Create a new builder for the function named `name`
1424    /// (the result of [`AggregateUDFImpl::name`])
1425    pub fn new(name: &'a str, params: &'a WindowFunctionParams) -> Self {
1426        Self { name, params }
1427    }
1428
1429    /// Build the display name
1430    pub fn build(self) -> Result<String> {
1431        let Self { name, params } = self;
1432
1433        let WindowFunctionParams {
1434            args,
1435            partition_by,
1436            order_by,
1437            window_frame,
1438            filter,
1439            null_treatment,
1440            distinct,
1441        } = params;
1442
1443        let mut display_name = String::new();
1444
1445        if *distinct {
1446            display_name.write_fmt(format_args!(
1447                "{}(DISTINCT {})",
1448                name,
1449                expr_vec_fmt!(args)
1450            ))?;
1451        } else {
1452            display_name.write_fmt(format_args!("{}({})", name, expr_vec_fmt!(args)))?;
1453        }
1454
1455        if let Some(null_treatment) = null_treatment {
1456            display_name.write_fmt(format_args!(" {null_treatment}"))?;
1457        }
1458
1459        if let Some(fe) = filter {
1460            display_name.write_fmt(format_args!(" FILTER (WHERE {fe})"))?;
1461        }
1462
1463        if !partition_by.is_empty() {
1464            display_name.write_fmt(format_args!(
1465                " PARTITION BY [{}]",
1466                expr_vec_fmt!(partition_by)
1467            ))?;
1468        }
1469
1470        if !order_by.is_empty() {
1471            display_name
1472                .write_fmt(format_args!(" ORDER BY [{}]", expr_vec_fmt!(order_by)))?;
1473        }
1474
1475        display_name.write_fmt(format_args!(
1476            " {} BETWEEN {} AND {}",
1477            window_frame.units, window_frame.start_bound, window_frame.end_bound
1478        ))?;
1479
1480        Ok(display_name)
1481    }
1482}
1483
1484/// Encapsulates default implementation of [`AggregateUDFImpl::window_function_display_name`].
1485#[deprecated(
1486    since = "56.0.0",
1487    note = "use `UdafWindowFunctionDisplayNameBuilder` instead"
1488)]
1489pub fn udaf_default_window_function_display_name<F: AggregateUDFImpl + ?Sized>(
1490    func: &F,
1491    params: &WindowFunctionParams,
1492) -> Result<String> {
1493    UdafWindowFunctionDisplayNameBuilder::new(func.name(), params).build()
1494}
1495
1496/// Encapsulates default implementation of [`AggregateUDFImpl::return_field`].
1497pub fn udaf_default_return_field<F: AggregateUDFImpl + ?Sized>(
1498    func: &F,
1499    arg_fields: &[FieldRef],
1500) -> Result<FieldRef> {
1501    let arg_types: Vec<_> = arg_fields.iter().map(|f| f.data_type()).cloned().collect();
1502    let data_type = func.return_type(&arg_types)?;
1503
1504    Ok(Arc::new(Field::new(
1505        func.name(),
1506        data_type,
1507        #[expect(deprecated)]
1508        func.is_nullable(),
1509    )))
1510}
1511
1512pub enum ReversedUDAF {
1513    /// The expression is the same as the original expression, like SUM, COUNT
1514    Identical,
1515    /// The expression does not support reverse calculation
1516    NotSupported,
1517    /// The expression is different from the original expression
1518    Reversed(Arc<AggregateUDF>),
1519}
1520
1521/// AggregateUDF that adds an alias to the underlying function. It is better to
1522/// implement [`AggregateUDFImpl`], which supports aliases, directly if possible.
1523#[derive(Debug, PartialEq, Eq, Hash)]
1524struct AliasedAggregateUDFImpl {
1525    inner: UdfEq<Arc<dyn AggregateUDFImpl>>,
1526    aliases: Vec<String>,
1527}
1528
1529impl AliasedAggregateUDFImpl {
1530    pub fn new(
1531        inner: Arc<dyn AggregateUDFImpl>,
1532        new_aliases: impl IntoIterator<Item = &'static str>,
1533    ) -> Self {
1534        let mut aliases = inner.aliases().to_vec();
1535        aliases.extend(new_aliases.into_iter().map(|s| s.to_string()));
1536
1537        Self {
1538            inner: inner.into(),
1539            aliases,
1540        }
1541    }
1542}
1543
1544#[warn(clippy::missing_trait_methods)] // Delegates, so it should implement every single trait method
1545impl AggregateUDFImpl for AliasedAggregateUDFImpl {
1546    fn name(&self) -> &str {
1547        self.inner.name()
1548    }
1549
1550    fn signature(&self) -> &Signature {
1551        self.inner.signature()
1552    }
1553
1554    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
1555        self.inner.return_type(arg_types)
1556    }
1557
1558    fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
1559        self.inner.accumulator(acc_args)
1560    }
1561
1562    fn aliases(&self) -> &[String] {
1563        &self.aliases
1564    }
1565
1566    fn schema_name(&self, params: &AggregateFunctionParams) -> Result<String> {
1567        self.inner.schema_name(params)
1568    }
1569
1570    fn human_display(&self, params: &AggregateFunctionParams) -> Result<String> {
1571        self.inner.human_display(params)
1572    }
1573
1574    fn window_function_schema_name(
1575        &self,
1576        params: &WindowFunctionParams,
1577    ) -> Result<String> {
1578        self.inner.window_function_schema_name(params)
1579    }
1580
1581    fn display_name(&self, params: &AggregateFunctionParams) -> Result<String> {
1582        self.inner.display_name(params)
1583    }
1584
1585    fn window_function_display_name(
1586        &self,
1587        params: &WindowFunctionParams,
1588    ) -> Result<String> {
1589        self.inner.window_function_display_name(params)
1590    }
1591
1592    fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
1593        self.inner.state_fields(args)
1594    }
1595
1596    fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool {
1597        self.inner.groups_accumulator_supported(args)
1598    }
1599
1600    fn groups_accumulator_supported_for_types(
1601        &self,
1602        arg_types: &[DataType],
1603        is_distinct: bool,
1604    ) -> Option<bool> {
1605        self.inner
1606            .groups_accumulator_supported_for_types(arg_types, is_distinct)
1607    }
1608
1609    fn create_groups_accumulator(
1610        &self,
1611        args: AccumulatorArgs,
1612    ) -> Result<Box<dyn GroupsAccumulator>> {
1613        self.inner.create_groups_accumulator(args)
1614    }
1615
1616    fn create_sliding_accumulator(
1617        &self,
1618        args: AccumulatorArgs,
1619    ) -> Result<Box<dyn Accumulator>> {
1620        self.inner.create_sliding_accumulator(args)
1621    }
1622
1623    fn with_beneficial_ordering(
1624        self: Arc<Self>,
1625        beneficial_ordering: bool,
1626    ) -> Result<Option<Arc<dyn AggregateUDFImpl>>> {
1627        Arc::clone(&self.inner)
1628            .with_beneficial_ordering(beneficial_ordering)
1629            .map(|udf| {
1630                udf.map(|udf| {
1631                    Arc::new(AliasedAggregateUDFImpl {
1632                        inner: udf.into(),
1633                        aliases: self.aliases.clone(),
1634                    }) as Arc<dyn AggregateUDFImpl>
1635                })
1636            })
1637    }
1638
1639    fn order_sensitivity(&self) -> AggregateOrderSensitivity {
1640        self.inner.order_sensitivity()
1641    }
1642
1643    fn simplify(&self) -> Option<AggregateFunctionSimplification> {
1644        self.inner.simplify()
1645    }
1646
1647    fn simplify_expr_op_literal(
1648        &self,
1649        agg_function: &AggregateFunction,
1650        arg: &Expr,
1651        op: Operator,
1652        lit: &Expr,
1653        arg_is_left: bool,
1654    ) -> Result<Option<Expr>> {
1655        self.inner
1656            .simplify_expr_op_literal(agg_function, arg, op, lit, arg_is_left)
1657    }
1658
1659    fn reverse_expr(&self) -> ReversedUDAF {
1660        self.inner.reverse_expr()
1661    }
1662
1663    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
1664        self.inner.coerce_types(arg_types)
1665    }
1666
1667    fn return_field(&self, arg_fields: &[FieldRef]) -> Result<FieldRef> {
1668        self.inner.return_field(arg_fields)
1669    }
1670
1671    fn is_nullable(&self) -> bool {
1672        #[expect(deprecated)]
1673        self.inner.is_nullable()
1674    }
1675
1676    fn is_descending(&self) -> Option<bool> {
1677        self.inner.is_descending()
1678    }
1679
1680    fn value_from_stats(&self, statistics_args: &StatisticsArgs) -> Option<ScalarValue> {
1681        self.inner.value_from_stats(statistics_args)
1682    }
1683
1684    fn default_value(&self, data_type: &DataType) -> Result<ScalarValue> {
1685        self.inner.default_value(data_type)
1686    }
1687
1688    fn supports_null_handling_clause(&self) -> bool {
1689        self.inner.supports_null_handling_clause()
1690    }
1691
1692    fn supports_within_group_clause(&self) -> bool {
1693        self.inner.supports_within_group_clause()
1694    }
1695
1696    fn set_monotonicity(&self, data_type: &DataType) -> SetMonotonicity {
1697        self.inner.set_monotonicity(data_type)
1698    }
1699
1700    fn distinct_handling(&self) -> DistinctHandling {
1701        self.inner.distinct_handling()
1702    }
1703
1704    fn documentation(&self) -> Option<&Documentation> {
1705        self.inner.documentation()
1706    }
1707}
1708
1709/// Indicates whether an aggregation function is monotonic as a set
1710/// function. A set function is monotonically increasing if its value
1711/// increases as its argument grows (as a set). Formally, `f` is a
1712/// monotonically increasing set function if `f(S) >= f(T)` whenever `S`
1713/// is a superset of `T`.
1714///
1715/// For example `COUNT` and `MAX` are monotonically increasing as their
1716/// values always increase (or stay the same) as new values are seen. On
1717/// the other hand, `MIN` is monotonically decreasing as its value always
1718/// decreases or stays the same as new values are seen.
1719#[derive(Debug, Clone, PartialEq)]
1720pub enum SetMonotonicity {
1721    /// Aggregate value increases or stays the same as the input set grows.
1722    Increasing,
1723    /// Aggregate value decreases or stays the same as the input set grows.
1724    Decreasing,
1725    /// Aggregate value may increase, decrease, or stay the same as the input
1726    /// set grows.
1727    NotMonotonic,
1728}
1729
1730/// How an aggregate function treats the `DISTINCT` modifier.
1731///
1732/// Mathematically, `Insensitive` means the function's merge operation is
1733/// idempotent (its state forms a semilattice): f(S ⊎ S) = f(S), so
1734/// removing duplicates from the input cannot change the result.
1735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1736#[non_exhaustive]
1737pub enum DistinctHandling {
1738    /// The result is the same with or without `DISTINCT`, so the planner
1739    /// is free to drop it. `min`, `max`, `bool_and`, `bit_or`, ...
1740    Insensitive,
1741    /// The accumulator reads `AccumulatorArgs::is_distinct` and deduplicates
1742    /// its input, so the planner must leave the flag alone. `count`, `sum`,
1743    /// `avg`, `var_samp`, `array_agg`, ... This is the default.
1744    Sensitive,
1745    /// The accumulator does not implement `DISTINCT`: it does not read
1746    /// `is_distinct`, or it rejects `DISTINCT` with an error. The planner has
1747    /// to deduplicate the input first (today `SingleDistinctToGroupBy` does
1748    /// that for single-argument functions) or reject the query. `stddev`,
1749    /// `approx_median`, `corr`, `regr_*`, `nth_value`, ...
1750    Unsupported,
1751}
1752
1753#[cfg(test)]
1754mod test {
1755    use crate::{AggregateUDF, AggregateUDFImpl};
1756    use arrow::array::ArrayRef;
1757    use arrow::datatypes::{DataType, Field, FieldRef, Schema};
1758    use datafusion_common::{Result, ScalarValue, not_impl_err};
1759    use datafusion_expr_common::accumulator::Accumulator;
1760    use datafusion_expr_common::signature::{Signature, Volatility};
1761    use datafusion_functions_aggregate_common::accumulator::{
1762        AccumulatorArgs, StateFieldsArgs,
1763    };
1764    use std::cmp::Ordering;
1765    use std::hash::{DefaultHasher, Hash, Hasher};
1766    use std::sync::Arc;
1767
1768    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1769    struct AMeanUdf {
1770        signature: Signature,
1771    }
1772
1773    impl AMeanUdf {
1774        fn new() -> Self {
1775            Self {
1776                signature: Signature::uniform(
1777                    1,
1778                    vec![DataType::Float64],
1779                    Volatility::Immutable,
1780                ),
1781            }
1782        }
1783    }
1784
1785    impl AggregateUDFImpl for AMeanUdf {
1786        fn name(&self) -> &str {
1787            "a"
1788        }
1789        fn signature(&self) -> &Signature {
1790            &self.signature
1791        }
1792        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
1793            unimplemented!()
1794        }
1795        fn accumulator(
1796            &self,
1797            _acc_args: AccumulatorArgs,
1798        ) -> Result<Box<dyn Accumulator>> {
1799            unimplemented!()
1800        }
1801        fn state_fields(&self, _args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
1802            unimplemented!()
1803        }
1804    }
1805
1806    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1807    struct BMeanUdf {
1808        signature: Signature,
1809    }
1810    impl BMeanUdf {
1811        fn new() -> Self {
1812            Self {
1813                signature: Signature::uniform(
1814                    1,
1815                    vec![DataType::Float64],
1816                    Volatility::Immutable,
1817                ),
1818            }
1819        }
1820    }
1821
1822    impl AggregateUDFImpl for BMeanUdf {
1823        fn name(&self) -> &str {
1824            "b"
1825        }
1826        fn signature(&self) -> &Signature {
1827            &self.signature
1828        }
1829        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
1830            unimplemented!()
1831        }
1832        fn accumulator(
1833            &self,
1834            _acc_args: AccumulatorArgs,
1835        ) -> Result<Box<dyn Accumulator>> {
1836            unimplemented!()
1837        }
1838        fn state_fields(&self, _args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
1839            unimplemented!()
1840        }
1841    }
1842
1843    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1844    struct DefaultStateFieldsUdf {
1845        signature: Signature,
1846    }
1847
1848    impl DefaultStateFieldsUdf {
1849        fn new() -> Self {
1850            Self {
1851                signature: Signature::uniform(
1852                    1,
1853                    vec![DataType::Float64],
1854                    Volatility::Immutable,
1855                ),
1856            }
1857        }
1858    }
1859
1860    impl AggregateUDFImpl for DefaultStateFieldsUdf {
1861        fn name(&self) -> &str {
1862            "default_state_fields"
1863        }
1864
1865        fn signature(&self) -> &Signature {
1866            &self.signature
1867        }
1868
1869        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
1870            unimplemented!()
1871        }
1872
1873        fn accumulator(
1874            &self,
1875            _acc_args: AccumulatorArgs,
1876        ) -> Result<Box<dyn Accumulator>> {
1877            unimplemented!()
1878        }
1879    }
1880
1881    /// Panics if driven: the test only checks which inner method is forwarded to.
1882    #[derive(Debug)]
1883    struct PanicAccumulator;
1884
1885    impl Accumulator for PanicAccumulator {
1886        fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
1887            unimplemented!()
1888        }
1889        fn evaluate(&mut self) -> Result<ScalarValue> {
1890            unimplemented!()
1891        }
1892        fn size(&self) -> usize {
1893            size_of::<Self>()
1894        }
1895        fn state(&mut self) -> Result<Vec<ScalarValue>> {
1896            unimplemented!()
1897        }
1898        fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
1899            unimplemented!()
1900        }
1901    }
1902
1903    /// Distinguishable accumulators: the plain one fails, the sliding one succeeds.
1904    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1905    struct SlidingOnlyUdf {
1906        signature: Signature,
1907    }
1908
1909    impl SlidingOnlyUdf {
1910        fn new() -> Self {
1911            Self {
1912                signature: Signature::uniform(
1913                    1,
1914                    vec![DataType::Float64],
1915                    Volatility::Immutable,
1916                ),
1917            }
1918        }
1919    }
1920
1921    impl AggregateUDFImpl for SlidingOnlyUdf {
1922        fn name(&self) -> &str {
1923            "sliding_only"
1924        }
1925        fn signature(&self) -> &Signature {
1926            &self.signature
1927        }
1928        fn return_type(&self, _args: &[DataType]) -> Result<DataType> {
1929            Ok(DataType::Int64)
1930        }
1931        fn accumulator(
1932            &self,
1933            _acc_args: AccumulatorArgs,
1934        ) -> Result<Box<dyn Accumulator>> {
1935            not_impl_err!("no plain accumulator")
1936        }
1937        fn create_sliding_accumulator(
1938            &self,
1939            _args: AccumulatorArgs,
1940        ) -> Result<Box<dyn Accumulator>> {
1941            Ok(Box::new(PanicAccumulator))
1942        }
1943        fn state_fields(&self, _args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
1944            unimplemented!()
1945        }
1946    }
1947
1948    #[test]
1949    fn test_aliased_udaf_forwards_create_sliding_accumulator() {
1950        let udaf = AggregateUDF::from(SlidingOnlyUdf::new()).with_aliases(["some_alias"]);
1951
1952        let schema = Schema::empty();
1953        let args = || AccumulatorArgs {
1954            return_field: Arc::new(Field::new("f", DataType::Int64, true)),
1955            schema: &schema,
1956            expr_fields: &[],
1957            ignore_nulls: false,
1958            order_bys: &[],
1959            is_reversed: false,
1960            name: "sliding_only",
1961            is_distinct: false,
1962            exprs: &[],
1963        };
1964
1965        // Asserting both directions proves the wrapper distinguishes the two
1966        // methods rather than routing both to the same one.
1967        let sliding = udaf.create_sliding_accumulator(args());
1968        assert!(
1969            sliding.is_ok(),
1970            "aliased UDAF must forward create_sliding_accumulator to the inner UDAF, got: {:?}",
1971            sliding.err()
1972        );
1973        assert!(udaf.accumulator(args()).is_err());
1974
1975        assert!(udaf.aliases().iter().any(|a| a == "some_alias"));
1976    }
1977
1978    #[test]
1979    fn test_partial_eq() {
1980        let a1 = AggregateUDF::from(AMeanUdf::new());
1981        let a2 = AggregateUDF::from(AMeanUdf::new());
1982        let eq = a1 == a2;
1983        assert!(eq);
1984        assert_eq!(a1, a2);
1985        assert_eq!(hash(a1), hash(a2));
1986    }
1987
1988    #[test]
1989    fn test_partial_ord() {
1990        // Test validates that partial ord is defined for AggregateUDF using the name and signature,
1991        // not intended to exhaustively test all possibilities
1992        let a1 = AggregateUDF::from(AMeanUdf::new());
1993        let a2 = AggregateUDF::from(AMeanUdf::new());
1994        assert_eq!(a1.partial_cmp(&a2), Some(Ordering::Equal));
1995
1996        let b1 = AggregateUDF::from(BMeanUdf::new());
1997        assert!(a1 < b1);
1998        assert!(!(a1 == b1));
1999    }
2000
2001    fn hash<T: Hash>(value: T) -> u64 {
2002        let hasher = &mut DefaultHasher::new();
2003        value.hash(hasher);
2004        hasher.finish()
2005    }
2006
2007    #[test]
2008    fn test_default_state_fields_namespaces_ordering_fields() -> Result<()> {
2009        let udf = DefaultStateFieldsUdf::new();
2010
2011        let input_fields = vec![Arc::new(Field::new("value", DataType::Float64, true))];
2012
2013        let ordering_fields = vec![
2014            Arc::new(Field::new("timestamp@0", DataType::Int64, true)),
2015            Arc::new(Field::new("timestamp@0", DataType::Int64, true)),
2016        ];
2017
2018        let fields = udf.state_fields(StateFieldsArgs {
2019            name: "my_agg(value)",
2020            input_fields: &input_fields,
2021            return_field: Arc::new(Field::new("result", DataType::Float64, true)),
2022            ordering_fields: &ordering_fields,
2023            is_distinct: false,
2024        })?;
2025
2026        let names: Vec<_> = fields.iter().map(|f| f.name().as_str()).collect();
2027
2028        assert_eq!(
2029            names,
2030            vec![
2031                "my_agg(value)[value]",
2032                "my_agg(value)[ordering_0]",
2033                "my_agg(value)[ordering_1]",
2034            ]
2035        );
2036
2037        Ok(())
2038    }
2039}