Skip to main content

datafusion_expr/
udf.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//! [`ScalarUDF`]: Scalar User Defined Functions
6
7use crate::async_udf::AsyncScalarUDF;
8use crate::expr::schema_name_from_exprs_comma_separated_without_space;
9use crate::preimage::PreimageResult;
10use crate::simplify::{ExprSimplifyResult, SimplifyContext};
11use crate::sort_properties::{ExprProperties, SortProperties};
12use crate::udf_eq::UdfEq;
13use crate::{ColumnarValue, Documentation, Expr, Signature};
14use arrow::datatypes::{DataType, Field, FieldRef};
15#[cfg(debug_assertions)]
16use datafusion_common::assert_or_internal_err;
17use datafusion_common::config::ConfigOptions;
18use datafusion_common::{Result, ScalarValue, not_impl_err};
19use datafusion_expr_common::dyn_eq::{DynEq, DynHash};
20use datafusion_expr_common::interval_arithmetic::Interval;
21use datafusion_expr_common::placement::ExpressionPlacement;
22use std::any::Any;
23use std::cmp::Ordering;
24use std::fmt::Debug;
25use std::hash::{Hash, Hasher};
26use std::sync::Arc;
27
28/// Describes how a struct-producing UDF's output fields correspond to its
29/// input arguments. This enables the optimizer to propagate orderings
30/// through struct projections (e.g., so that sorting by a struct field
31/// can be recognized as equivalent to sorting by the source column).
32///
33/// See [`ScalarUDFImpl::struct_field_mapping`] for details.
34pub struct StructFieldMapping {
35    /// The UDF used to construct field access expressions on the output.
36    /// For example, the `get_field` UDF for accessing struct fields.
37    pub field_accessor: Arc<ScalarUDF>,
38    /// For each output field: the literal arguments to pass to the
39    /// `field_accessor` UDF (after the base expression), and the index
40    /// of the corresponding input argument that produces the field's value.
41    ///
42    /// For `named_struct('a', col1, 'b', col2)`, this would be:
43    /// `[(["a"], 1), (["b"], 3)]` — field `"a"` comes from arg index 1.
44    pub fields: Vec<(Vec<ScalarValue>, usize)>,
45}
46
47/// Logical representation of a Scalar User Defined Function.
48///
49/// A scalar function produces a single row output for each row of input. This
50/// struct contains the information DataFusion needs to plan and invoke
51/// functions you supply such as name, type signature, return type, and actual
52/// implementation.
53///
54/// 1. For simple use cases, use [`create_udf`] (examples in [`simple_udf.rs`]).
55///
56/// 2. For advanced use cases, use [`ScalarUDFImpl`] which provides full API
57///    access (examples in  [`advanced_udf.rs`]).
58///
59/// See [`Self::call`] to create an `Expr` which invokes a `ScalarUDF` with arguments.
60///
61/// # API Note
62///
63/// This is a separate struct from [`ScalarUDFImpl`] to maintain backwards
64/// compatibility with the older API.
65///
66/// [`create_udf`]: crate::expr_fn::create_udf
67/// [`simple_udf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/udf/simple_udf.rs
68/// [`advanced_udf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/udf/advanced_udf.rs
69#[derive(Debug, Clone)]
70pub struct ScalarUDF {
71    inner: Arc<dyn ScalarUDFImpl>,
72}
73
74impl PartialEq for ScalarUDF {
75    fn eq(&self, other: &Self) -> bool {
76        self.inner.as_ref().dyn_eq(other.inner.as_ref() as &dyn Any)
77    }
78}
79
80impl PartialOrd for ScalarUDF {
81    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
82        let mut cmp = self.name().cmp(other.name());
83        if cmp == Ordering::Equal {
84            cmp = self.signature().partial_cmp(other.signature())?;
85        }
86        if cmp == Ordering::Equal {
87            cmp = self.aliases().partial_cmp(other.aliases())?;
88        }
89        // Contract for PartialOrd and PartialEq consistency requires that
90        // a == b if and only if partial_cmp(a, b) == Some(Equal).
91        if cmp == Ordering::Equal && self != other {
92            // Functions may have other properties besides name and signature
93            // that differentiate two instances (e.g. type, or arbitrary parameters).
94            // We cannot return Some(Equal) in such case.
95            return None;
96        }
97        debug_assert!(
98            cmp == Ordering::Equal || self != other,
99            "Detected incorrect implementation of PartialEq when comparing functions: '{}' and '{}'. \
100            The functions compare as equal, but they are not equal based on general properties that \
101            the PartialOrd implementation observes,",
102            self.name(),
103            other.name()
104        );
105        Some(cmp)
106    }
107}
108
109impl Eq for ScalarUDF {}
110
111impl Hash for ScalarUDF {
112    fn hash<H: Hasher>(&self, state: &mut H) {
113        self.inner.dyn_hash(state)
114    }
115}
116
117impl ScalarUDF {
118    /// Create a new `ScalarUDF` from a `[ScalarUDFImpl]` trait object
119    ///
120    /// Note this is the same as using the `From` impl (`ScalarUDF::from`)
121    pub fn new_from_impl<F>(fun: F) -> ScalarUDF
122    where
123        F: ScalarUDFImpl + 'static,
124    {
125        Self::new_from_shared_impl(Arc::new(fun))
126    }
127
128    /// Create a new `ScalarUDF` from a `[ScalarUDFImpl]` trait object
129    pub fn new_from_shared_impl(fun: Arc<dyn ScalarUDFImpl>) -> ScalarUDF {
130        Self { inner: fun }
131    }
132
133    /// Return the underlying [`ScalarUDFImpl`] trait object for this function
134    pub fn inner(&self) -> &Arc<dyn ScalarUDFImpl> {
135        &self.inner
136    }
137
138    /// Adds additional names that can be used to invoke this function, in
139    /// addition to `name`
140    ///
141    /// If you implement [`ScalarUDFImpl`] directly you should return aliases directly.
142    pub fn with_aliases(self, aliases: impl IntoIterator<Item = &'static str>) -> Self {
143        Self::new_from_impl(AliasedScalarUDFImpl::new(Arc::clone(&self.inner), aliases))
144    }
145
146    /// Returns a [`Expr`] logical expression to call this UDF with specified
147    /// arguments.
148    ///
149    /// This utility allows easily calling UDFs
150    ///
151    /// # Example
152    /// ```no_run
153    /// use datafusion_expr::{col, lit, ScalarUDF};
154    /// # fn my_udf() -> ScalarUDF { unimplemented!() }
155    /// let my_func: ScalarUDF = my_udf();
156    /// // Create an expr for `my_func(a, 12.3)`
157    /// let expr = my_func.call(vec![col("a"), lit(12.3)]);
158    /// ```
159    pub fn call(&self, args: Vec<Expr>) -> Expr {
160        Expr::ScalarFunction(crate::expr::ScalarFunction::new_udf(
161            Arc::new(self.clone()),
162            args,
163        ))
164    }
165
166    /// Returns this function's name.
167    ///
168    /// See [`ScalarUDFImpl::name`] for more details.
169    pub fn name(&self) -> &str {
170        self.inner.name()
171    }
172
173    /// Returns this function's schema_name.
174    ///
175    /// See [`ScalarUDFImpl::schema_name`] for more details
176    pub fn schema_name(&self, args: &[Expr]) -> Result<String> {
177        self.inner.schema_name(args)
178    }
179
180    /// Returns the aliases for this function.
181    ///
182    /// See [`ScalarUDF::with_aliases`] for more details
183    pub fn aliases(&self) -> &[String] {
184        self.inner.aliases()
185    }
186
187    /// Returns true if this function always returns NULL when any argument is
188    /// NULL.
189    ///
190    /// See [`ScalarUDFImpl::is_strict`] for more details.
191    pub fn is_strict(&self) -> bool {
192        self.inner.is_strict()
193    }
194
195    /// Returns this function's [`Signature`] (what input types are accepted).
196    ///
197    /// See [`ScalarUDFImpl::signature`] for more details.
198    pub fn signature(&self) -> &Signature {
199        self.inner.signature()
200    }
201
202    /// The datatype this function returns given the input argument types.
203    /// This function is used when the input arguments are [`DataType`]s.
204    ///
205    ///  # Notes
206    ///
207    /// If a function implement [`ScalarUDFImpl::return_field_from_args`],
208    /// its [`ScalarUDFImpl::return_type`] should raise an error.
209    ///
210    /// See [`ScalarUDFImpl::return_type`] for more details.
211    pub fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
212        self.inner.return_type(arg_types)
213    }
214
215    /// Return the datatype this function returns given the input argument types.
216    ///
217    /// See [`ScalarUDFImpl::return_field_from_args`] for more details.
218    pub fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
219        self.inner.return_field_from_args(args)
220    }
221
222    /// Returns whether this scalar function should be evaluated during
223    /// constant folding for the specified literal arguments.
224    pub fn should_evaluate_const(&self, args: &[&ScalarValue]) -> bool {
225        self.inner.should_evaluate_const(args)
226    }
227
228    /// Returns this scalar function's simplification result.
229    ///
230    /// See [`ScalarUDFImpl::simplify`] for more details.
231    pub fn simplify(
232        &self,
233        args: Vec<Expr>,
234        info: &SimplifyContext,
235    ) -> Result<ExprSimplifyResult> {
236        self.inner.simplify(args, info)
237    }
238
239    /// Return a preimage
240    ///
241    /// See [`ScalarUDFImpl::preimage`] for more details.
242    pub fn preimage(
243        &self,
244        args: &[Expr],
245        lit_expr: &Expr,
246        info: &SimplifyContext,
247    ) -> Result<PreimageResult> {
248        self.inner.preimage(args, lit_expr, info)
249    }
250
251    /// Invoke the function on `args`, returning the appropriate result.
252    ///
253    /// See [`ScalarUDFImpl::invoke_with_args`] for details.
254    pub fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
255        #[cfg(debug_assertions)]
256        let return_field = Arc::clone(&args.return_field);
257        let result = self.inner.invoke_with_args(args)?;
258        // Maybe this could be enabled always?
259        // This doesn't use debug_assert!, but it's meant to run anywhere except on production. It's same in spirit, thus conditioning on debug_assertions.
260        #[cfg(debug_assertions)]
261        {
262            let result_data_type = result.data_type();
263            let expected_type = return_field.data_type();
264            assert_or_internal_err!(
265                result_data_type == *expected_type,
266                "Function '{}' returned value of type '{}' while the following type was promised at planning time and expected: '{}'",
267                self.name(),
268                result_data_type,
269                expected_type
270            );
271            // TODO verify return data is non-null when it was promised to be?
272        }
273        Ok(result)
274    }
275
276    /// Determines which of the arguments passed to this function are evaluated eagerly
277    /// and which may be evaluated lazily.
278    ///
279    /// See [ScalarUDFImpl::conditional_arguments] for more information.
280    pub fn conditional_arguments<'a>(
281        &self,
282        args: &'a [Expr],
283    ) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
284        self.inner.conditional_arguments(args)
285    }
286
287    /// Returns true if some of this `exprs` subexpressions may not be evaluated
288    /// and thus any side effects (like divide by zero) may not be encountered.
289    ///
290    /// See [ScalarUDFImpl::short_circuits] for more information.
291    pub fn short_circuits(&self) -> bool {
292        self.inner.short_circuits()
293    }
294
295    /// Computes the output interval for a [`ScalarUDF`], given the input
296    /// intervals.
297    ///
298    /// # Parameters
299    ///
300    /// * `inputs` are the intervals for the inputs (children) of this function.
301    ///
302    /// # Example
303    ///
304    /// If the function is `ABS(a)`, and the input interval is `a: [-3, 2]`,
305    /// then the output interval would be `[0, 3]`.
306    pub fn evaluate_bounds(&self, inputs: &[&Interval]) -> Result<Interval> {
307        self.inner.evaluate_bounds(inputs)
308    }
309
310    /// See [`ScalarUDFImpl::struct_field_mapping`] for more details.
311    pub fn struct_field_mapping(
312        &self,
313        literal_args: &[Option<ScalarValue>],
314    ) -> Option<StructFieldMapping> {
315        self.inner.struct_field_mapping(literal_args)
316    }
317
318    /// Updates bounds for child expressions, given a known interval for this
319    /// function. This is used to propagate constraints down through an expression
320    /// tree.
321    ///
322    /// # Parameters
323    ///
324    /// * `interval` is the currently known interval for this function.
325    /// * `inputs` are the current intervals for the inputs (children) of this function.
326    ///
327    /// # Returns
328    ///
329    /// A `Vec` of new intervals for the children, in order.
330    ///
331    /// If constraint propagation reveals an infeasibility for any child, returns
332    /// [`None`]. If none of the children intervals change as a result of
333    /// propagation, may return an empty vector instead of cloning `children`.
334    /// This is the default (and conservative) return value.
335    ///
336    /// # Example
337    ///
338    /// If the function is `ABS(a)`, the current `interval` is `[4, 5]` and the
339    /// input `a` is given as `[-7, 3]`, then propagation would return `[-5, 3]`.
340    pub fn propagate_constraints(
341        &self,
342        interval: &Interval,
343        inputs: &[&Interval],
344    ) -> Result<Option<Vec<Interval>>> {
345        self.inner.propagate_constraints(interval, inputs)
346    }
347
348    /// Calculates the [`SortProperties`] of this function based on its
349    /// children's properties.
350    pub fn output_ordering(&self, inputs: &[ExprProperties]) -> Result<SortProperties> {
351        self.inner.output_ordering(inputs)
352    }
353
354    /// See [`ScalarUDFImpl::supports_range_key_locality_analysis`] for more details.
355    pub fn supports_range_key_locality_analysis(
356        &self,
357        argument_types: &[DataType],
358        literal_arguments: &[Option<&ScalarValue>],
359    ) -> bool {
360        self.inner
361            .supports_range_key_locality_analysis(argument_types, literal_arguments)
362    }
363
364    pub fn preserves_lex_ordering(&self, inputs: &[ExprProperties]) -> Result<bool> {
365        self.inner.preserves_lex_ordering(inputs)
366    }
367
368    /// See [`ScalarUDFImpl::strictly_order_preserving`] for more details.
369    pub fn strictly_order_preserving(&self, inputs: &[ExprProperties]) -> Result<bool> {
370        self.inner.strictly_order_preserving(inputs)
371    }
372
373    /// See [`ScalarUDFImpl::coerce_types`] for more details.
374    pub fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
375        self.inner.coerce_types(arg_types)
376    }
377
378    /// Returns the documentation for this Scalar UDF.
379    ///
380    /// Documentation can be accessed programmatically as well as
381    /// generating publicly facing documentation.
382    pub fn documentation(&self) -> Option<&Documentation> {
383        self.inner.documentation()
384    }
385
386    /// Return true if this function is an async function
387    pub fn as_async(&self) -> Option<&AsyncScalarUDF> {
388        self.inner().downcast_ref::<AsyncScalarUDF>()
389    }
390
391    /// Returns placement information for this function.
392    ///
393    /// See [`ScalarUDFImpl::placement`] for more details.
394    pub fn placement(&self, args: &[ExpressionPlacement]) -> ExpressionPlacement {
395        self.inner.placement(args)
396    }
397}
398
399impl<F> From<F> for ScalarUDF
400where
401    F: ScalarUDFImpl + 'static,
402{
403    fn from(fun: F) -> Self {
404        Self::new_from_impl(fun)
405    }
406}
407
408/// Arguments passed to [`ScalarUDFImpl::invoke_with_args`] when invoking a
409/// scalar function.
410#[derive(Debug, Clone)]
411pub struct ScalarFunctionArgs {
412    /// The evaluated arguments to the function
413    pub args: Vec<ColumnarValue>,
414    /// Field associated with each arg, if it exists
415    pub arg_fields: Vec<FieldRef>,
416    /// The number of rows in record batch being evaluated
417    pub number_rows: usize,
418    /// The return field of the scalar function returned (from `return_type`
419    /// or `return_field_from_args`) when creating the physical expression
420    /// from the logical expression
421    pub return_field: FieldRef,
422    /// The config options at execution time
423    pub config_options: Arc<ConfigOptions>,
424}
425
426impl ScalarFunctionArgs {
427    /// The return type of the function. See [`Self::return_field`] for more
428    /// details.
429    pub fn return_type(&self) -> &DataType {
430        self.return_field.data_type()
431    }
432}
433
434/// Information about arguments passed to the function
435///
436/// This structure contains metadata about how the function was called
437/// such as the type of the arguments, any scalar arguments and if the
438/// arguments can (ever) be null
439///
440/// See [`ScalarUDFImpl::return_field_from_args`] for more information
441#[derive(Debug)]
442pub struct ReturnFieldArgs<'a> {
443    /// The data types of the arguments to the function
444    pub arg_fields: &'a [FieldRef],
445    /// Is argument `i` to the function a scalar (constant)?
446    ///
447    /// If the argument `i` is not a scalar, it will be None
448    ///
449    /// For example, if a function is called like `my_function(column_a, 5)`
450    /// this field will be `[None, Some(ScalarValue::Int32(Some(5)))]`
451    pub scalar_arguments: &'a [Option<&'a ScalarValue>],
452}
453
454/// Trait for implementing user defined scalar functions.
455///
456/// This trait exposes the full API for implementing user defined functions and
457/// can be used to implement any function.
458///
459/// See [`advanced_udf.rs`] for a full example with complete implementation and
460/// [`ScalarUDF`] for other available options.
461///
462/// [`advanced_udf.rs`]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/udf/advanced_udf.rs
463///
464/// # Basic Example
465/// ```
466/// # use std::any::Any;
467/// # use std::sync::LazyLock;
468/// # use arrow::datatypes::DataType;
469/// # use datafusion_common::{DataFusionError, plan_err, Result};
470/// # use datafusion_expr::{col, ColumnarValue, Documentation, ScalarFunctionArgs, Signature, Volatility};
471/// # use datafusion_expr::{ScalarUDFImpl, ScalarUDF};
472/// # use datafusion_expr::scalar_doc_sections::DOC_SECTION_MATH;
473/// /// This struct for a simple UDF that adds one to an int32
474/// #[derive(Debug, PartialEq, Eq, Hash)]
475/// struct AddOne {
476///   signature: Signature,
477/// }
478///
479/// impl AddOne {
480///   fn new() -> Self {
481///     Self {
482///       signature: Signature::uniform(1, vec![DataType::Int32], Volatility::Immutable),
483///      }
484///   }
485/// }
486///
487/// static DOCUMENTATION: LazyLock<Documentation> = LazyLock::new(|| {
488///         Documentation::builder(DOC_SECTION_MATH, "Add one to an int32", "add_one(2)")
489///             .with_argument("arg1", "The int32 number to add one to")
490///             .build()
491///     });
492///
493/// fn get_doc() -> &'static Documentation {
494///     &DOCUMENTATION
495/// }
496///
497/// /// Implement the ScalarUDFImpl trait for AddOne
498/// impl ScalarUDFImpl for AddOne {
499///    fn name(&self) -> &str { "add_one" }
500///    fn signature(&self) -> &Signature { &self.signature }
501///    fn return_type(&self, args: &[DataType]) -> Result<DataType> {
502///      if !matches!(args.get(0), Some(&DataType::Int32)) {
503///        return plan_err!("add_one only accepts Int32 arguments");
504///      }
505///      Ok(DataType::Int32)
506///    }
507///    // The actual implementation would add one to the argument
508///    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
509///         unimplemented!()
510///    }
511///    fn documentation(&self) -> Option<&Documentation> {
512///         Some(get_doc())
513///     }
514/// }
515///
516/// // Create a new ScalarUDF from the implementation
517/// let add_one = ScalarUDF::from(AddOne::new());
518///
519/// // Call the function `add_one(col)`
520/// let expr = add_one.call(vec![col("a")]);
521/// ```
522pub trait ScalarUDFImpl: Debug + DynEq + DynHash + Send + Sync + Any {
523    /// Returns this function's name
524    fn name(&self) -> &str;
525
526    /// Returns any aliases (alternate names) for this function.
527    ///
528    /// Aliases can be used to invoke the same function using different names.
529    /// For example in some databases `now()` and `current_timestamp()` are
530    /// aliases for the same function. This behavior can be obtained by
531    /// returning `current_timestamp` as an alias for the `now` function.
532    ///
533    /// Note: `aliases` should only include names other than [`Self::name`].
534    /// Defaults to `[]` (no aliases)
535    fn aliases(&self) -> &[String] {
536        &[]
537    }
538
539    /// Returns the name of the column this expression would create
540    ///
541    /// See [`Expr::schema_name`] for details
542    fn schema_name(&self, args: &[Expr]) -> Result<String> {
543        /// Use an inner function to avoid code duplication over all
544        /// generic callsites as the body is the same.
545        fn inner(name: &str, args: &[Expr]) -> Result<String> {
546            Ok(format!(
547                "{}({})",
548                name,
549                schema_name_from_exprs_comma_separated_without_space(args)?
550            ))
551        }
552        inner(self.name(), args)
553    }
554
555    /// Returns a [`Signature`] describing the argument types for which this
556    /// function has an implementation, and the function's [`Volatility`].
557    ///
558    /// See [`Signature`] for more details on argument type handling
559    /// and [`Self::return_type`] for computing the return type.
560    ///
561    /// [`Volatility`]: datafusion_expr_common::signature::Volatility
562    fn signature(&self) -> &Signature;
563
564    /// [`DataType`] returned by this function, given the types of the
565    /// arguments.
566    ///
567    /// # Arguments
568    ///
569    /// `arg_types` Data types of the arguments. The implementation of
570    /// `return_type` can assume that some other part of the code has coerced
571    /// the actual argument types to match [`Self::signature`].
572    ///
573    /// # Notes
574    ///
575    /// If you provide an implementation for [`Self::return_field_from_args`],
576    /// DataFusion will not call `return_type` (this function). While it is
577    /// valid to put [`unimplemented!()`] or [`unreachable!()`], it is
578    /// recommended to return [`DataFusionError::Internal`] instead, which
579    /// reduces the severity of symptoms if bugs occur (an error rather than a
580    /// panic).
581    ///
582    /// [`DataFusionError::Internal`]: datafusion_common::DataFusionError::Internal
583    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType>;
584
585    /// Create a new instance of this function with updated configuration.
586    ///
587    /// This method is called when configuration options change at runtime
588    /// (e.g., via `SET` statements) to allow functions that depend on
589    /// configuration to update themselves accordingly.
590    ///
591    /// Note the current [`ConfigOptions`] are also passed to [`Self::invoke_with_args`] so
592    /// this API is not needed for functions where the values may
593    /// depend on the current options.
594    ///
595    /// This API is useful for functions where the return
596    /// **type** depends on the configuration options, such as the `now()` function
597    /// which depends on the current timezone.
598    ///
599    /// # Arguments
600    ///
601    /// * `config` - The updated configuration options
602    ///
603    /// # Returns
604    ///
605    /// * `Some(ScalarUDF)` - A new instance of this function configured with the new settings
606    /// * `None` - If this function does not change with new configuration settings (the default)
607    fn with_updated_config(&self, _config: &ConfigOptions) -> Option<ScalarUDF> {
608        None
609    }
610
611    /// What type will be returned by this function, given the arguments?
612    ///
613    /// By default, this function calls [`Self::return_type`] with the
614    /// types of each argument.
615    ///
616    /// # Notes
617    ///
618    /// For the majority of UDFs, implementing [`Self::return_type`] is sufficient,
619    /// as the result type is typically a deterministic function of the input types
620    /// (e.g., `sqrt(f32)` consistently yields `f32`). Implementing this method directly
621    /// is generally unnecessary unless the return type depends on runtime values.
622    ///
623    /// This function can be used for more advanced cases such as:
624    ///
625    /// 1. specifying nullability
626    /// 2. return types based on the **values** of the arguments (rather than
627    ///    their **types**.
628    ///
629    /// # Example creating `Field`
630    ///
631    /// Note the name of the [`Field`] is ignored, except for structured types such as
632    /// `DataType::Struct`.
633    ///
634    /// ```rust
635    /// # use std::sync::Arc;
636    /// # use arrow::datatypes::{DataType, Field, FieldRef};
637    /// # use datafusion_common::Result;
638    /// # use datafusion_expr::ReturnFieldArgs;
639    /// # struct Example{}
640    /// # impl Example {
641    /// fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
642    ///     // report output is only nullable if any one of the arguments are nullable
643    ///     let nullable = args.arg_fields.iter().any(|f| f.is_nullable());
644    ///     let field = Arc::new(Field::new("ignored_name", DataType::Int32, nullable));
645    ///     Ok(field)
646    /// }
647    /// # }
648    /// ```
649    ///
650    /// # Output Type based on Values
651    ///
652    /// For example, the following two function calls get the same argument
653    /// types (something and a `Utf8` string) but return different types based
654    /// on the value of the second argument:
655    ///
656    /// * `arrow_cast(x, 'Int16')` --> `Int16`
657    /// * `arrow_cast(x, 'Float32')` --> `Float32`
658    ///
659    /// # Requirements
660    ///
661    /// This function **must** consistently return the same type for the same
662    /// logical input even if the input is simplified (e.g. it must return the same
663    /// value for `('foo' | 'bar')` as it does for ('foobar').
664    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
665        /// Use an inner function to avoid code duplication over all
666        /// generic callsites as the body is the same.
667        fn arg_fields_to_data_types(arg_fields: &[FieldRef]) -> Vec<DataType> {
668            arg_fields.iter().map(|f| f.data_type().clone()).collect()
669        }
670        let data_types = arg_fields_to_data_types(args.arg_fields);
671        let return_type = self.return_type(&data_types)?;
672        Ok(Arc::new(Field::new(self.name(), return_type, true)))
673    }
674
675    /// Returns true if this function always returns NULL when any argument is
676    /// NULL.
677    ///
678    /// Strict functions are NULL-propagating: if any argument evaluates to
679    /// NULL, the function result is guaranteed to be NULL. Optimizer rules can
680    /// use this property when reasoning about expression nullability and
681    /// null-rejecting filters.
682    ///
683    /// Defaults to `false` because user-defined functions may choose to accept
684    /// NULL inputs and produce non-NULL results.
685    fn is_strict(&self) -> bool {
686        false
687    }
688
689    /// Invoke the function returning the appropriate result.
690    ///
691    /// # Performance
692    ///
693    /// For the best performance, the implementations should handle the common case
694    /// when one or more of their arguments are constant values (aka
695    /// [`ColumnarValue::Scalar`]).
696    ///
697    /// [`ColumnarValue::values_to_arrays`] can be used to convert the arguments
698    /// to arrays, which will likely be simpler code, but be slower.
699    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue>;
700
701    /// Returns whether this function should be evaluated during constant
702    /// folding for the specified literal arguments.
703    ///
704    /// Implementations can return `false` when evaluation is valid but may be
705    /// too expensive for planning. The expression is then preserved for
706    /// runtime evaluation. The default preserves the existing behavior of
707    /// evaluating immutable functions with literal arguments.
708    fn should_evaluate_const(&self, _args: &[&ScalarValue]) -> bool {
709        true
710    }
711
712    /// Optionally apply per-UDF simplification / rewrite rules.
713    ///
714    /// This can be used to apply function specific simplification rules during
715    /// optimization (e.g. `arrow_cast` --> `Expr::Cast`). The default
716    /// implementation does nothing.
717    ///
718    /// Note that DataFusion handles simplifying arguments and  "constant
719    /// folding" (replacing a function call with constant arguments such as
720    /// `my_add(1,2) --> 3` ). Thus, there is no need to implement such
721    /// optimizations manually for specific UDFs.
722    ///
723    /// # Arguments
724    /// * `args`: The arguments of the function
725    /// * `info`: The necessary information for simplification
726    ///
727    /// # Returns
728    /// [`ExprSimplifyResult`] indicating the result of the simplification NOTE
729    /// if the function cannot be simplified, the arguments *MUST* be returned
730    /// unmodified
731    ///
732    /// # Notes
733    ///
734    /// The returned expression must have the same schema as the original
735    /// expression, including both the data type and nullability. For example,
736    /// if the original expression is nullable, the returned expression must
737    /// also be nullable, otherwise it may lead to schema verification errors
738    /// later in query planning.
739    fn simplify(
740        &self,
741        args: Vec<Expr>,
742        _info: &SimplifyContext,
743    ) -> Result<ExprSimplifyResult> {
744        Ok(ExprSimplifyResult::Original(args))
745    }
746
747    /// Returns a single contiguous preimage for this function and the specified
748    /// scalar expression, if any.
749    ///
750    /// Currently only applies to `=, !=, >, >=, <, <=, is distinct from, is not distinct from` predicates
751    /// # Return Value
752    ///
753    /// Implementations should return a half-open interval: inclusive lower
754    /// bound and exclusive upper bound. This is slightly different from normal
755    /// [`Interval`] semantics where the upper bound is closed (inclusive).
756    /// Typically this means the upper endpoint must be adjusted to the next
757    /// value not included in the preimage. See the Half-Open Intervals section
758    /// below for more details.
759    ///
760    /// # Background
761    ///
762    /// Inspired by the [ClickHouse Paper], a "preimage rewrite" transforms a
763    /// predicate containing a function call into a predicate containing an
764    /// equivalent set of input literal (constant) values. The resulting
765    /// predicate can often be further optimized by other rewrites (see
766    /// Examples).
767    ///
768    /// From the paper:
769    ///
770    /// > some functions can compute the preimage of a given function result.
771    /// > This is used to replace comparisons of constants with function calls
772    /// > on the key columns by comparing the key column value with the preimage.
773    /// > For example, `toYear(k) = 2024` can be replaced by
774    /// > `k >= 2024-01-01 && k < 2025-01-01`
775    ///
776    /// For example, given an expression like
777    /// ```sql
778    /// date_part('YEAR', k) = 2024
779    /// ```
780    ///
781    /// The interval `[2024-01-01, 2025-12-31`]` contains all possible input
782    /// values (preimage values) for which the function `date_part(YEAR, k)`
783    /// produces the output value `2024` (image value). Returning the interval
784    /// (note upper bound adjusted up) `[2024-01-01, 2025-01-01]` the expression
785    /// can be rewritten to
786    ///
787    /// ```sql
788    /// k >= '2024-01-01' AND k < '2025-01-01'
789    /// ```
790    ///
791    /// which is a simpler and a more canonical form, making it easier for other
792    /// optimizer passes to recognize and apply further transformations.
793    ///
794    /// # Examples
795    ///
796    /// Case 1:
797    ///
798    /// Original:
799    /// ```sql
800    /// date_part('YEAR', k) = 2024 AND k >= '2024-06-01'
801    /// ```
802    ///
803    /// After preimage rewrite:
804    /// ```sql
805    /// k >= '2024-01-01' AND k < '2025-01-01' AND k >= '2024-06-01'
806    /// ```
807    ///
808    /// Since this form is much simpler, the optimizer can combine and simplify
809    /// sub-expressions further into:
810    /// ```sql
811    /// k >= '2024-06-01' AND k < '2025-01-01'
812    /// ```
813    ///
814    /// Case 2:
815    ///
816    /// For min/max pruning, simpler predicates such as:
817    /// ```sql
818    /// k >= '2024-01-01' AND k < '2025-01-01'
819    /// ```
820    /// are much easier for the pruner to reason about. See [PruningPredicate]
821    /// for the backgrounds of predicate pruning.
822    ///
823    /// The trade-off with the preimage rewrite is that evaluating the rewritten
824    /// form might be slightly more expensive than evaluating the original
825    /// expression. In practice, this cost is usually outweighed by the more
826    /// aggressive optimization opportunities it enables.
827    ///
828    /// # Half-Open Intervals
829    ///
830    /// The preimage API uses half-open intervals, which makes the rewrite
831    /// easier to implement by avoiding calculations to adjust the upper bound.
832    /// For example, if a function returns its input unchanged and the desired
833    /// output is the single value `5`, a closed interval could be represented
834    /// as `[5, 5]`, but then the rewrite would require adjusting the upper
835    /// bound to `6` to create a proper range predicate. With a half-open
836    /// interval, the same range is represented as `[5, 6)`, which already
837    /// forms a valid predicate.
838    ///
839    /// [PruningPredicate]: https://docs.rs/datafusion/latest/datafusion/physical_optimizer/pruning/struct.PruningPredicate.html
840    /// [ClickHouse Paper]:  https://www.vldb.org/pvldb/vol17/p3731-schulze.pdf
841    /// [image]: https://en.wikipedia.org/wiki/Image_(mathematics)#Image_of_an_element
842    /// [preimage]: https://en.wikipedia.org/wiki/Image_(mathematics)#Inverse_image
843    fn preimage(
844        &self,
845        _args: &[Expr],
846        _lit_expr: &Expr,
847        _info: &SimplifyContext,
848    ) -> Result<PreimageResult> {
849        Ok(PreimageResult::None)
850    }
851
852    /// Returns true if some of this `exprs` subexpressions may not be evaluated
853    /// and thus any side effects (like divide by zero) may not be encountered.
854    ///
855    /// Setting this to true prevents certain optimizations such as common
856    /// subexpression elimination
857    ///
858    /// When overriding this function to return `true`, [ScalarUDFImpl::conditional_arguments] can also be
859    /// overridden to report more accurately which arguments are eagerly evaluated and which ones
860    /// lazily.
861    fn short_circuits(&self) -> bool {
862        false
863    }
864
865    /// Determines which of the arguments passed to this function are evaluated eagerly
866    /// and which may be evaluated lazily.
867    ///
868    /// If this function returns `None`, all arguments are eagerly evaluated.
869    /// Returning `None` is a micro optimization that saves a needless `Vec`
870    /// allocation.
871    ///
872    /// If the function returns `Some`, returns (`eager`, `lazy`) where `eager`
873    /// are the arguments that are always evaluated, and `lazy` are the
874    /// arguments that may be evaluated lazily (i.e. may not be evaluated at all
875    /// in some cases).
876    ///
877    /// Implementations must ensure that the two returned `Vec`s are disjunct,
878    /// and that each argument from `args` is present in one the two `Vec`s.
879    ///
880    /// When overriding this function, [ScalarUDFImpl::short_circuits] must
881    /// be overridden to return `true`.
882    fn conditional_arguments<'a>(
883        &self,
884        args: &'a [Expr],
885    ) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
886        if self.short_circuits() {
887            Some((vec![], args.iter().collect()))
888        } else {
889            None
890        }
891    }
892
893    /// Computes the output [`Interval`] for a [`ScalarUDFImpl`], given the input
894    /// intervals.
895    ///
896    /// # Parameters
897    ///
898    /// * `children` are the intervals for the children (inputs) of this function.
899    ///
900    /// # Example
901    ///
902    /// If the function is `ABS(a)`, and the input interval is `a: [-3, 2]`,
903    /// then the output interval would be `[0, 3]`.
904    ///
905    /// # Output type
906    ///
907    /// The default implementation returns an unbounded [`DataType::Null`]
908    /// interval because the output type cannot be inferred from input intervals
909    /// alone. During physical property analysis, `ScalarFunctionExpr` uses its
910    /// resolved return type to replace any unbounded [`DataType::Null`]
911    /// interval returned here with a typed unbounded interval when supported,
912    /// including intervals returned by overrides. If the resolved type is not
913    /// supported by [`Interval::make_unbounded`], the original interval is kept.
914    /// UDFs need not override this method solely to preserve their output type
915    /// for that analysis.
916    ///
917    /// Override this method to provide more precise bounds. All intervals other
918    /// than an unbounded [`DataType::Null`] interval are preserved. The fallback
919    /// does not apply to direct calls to `PhysicalExpr::evaluate_bounds`.
920    fn evaluate_bounds(&self, _input: &[&Interval]) -> Result<Interval> {
921        // We cannot assume the input datatype is the same of output type.
922        Interval::make_unbounded(&DataType::Null)
923    }
924
925    /// Updates bounds for child expressions, given a known [`Interval`]s for this
926    /// function.
927    ///
928    /// This function is used to propagate constraints down through an
929    /// expression tree.
930    ///
931    /// # Parameters
932    ///
933    /// * `interval` is the currently known interval for this function.
934    /// * `inputs` are the current intervals for the inputs (children) of this function.
935    ///
936    /// # Returns
937    ///
938    /// A `Vec` of new intervals for the children, in order.
939    ///
940    /// If constraint propagation reveals an infeasibility for any child, returns
941    /// [`None`]. If none of the children intervals change as a result of
942    /// propagation, may return an empty vector instead of cloning `children`.
943    /// This is the default (and conservative) return value.
944    ///
945    /// # Example
946    ///
947    /// If the function is `ABS(a)`, the current `interval` is `[4, 5]` and the
948    /// input `a` is given as `[-7, 3]`, then propagation would return `[-5, 3]`.
949    fn propagate_constraints(
950        &self,
951        _interval: &Interval,
952        _inputs: &[&Interval],
953    ) -> Result<Option<Vec<Interval>>> {
954        Ok(Some(vec![]))
955    }
956
957    /// Calculates the [`SortProperties`] of this function based on its children's properties.
958    fn output_ordering(&self, inputs: &[ExprProperties]) -> Result<SortProperties> {
959        if !self.preserves_lex_ordering(inputs)? {
960            return Ok(SortProperties::Unordered);
961        }
962
963        /// Use an inner function to avoid code duplication over all
964        /// generic callsites as the body is the same.
965        fn inner(inputs: &[ExprProperties]) -> SortProperties {
966            let Some(first_order) = inputs.first().map(|p| &p.sort_properties) else {
967                return SortProperties::Singleton;
968            };
969
970            if inputs
971                .iter()
972                .skip(1)
973                .all(|input| &input.sort_properties == first_order)
974            {
975                *first_order
976            } else {
977                SortProperties::Unordered
978            }
979        }
980        Ok(inner(inputs))
981    }
982
983    /// Returns whether this function has been audited for range-key locality
984    /// analysis with these argument types and literal values.
985    ///
986    /// Range-boundary analysis has subtle correctness requirements, so the
987    /// policy is default-deny. Functions may opt in only after individual audit.
988    /// At minimum, an opted-in combination must:
989    ///
990    /// - have same-direction [`SortProperties::Ordered`] metadata over the
991    ///   admitted non-null domain when all other inputs are singleton;
992    /// - preserve nullness exactly, so successful evaluation returns null if and
993    ///   only if the range input is null.
994    ///
995    /// Callers may then prove key locality by evaluating values on both sides of
996    /// each concrete range split. Ordered metadata alone is insufficient because
997    /// a non-strict transform can collapse a split boundary.
998    ///
999    /// This does not claim a concrete partition layout or cross-input
1000    /// co-partitioning compatibility. Boundary evaluation errors cause the
1001    /// analysis to return `false`. This capability is not transported across FFI.
1002    ///
1003    /// `literal_arguments` has one entry per argument. `None` means the argument
1004    /// is not a literal; `Some(value)` supplies its value, which may itself be
1005    /// NULL. Non-literal expressions are not evaluated to obtain these values.
1006    fn supports_range_key_locality_analysis(
1007        &self,
1008        _argument_types: &[DataType],
1009        _literal_arguments: &[Option<&ScalarValue>],
1010    ) -> bool {
1011        false
1012    }
1013
1014    /// Returns true if the function preserves lexicographical ordering based on
1015    /// the input ordering.
1016    ///
1017    /// See [`ExprProperties::preserves_lex_ordering`] for more details
1018    fn preserves_lex_ordering(&self, _inputs: &[ExprProperties]) -> Result<bool> {
1019        Ok(false)
1020    }
1021
1022    /// Returns true if the function is strictly order-preserving with respect
1023    /// to its `Ordered` inputs, i.e. `a.cmp(b) == f(a).cmp(f(b))`.
1024    ///
1025    /// See [`ExprProperties::strictly_order_preserving`] for more details
1026    fn strictly_order_preserving(&self, _inputs: &[ExprProperties]) -> Result<bool> {
1027        Ok(false)
1028    }
1029
1030    /// Coerce arguments of a function call to types that the function can evaluate.
1031    ///
1032    /// This function is only called if [`ScalarUDFImpl::signature`] returns
1033    /// [`crate::TypeSignature::UserDefined`]. Most UDFs should return one of
1034    /// the other variants of [`TypeSignature`] which handle common cases.
1035    ///
1036    /// See the [type coercion module](crate::type_coercion)
1037    /// documentation for more details on type coercion
1038    ///
1039    /// [`TypeSignature`]: crate::TypeSignature
1040    ///
1041    /// For example, if your function requires a floating point arguments, but the user calls
1042    /// it like `my_func(1::int)` (i.e. with `1` as an integer), coerce_types can return `[DataType::Float64]`
1043    /// to ensure the argument is converted to `1::double`
1044    ///
1045    /// # Parameters
1046    /// * `arg_types`: The argument types of the arguments  this function with
1047    ///
1048    /// # Return value
1049    /// A Vec the same length as `arg_types`. DataFusion will `CAST` the function call
1050    /// arguments to these specific types.
1051    fn coerce_types(&self, _arg_types: &[DataType]) -> Result<Vec<DataType>> {
1052        /// Use an inner function to avoid code duplication over all
1053        /// generic callsites as the body is the same.
1054        fn inner(name: &str) -> Result<Vec<DataType>> {
1055            not_impl_err!("Function {name} does not implement coerce_types")
1056        }
1057        inner(self.name())
1058    }
1059
1060    /// For struct-producing functions, return how output fields map to input
1061    /// arguments. This enables the optimizer to propagate orderings through
1062    /// struct projections.
1063    ///
1064    /// `literal_args[i]` is `Some(value)` if argument `i` is a known literal,
1065    /// allowing extraction of field names from arguments like
1066    /// `named_struct('field_name', value, ...)`.
1067    ///
1068    /// For example, `named_struct('a', col1, 'b', col2)` would return a
1069    /// mapping indicating that output field `'a'` (accessed via
1070    /// `get_field(output, 'a')`) corresponds to input argument `col1` at
1071    /// index 1, and field `'b'` corresponds to `col2` at index 3.
1072    fn struct_field_mapping(
1073        &self,
1074        _literal_args: &[Option<ScalarValue>],
1075    ) -> Option<StructFieldMapping> {
1076        None
1077    }
1078
1079    /// Returns the documentation for this Scalar UDF.
1080    ///
1081    /// Documentation can be accessed programmatically as well as generating
1082    /// publicly facing documentation.
1083    fn documentation(&self) -> Option<&Documentation> {
1084        None
1085    }
1086
1087    /// Returns placement information for this function.
1088    ///
1089    /// This is used by optimizers to make decisions about expression placement,
1090    /// such as whether to push expressions down through projections.
1091    ///
1092    /// The default implementation returns [`ExpressionPlacement::KeepInPlace`],
1093    /// meaning the expression should be kept where it is in the plan.
1094    ///
1095    /// Override this method to indicate that the function can be pushed down
1096    /// closer to the data source.
1097    fn placement(&self, _args: &[ExpressionPlacement]) -> ExpressionPlacement {
1098        ExpressionPlacement::KeepInPlace
1099    }
1100}
1101
1102impl dyn ScalarUDFImpl {
1103    /// Returns `true` if the implementation is of type `T`.
1104    ///
1105    /// Works correctly when called on `Arc<dyn ScalarUDFImpl>` via auto-deref.
1106    pub fn is<T: ScalarUDFImpl>(&self) -> bool {
1107        (self as &dyn Any).is::<T>()
1108    }
1109
1110    /// Attempts to downcast to a concrete type `T`, returning `None` if the
1111    /// implementation is not of that type.
1112    ///
1113    /// Works correctly when called on `Arc<dyn ScalarUDFImpl>` via auto-deref,
1114    /// unlike `(&arc as &dyn Any).downcast_ref::<T>()` which would attempt to
1115    /// downcast the `Arc` itself.
1116    pub fn downcast_ref<T: ScalarUDFImpl>(&self) -> Option<&T> {
1117        (self as &dyn Any).downcast_ref()
1118    }
1119}
1120
1121/// ScalarUDF that adds an alias to the underlying function. It is better to
1122/// implement [`ScalarUDFImpl`], which supports aliases, directly if possible.
1123#[derive(Debug, PartialEq, Eq, Hash)]
1124struct AliasedScalarUDFImpl {
1125    inner: UdfEq<Arc<dyn ScalarUDFImpl>>,
1126    aliases: Vec<String>,
1127}
1128
1129impl AliasedScalarUDFImpl {
1130    pub fn new(
1131        inner: Arc<dyn ScalarUDFImpl>,
1132        new_aliases: impl IntoIterator<Item = &'static str>,
1133    ) -> Self {
1134        let mut aliases = inner.aliases().to_vec();
1135        aliases.extend(new_aliases.into_iter().map(|s| s.to_string()));
1136        Self {
1137            inner: inner.into(),
1138            aliases,
1139        }
1140    }
1141}
1142
1143#[warn(clippy::missing_trait_methods)] // Delegates, so it should implement every single trait method
1144impl ScalarUDFImpl for AliasedScalarUDFImpl {
1145    fn name(&self) -> &str {
1146        self.inner.name()
1147    }
1148
1149    fn schema_name(&self, args: &[Expr]) -> Result<String> {
1150        self.inner.schema_name(args)
1151    }
1152
1153    fn signature(&self) -> &Signature {
1154        self.inner.signature()
1155    }
1156
1157    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
1158        self.inner.return_type(arg_types)
1159    }
1160
1161    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
1162        self.inner.return_field_from_args(args)
1163    }
1164
1165    fn is_strict(&self) -> bool {
1166        self.inner.is_strict()
1167    }
1168
1169    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
1170        self.inner.invoke_with_args(args)
1171    }
1172
1173    fn should_evaluate_const(&self, args: &[&ScalarValue]) -> bool {
1174        self.inner.should_evaluate_const(args)
1175    }
1176
1177    fn with_updated_config(&self, _config: &ConfigOptions) -> Option<ScalarUDF> {
1178        None
1179    }
1180
1181    fn aliases(&self) -> &[String] {
1182        &self.aliases
1183    }
1184
1185    fn simplify(
1186        &self,
1187        args: Vec<Expr>,
1188        info: &SimplifyContext,
1189    ) -> Result<ExprSimplifyResult> {
1190        self.inner.simplify(args, info)
1191    }
1192
1193    fn preimage(
1194        &self,
1195        args: &[Expr],
1196        lit_expr: &Expr,
1197        info: &SimplifyContext,
1198    ) -> Result<PreimageResult> {
1199        self.inner.preimage(args, lit_expr, info)
1200    }
1201
1202    fn conditional_arguments<'a>(
1203        &self,
1204        args: &'a [Expr],
1205    ) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
1206        self.inner.conditional_arguments(args)
1207    }
1208
1209    fn short_circuits(&self) -> bool {
1210        self.inner.short_circuits()
1211    }
1212
1213    fn evaluate_bounds(&self, input: &[&Interval]) -> Result<Interval> {
1214        self.inner.evaluate_bounds(input)
1215    }
1216
1217    fn propagate_constraints(
1218        &self,
1219        interval: &Interval,
1220        inputs: &[&Interval],
1221    ) -> Result<Option<Vec<Interval>>> {
1222        self.inner.propagate_constraints(interval, inputs)
1223    }
1224
1225    fn struct_field_mapping(
1226        &self,
1227        literal_args: &[Option<ScalarValue>],
1228    ) -> Option<StructFieldMapping> {
1229        self.inner.struct_field_mapping(literal_args)
1230    }
1231
1232    fn output_ordering(&self, inputs: &[ExprProperties]) -> Result<SortProperties> {
1233        self.inner.output_ordering(inputs)
1234    }
1235
1236    fn supports_range_key_locality_analysis(
1237        &self,
1238        argument_types: &[DataType],
1239        literal_arguments: &[Option<&ScalarValue>],
1240    ) -> bool {
1241        self.inner
1242            .supports_range_key_locality_analysis(argument_types, literal_arguments)
1243    }
1244
1245    fn preserves_lex_ordering(&self, inputs: &[ExprProperties]) -> Result<bool> {
1246        self.inner.preserves_lex_ordering(inputs)
1247    }
1248
1249    fn strictly_order_preserving(&self, inputs: &[ExprProperties]) -> Result<bool> {
1250        self.inner.strictly_order_preserving(inputs)
1251    }
1252
1253    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
1254        self.inner.coerce_types(arg_types)
1255    }
1256
1257    fn documentation(&self) -> Option<&Documentation> {
1258        self.inner.documentation()
1259    }
1260
1261    fn placement(&self, args: &[ExpressionPlacement]) -> ExpressionPlacement {
1262        self.inner.placement(args)
1263    }
1264}
1265
1266#[cfg(test)]
1267mod tests {
1268    use super::*;
1269    use datafusion_expr_common::signature::Volatility;
1270    use std::hash::DefaultHasher;
1271
1272    #[derive(Debug, PartialEq, Eq, Hash)]
1273    struct TestScalarUDFImpl {
1274        name: &'static str,
1275        field: &'static str,
1276        signature: Signature,
1277    }
1278    impl ScalarUDFImpl for TestScalarUDFImpl {
1279        fn name(&self) -> &str {
1280            self.name
1281        }
1282
1283        fn signature(&self) -> &Signature {
1284            &self.signature
1285        }
1286
1287        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
1288            unimplemented!()
1289        }
1290
1291        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
1292            unimplemented!()
1293        }
1294    }
1295
1296    // PartialEq and Hash must be consistent, and also PartialEq and PartialOrd
1297    // must be consistent, so they are tested together.
1298    #[test]
1299    fn test_partial_eq_hash_and_partial_ord() {
1300        // A parameterized function
1301        let f = test_func("foo", "a");
1302
1303        // Same like `f`, different instance
1304        let f2 = test_func("foo", "a");
1305        assert_eq!(f, f2);
1306        assert_eq!(hash(&f), hash(&f2));
1307        assert_eq!(f.partial_cmp(&f2), Some(Ordering::Equal));
1308
1309        // Different parameter
1310        let b = test_func("foo", "b");
1311        assert_ne!(f, b);
1312        assert_ne!(hash(&f), hash(&b)); // hash can collide for different values but does not collide in this test
1313        assert_eq!(f.partial_cmp(&b), None);
1314
1315        // Different name
1316        let o = test_func("other", "a");
1317        assert_ne!(f, o);
1318        assert_ne!(hash(&f), hash(&o)); // hash can collide for different values but does not collide in this test
1319        assert_eq!(f.partial_cmp(&o), Some(Ordering::Less));
1320
1321        // Different name and parameter
1322        assert_ne!(b, o);
1323        assert_ne!(hash(&b), hash(&o)); // hash can collide for different values but does not collide in this test
1324        assert_eq!(b.partial_cmp(&o), Some(Ordering::Less));
1325    }
1326
1327    #[test]
1328    fn range_key_locality_analysis_is_disabled_by_default() {
1329        let function = test_func("range_function", "a");
1330        assert!(!function.supports_range_key_locality_analysis(
1331            &[DataType::Int64],
1332            &[Some(&ScalarValue::Int64(Some(1)))],
1333        ));
1334    }
1335
1336    fn test_func(name: &'static str, parameter: &'static str) -> ScalarUDF {
1337        ScalarUDF::from(TestScalarUDFImpl {
1338            name,
1339            field: parameter,
1340            signature: Signature::any(1, Volatility::Immutable),
1341        })
1342    }
1343
1344    fn hash<T: Hash>(value: &T) -> u64 {
1345        let hasher = &mut DefaultHasher::new();
1346        value.hash(hasher);
1347        hasher.finish()
1348    }
1349}